diff --git a/src/bitmap.cpp b/src/bitmap.cpp index 89ae82875..35c15b0d7 100644 --- a/src/bitmap.cpp +++ b/src/bitmap.cpp @@ -219,8 +219,8 @@ BOOL CBitmap::Enlarge(int width, int height) if (Height > height) height = Height; // try to create a larger bitmap - // !CAUTION! Sal 2.5b6 was slow when painting to Viewer (PgDn) compared to 2.0 - // Caused by creating the cache with CreateBitmap() instead of CreateCompatibleBitmap() + // !CAUTION! Sal 2.5b6 was slow when painting in Viewer (PgDn) compared to 2.0 + // This was caused by creating the cache with CreateBitmap() instead of CreateCompatibleBitmap() // According to MSDN, CreateBitmap() should only be used for B&W bitmaps. HBITMAP hTmpBmp; if (HMemDC == NULL || BlackAndWhite) diff --git a/src/bitmap.h b/src/bitmap.h index 9eed653ec..99e8a9e9d 100644 --- a/src/bitmap.h +++ b/src/bitmap.h @@ -45,8 +45,8 @@ class CBitmap // will be compatible with the screen BOOL ReCreateForScreenDC(int width = -1, int height = -1); - // enlarges the bitmap to desired size; if the bitmap is large enough already, it won't - // be shrinked - just returns TRUE + // enlarges the bitmap to the requested size; if the bitmap is already large enough, + // it does not shrink it and only returns TRUE BOOL Enlarge(int width, int height); // returns TRUE, if the bitmap needs to be enlarged BOOL NeedEnlarge(int width, int height); diff --git a/src/bugreprt.cpp b/src/bugreprt.cpp index af36fe22e..d83320d4d 100644 --- a/src/bugreprt.cpp +++ b/src/bugreprt.cpp @@ -43,7 +43,7 @@ BOOL GetProcessorSpeed(DWORD* mhz) HANDLE t, p; if (!QueryPerformanceFrequency(&f)) - return FALSE; // installed hardware doesn't supports a high-resolution performance counter + return FALSE; // installed hardware does not support a high-resolution performance counter // temporarily raise priority t = GetCurrentThread(); @@ -70,7 +70,7 @@ BOOL GetProcessorSpeed(DWORD* mhz) c2 = __rdtsc(); QueryPerformanceCounter(&t2); - // restore original priority + // restore the original priorities SetThreadPriority(t, tp); SetPriorityClass(p, pp); @@ -173,7 +173,7 @@ MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dw sprintf(buf, "Monitor %d: (%d,%d)-(%d,%d) %dx%d pixels", data->Index, r.left, r.top, r.right, r.bottom, r.right - r.left, r.bottom - r.top); - // hdcMonitor is NULL, we must create a DC + // hdcMonitor is NULL, so we must create a DC HDC hdc = NOHANDLES(CreateDC(mi.szDevice, mi.szDevice, NULL, NULL)); int planes = GetDeviceCaps(hdc, PLANES); int bitsPixels = GetDeviceCaps(hdc, BITSPIXEL); @@ -575,8 +575,8 @@ void CCallStack::PrintBugReport(EXCEPTION_POINTERS* Exception, DWORD ThreadID, D PrintLine(param, buf, TRUE); if (IsDebuggerPresent()) { - // the x64/Debug build on W7 started from the MSVC debugger did not generate a valid minidump (function failed, dump incomplete) - // outside MSVC everything worked correctly - note that we are running from the debugger + // The x64/Debug build on Windows 7 started from the MSVC debugger did not generate a valid minidump + // outside MSVC everything worked correctly, so note that we are running under the debugger sprintf(buf, "Debugger is present!"); PrintLine(param, buf, TRUE); } @@ -2026,8 +2026,8 @@ void CCallStack::PrintBugReport(EXCEPTION_POINTERS* Exception, DWORD ThreadID, D int i; for (i = 0; i < CCallStack::CallStacks.Count; i++) { - // !!! accesses to CCallStack::CallStacks array should be protected by a critical section - // otherwise we risk touching non-existing memory + // !!! access to the CCallStack::CallStacks array should be protected by a critical section + // otherwise we risk accessing invalid memory CCallStack* stack; stack = CCallStack::CallStacks[i]; @@ -2054,7 +2054,7 @@ void CCallStack::PrintBugReport(EXCEPTION_POINTERS* Exception, DWORD ThreadID, D BOOL threadWithException = (Exception != NULL && Exception->ContextRecord != NULL && stack->ThreadID == ThreadID); if (stack->ThreadID != GetCurrentThreadId() || threadWithException) { - // if this isn't our thread, suspend it so we can retrieve context + // if this is not our thread, suspend it so we can retrieve its context if (threadWithException || SuspendThread(hThread) != -1) { if (!firstTime) @@ -2098,7 +2098,7 @@ void CCallStack::PrintBugReport(EXCEPTION_POINTERS* Exception, DWORD ThreadID, D // // this function's ebp // points here ------------\ - // ebp-0x8 ebp-0x4 ebp+0x0 ebp+0x4 ebp+0x8 ebp+0xC + // ebp-0x8 ebp-0x4 ebp+0x0 ebp+0x4 ebp+0x8 ebp+0xC // caller's return // local1 local0 ebp addr param0 param1 // ... 00000000 00000000 00000000 00000000 00000000 00000000 ... @@ -2372,11 +2372,11 @@ void CCallStack::PrintBugReport(EXCEPTION_POINTERS* Exception, DWORD ThreadID, D PrintLine(param, "", FALSE); /* - // leaving thread enumeration unfinished for now because Petr suggested showing - // the back trace for the thread where the crash occurred (we know its ID) + // leaving thread enumeration unfinished for now because Petr suggested displaying + // the backtrace for the thread in which the crash occurred (we know its ID) - // the knownThreads array contains a list of displayed threads; - // now we attempt to find those not yet shown + // the knownThreads array contains the list of threads already shown; + // now we will try to find those not yet shown if (knownThreads.IsGood()) { HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); diff --git a/src/cache.cpp b/src/cache.cpp index 6b8e74011..9fa7f991f 100644 --- a/src/cache.cpp +++ b/src/cache.cpp @@ -56,7 +56,7 @@ CCacheData::CCacheData(const char* name, const char* tmpName, BOOL ownDelete, CCacheData::~CCacheData() { - if (TmpName != NULL && LockObject.Count == 0) // tmp-file not needed anymore + if (TmpName != NULL && LockObject.Count == 0) // tmp-file is no longer needed { if (!CleanFromDisk()) { @@ -97,7 +97,7 @@ CCacheData::~CCacheData() BOOL CCacheData::CleanFromDisk() { CALL_STACK_MESSAGE1("CCacheData::CleanFromDisk"); - if (!Detached) // user does not wish to delete tmp-file + if (!Detached) // the user does not want the tmp-file deleted { if (!OwnDelete) { @@ -126,9 +126,8 @@ BOOL CCacheData::CleanFromDisk() } else // deletion should be handled by the plugin { - if (OwnDeletePlugin != NULL) // we can start deleting (plugin can't be unloaded), otherwise the file - { // won't be deleted (it's either already deleted or it's just - // disconnected - the plugin decides this during its unload + if (OwnDeletePlugin != NULL) // we can start deleting (the plugin cannot be unloaded); otherwise the file will not be deleted + { // won't be deleted (it is either already deleted or just disconnected; the plugin decides this during unload) DeleteManager.AddFile(TmpName, OwnDeletePlugin); OwnDeletePlugin = NULL; // no more deleting will be done } @@ -156,17 +155,17 @@ CCacheData::GetName(CDiskCache* monitor, BOOL* exists, BOOL canBlock, BOOL onlyA else { res = WaitForSingleObject(Preparing, 0); // no waiting - if (res == WAIT_TIMEOUT) // the file is being prepared, we won't wait + if (res == WAIT_TIMEOUT) // the file is being prepared; do not wait { NewCount--; *exists = FALSE; if (errorCode != NULL) *errorCode = onlyAdd ? DCGNE_ALREADYEXISTS : DCGNE_NOTFOUND; - return NULL; // "not found" error, and if 'onlyAdd' is TRUE, then also "file already exists" + return NULL; // "not found" error, and if 'onlyAdd' is TRUE, also "file already exists" } } - if (res == WAIT_OBJECT_0) // tmp-file is ready or we are allowed to prepare it (the one who calls GetName) + if (res == WAIT_OBJECT_0) // tmp-file is ready or we are allowed to prepare it ourselves (the caller of GetName) { if (Prepared) // tmp-file is ready { @@ -195,7 +194,7 @@ CCacheData::GetName(CDiskCache* monitor, BOOL* exists, BOOL canBlock, BOOL onlyA } else { - ReleaseMutex(Preparing); // providing a message about readiness to other threads + ReleaseMutex(Preparing); // signal readiness to the other threads if (onlyAdd) { NewCount--; @@ -217,7 +216,7 @@ CCacheData::GetName(CDiskCache* monitor, BOOL* exists, BOOL canBlock, BOOL onlyA // tmp-file is not ready, the owning thread has been terminated // mutex Preparing is ours (either via WAIT_OBJECT_0 or WAIT_ABANDONED) *exists = FALSE; - if (!CleanFromDisk()) // name change is needed, the original tmp-file probably remained open + if (!CleanFromDisk()) // a name change is needed; the original tmp-file probably remained open { TRACE_E("Unable to delete tmp-file."); } @@ -271,10 +270,10 @@ BOOL CCacheData::ReleaseName(BOOL* lastLock, BOOL storeInCache) if (!Prepared) ReleaseMutex(Preparing); // if we're preparing tmp-file, we give up by this *lastLock = IsLocked(); - if (*lastLock && Prepared && storeInCache && !OutOfDate) // only the prepared file can remaing in cache + if (*lastLock && Prepared && storeInCache && !OutOfDate) // only a prepared file can remain in the cache { Cached = TRUE; // we mark the file as cached, otherwise disk-cache would cancel it immediately - LastAccess = LastAccessCounter++; // the last 'lock', it's in a tight spot (we set the time of the last usage) + LastAccess = LastAccessCounter++; // the last 'lock' is at risk (we update the last-use time) } return TRUE; } @@ -294,7 +293,7 @@ BOOL CCacheData::WaitSatisfied(HANDLE lock, BOOL* lastLock) LockObjOwner.Delete(i); *lastLock = IsLocked(); if (*lastLock) - LastAccess = LastAccessCounter++; // the last 'lock', it's in a tight spot + LastAccess = LastAccessCounter++; // the last 'lock' is gone, so the file is now at risk return TRUE; } } @@ -310,8 +309,8 @@ void CCacheData::PrematureDeleteByPlugin(CPluginInterfaceAbstract* ownDeletePlug CALL_STACK_MESSAGE2("CCacheData::PrematureDeleteByPlugin(, %d)", onlyDetach); if (Detached) onlyDetach = TRUE; - if (OwnDelete && // deleting should be taken care by a plugin - OwnDeletePlugin == ownDeletePlugin) // we're searching for this tmp-file (The plugin 'ownDeletePlugin' deletes it) + if (OwnDelete && // deletion should be handled by the plugin + OwnDeletePlugin == ownDeletePlugin) // searching for this tmp file (the plugin 'ownDeletePlugin' deletes it) { if (!onlyDetach) DeleteManager.AddFile(TmpName, OwnDeletePlugin); @@ -364,7 +363,7 @@ BOOL CCacheDirData::ContainTmpName(const char* tmpName, const char* rootTmpPath, s++; while (*s != 0 && *s != '\\') s++; - if (*s == 0 || *(s + 1) == 0) // // after the root-tmp-path, there's only one subdirectory name (possibly with '\\' at the end) + if (*s == 0 || *(s + 1) == 0) // after the root tmp path, there is only one subdirectory name left (possibly with a trailing '\\') { *canContainThisName = TRUE; // tmp-root matches, tmp-file can be placed here @@ -388,14 +387,14 @@ BOOL CCacheDirData::ContainTmpName(const char* tmpName, const char* rootTmpPath, if (StrICmp(tmpName, data.cFileName) == 0) { TRACE_E("CCacheDirData::ContainTmpName(): unexpected situation: tmp-directory contains unknown file!"); - *canContainThisName = FALSE; // the file can't be placed here, a foreign file would be opened + *canContainThisName = FALSE; // the file cannot be placed here; another file would be opened } else { if (data.cAlternateFileName[0] != 0 && StrICmp(tmpName, data.cAlternateFileName) == 0) { TRACE_I("CCacheDirData::ContainTmpName(): tmp-directory contains file whose dos-name conflicts with new tmp-file - different tmp-directory has to be choosen!"); - *canContainThisName = FALSE; // the file can't be placed here, an existing file with the same dos-name would be opened + *canContainThisName = FALSE; // the file cannot be placed here; an existing file with the same DOS name would be opened } } } @@ -470,7 +469,7 @@ void CCacheDirData::RemoveEmptyTmpDirsOnlyFromDisk() if (PathLength > 0) Path[PathLength - 1] = 0; // backslash trimming SetFileAttributes(Path, FILE_ATTRIBUTE_ARCHIVE); - // the system deletes our tmp-directory only if it's empty (in case of further need for a tmp-directory, we will create it in CCacheDirData::GetName()) + // the system deletes our tmp directory only if it is empty (if a tmp directory is needed again, we create it in CCacheDirData::GetName()) RemoveDirectory(Path); if (PathLength > 0) Path[PathLength - 1] = '\\'; // restoring backslash @@ -486,8 +485,8 @@ BOOL CCacheDirData::GetName(CDiskCache* monitor, const char* name, BOOL* exists, if (GetNameIndex(name, i)) // 'name' found at index 'i' { *tmpPath = Names[i]->GetName(monitor, exists, canBlock, onlyAdd, errorCode); - if (*tmpPath != NULL) // not a fatal error nor an unprepared tmp-file - { // nor a "file already exists" error (only if 'onlyAdd' is TRUE) + if (*tmpPath != NULL) // neither a fatal error nor an unprepared tmp file + { // not a "file already exists" error either (only if 'onlyAdd' is TRUE) CheckAndCreateDirectory(Path, NULL, TRUE); } return TRUE; @@ -520,7 +519,7 @@ CCacheDirData::GetName(const char* name, const char* tmpName, BOOL* exists, BOOL return NULL; } int i; - if (GetNameIndex(name, i)) // error: inserted name is unique - it can't be in the array yet + if (GetNameIndex(name, i)) // error: the inserted name is unique, so it cannot already be in the array { TRACE_E("This should never happen!"); } @@ -582,7 +581,7 @@ BOOL CCacheDirData::ReleaseName(const char* name, BOOL* ret, BOOL* lastCached, B BOOL last; *ret = Names[i]->ReleaseName(&last, storeInCache); *lastCached = FALSE; - if (last) // contemporarily, this was also the last link to this tmp-file + if (last) // this was also the last link to this tmp-file { if (Names[i]->IsCached()) *lastCached = TRUE; @@ -602,7 +601,7 @@ BOOL CCacheDirData::Release(CCacheData* data) CALL_STACK_MESSAGE1("CCacheDirData::Release()"); int i; if (GetNameIndex(data->GetName(), i)) // 'data' found at index 'i' - { // we took advantage of the fact that the name is unique, so that Names[i] == data + { // we rely on the name being unique, so Names[i] must equal data #ifdef _DEBUG if (Names[i] != data) { @@ -647,12 +646,12 @@ void CCacheDirData::AddVictimsToArray(TDirectArray& victArr) BOOL CCacheDirData::DetachTmpFile(const char* tmpName) { - if (StrNICmp(tmpName, Path, PathLength) == 0) // if there's a chance that this is our tmp-file + if (StrNICmp(tmpName, Path, PathLength) == 0) // if there is a chance that this is our tmp file { int i; for (i = 0; i < Names.Count; i++) { - if (StrICmp(Names[i]->GetTmpName() + PathLength, tmpName + PathLength) == 0) // we've got it + if (StrICmp(Names[i]->GetTmpName() + PathLength, tmpName + PathLength) == 0) // found it { Names[i]->DetachTmpFile(); return TRUE; @@ -667,9 +666,9 @@ void CCacheDirData::FlushCache(const char* name) int nameLen = (int)strlen(name); int i; GetNameIndex(name, i); // we'll find the index (match/insertion) from which it makes sense to search for the same prefixes - for (; i < Names.Count; i++) // names are sorted -> elements with the same prefix are continuously next to each other + for (; i < Names.Count; i++) // names are sorted -> elements with the same prefix are contiguous { - if (strncmp(Names[i]->GetName(), name, nameLen) == 0) // mame ho + if (strncmp(Names[i]->GetName(), name, nameLen) == 0) // match found { CCacheData* data = Names[i]; if (data->IsLocked()) @@ -687,7 +686,7 @@ void CCacheDirData::FlushCache(const char* name) } } else - break; // there can't be any other, we are finished + break; // there can be no more; stop here } } @@ -736,7 +735,7 @@ unsigned ThreadCacheHandlesBody(void* param) int index; handles->WaitForObjects(&handle, &owner, &index); CALL_STACK_MESSAGE1("ThreadCacheHandlesBody::WaitForObjects_end"); - if (handle == handles->Terminate) // we should end + if (handle == handles->Terminate) // we should terminate { break; } @@ -757,7 +756,7 @@ unsigned ThreadCacheHandlesBody(void* param) if (handle == handles->TestIdle) // WaitForIdle unblocked WaitForObjects (we can ignore it) { } - else // someone from outside changed the state of 'handle' to "signaled" (e.g. the application ended) + else // the state of 'handle' was changed to "signaled" externally (e.g. the application terminated) { if (handle != NULL && owner != NULL) handles->WaitSatisfied(handle, owner, index); @@ -866,12 +865,12 @@ CCacheHandles::CCacheHandles() : Handles(100, 50), Owners(100, 50) void CCacheHandles::Destroy() { CALL_STACK_MESSAGE1("CCacheHandles::Destroy()"); - if (Thread != NULL) // thread termination is required + if (Thread != NULL) // the thread needs to be terminated { SetEvent(Terminate); // "you should end now" if (WaitForSingleObject(Thread, 1000) == WAIT_TIMEOUT) // let's give it 1 second { - TerminateThread(Thread, 666); // it doesn't want to end, we will kill it + TerminateThread(Thread, 666); // if it does not want to terminate, kill it WaitForSingleObject(Thread, INFINITE); // we will wait until the thread really ends, sometimes it takes a while } HANDLES(CloseHandle(Thread)); @@ -930,7 +929,7 @@ void CCacheHandles::WaitForObjects(HANDLE* handle, CCacheData** owner, int* inde while (1) { if (Idle == 1) - Idle = 2; // it is asking, we will find out + Idle = 2; // querying; will determine int offset; for (offset = 0; offset < Handles.Count;) { @@ -948,7 +947,7 @@ void CCacheHandles::WaitForObjects(HANDLE* handle, CCacheData** owner, int* inde GetErrorText(err), offset, count, Handles.Count); #ifndef CALLSTK_DISABLE int i; - for (i = 0; i < count; i++) // this is a little bit dirty ... + for (i = 0; i < count; i++) // somewhat of a hack ... { #if (defined(_DEBUG) || defined(CALLSTK_MEASURETIMES)) && !defined(CALLSTK_DISABLEMEASURETIMES) new CCallStackMessage(TRUE, 0, "handle %d: %p", i, (((HANDLE*)Handles.GetData()) + offset)[i]); @@ -983,7 +982,7 @@ void CCacheHandles::WaitForObjects(HANDLE* handle, CCacheData** owner, int* inde *handle = (HANDLE)Handles[*index]; *owner = Owners[*index]; if (Idle == 2) - Idle = 1; // a formality: answer "no", but it asked, so it will ask again + Idle = 1; // formality: answer "no", but since it asked, it asks again return; } } @@ -1044,7 +1043,7 @@ void CCacheHandles::WaitForIdle() { CALL_STACK_MESSAGE1("CCacheHandles::WaitForIdle()"); TRACE_I("CCacheHandles::WaitForIdle begin"); - Idle = 1; // we are asking + Idle = 1; // asking whether we're idle SetEvent(TestIdle); // if the watching thread is waiting, we will stop the wait (we will run the idle-state test) WaitForSingleObject(IsIdle, INFINITE); // we are waiting for idle TRACE_I("CCacheHandles::WaitForIdle end"); @@ -1128,8 +1127,8 @@ CDiskCache::GetName(const char* name, const char* tmpName, BOOL* exists, BOOL on const char* tmpPath; if (Dirs[i]->GetName(this, name, exists, &tmpPath, tmpName != NULL && !onlyAdd, onlyAdd, errorCode)) - { // 'name' found; if 'tmpName' is NULL, it can be an unprepared tmp-file (it returns 'not found' error) - // if 'onlyAdd' is TRUE, it can be a "file already exists" error + { // 'name' found; if 'tmpName' is NULL, the name may still refer to an unprepared file (returns a "not found" error) + // if 'onlyAdd' is TRUE, it may instead be a "file already exists" error Leave(); return tmpPath; } @@ -1269,8 +1268,8 @@ BOOL CDiskCache::ReleaseName(const char* name, BOOL storeInCache) BOOL lastCached; if (Dirs[i]->ReleaseName(name, &ret, &lastCached, storeInCache)) // 'name' found { - if (lastCached) // tmp-file is without links and cached, we will see if we need - { // to release it, or if we need to release space on disk + if (lastCached) // The tmp-file is orphaned and cached; we will see whether it already needs to be released. + { // Check whether we need to free up disk space. CheckCachedFiles(); } Leave(); @@ -1317,7 +1316,7 @@ void CDiskCache::CheckCachedFiles() int i; for (i = 0; i < Dirs.Count; i++) size += Dirs[i]->GetSizeOfFiles(); - if (size > MAX_CACHE_SIZE) // it is needed to delete some files + if (size > MAX_CACHE_SIZE) // some files need to be deleted { TDirectArray victArr(100, 50); for (i = 0; i < Dirs.Count; i++) @@ -1325,7 +1324,7 @@ void CDiskCache::CheckCachedFiles() Dirs[i]->AddVictimsToArray(victArr); } if (!victArr.IsGood()) - return; // low memory, we won't perform optimization + return; // low memory, optimization will not be performed if (victArr.Count > 1) SortVictims(victArr, 0, victArr.Count - 1); int actVict = 0; @@ -1336,16 +1335,16 @@ void CDiskCache::CheckCachedFiles() { CCacheData* data = victArr[actVict++]; size -= data->GetSize(); // subtract its size from the total size of cache - for (i = 0; i < Dirs.Count; i++) // release it from cache and from disk + for (i = 0; i < Dirs.Count; i++) // release it from the cache and from disk { if (Dirs[i]->Release(data)) - break; // found and cancelled + break; // found and removed } } else - break; // at least one cached file must remain in cache, it will be - // the one which was released last, it prevents discarding - // of the file which the user is currently looking at + break; // at least one cached file must remain in the cache; + // it will be the one most recently released, + // preventing the file the user is currently viewing from being discarded } } } @@ -1357,13 +1356,13 @@ void CDiskCache::WaitSatisfied(HANDLE lock, CCacheData* owner) BOOL last; if (owner->WaitSatisfied(lock, &last)) { - if (last) // tmp-file is without links, we can cancel it + if (last) // the tmp file is orphaned; we can delete it { - if (owner->IsCached()) // we will see if we need to release it, - { // or we will free space on disk + if (owner->IsCached()) // see if we already need to free some space + { // free up disk space if needed CheckCachedFiles(); } - else // we should delete the file directly + else // delete the file directly { int i; for (i = 0; i < Dirs.Count; i++) @@ -1383,7 +1382,7 @@ void CDiskCache::WaitSatisfied(HANDLE lock, CCacheData* owner) return; } Leave(); - return; // an error in owner->WaitSatisfied() + return; // error in owner->WaitSatisfied() } BOOL CDiskCache::DetachTmpFile(const char* tmpName) @@ -1462,7 +1461,7 @@ void CDiskCache::ClearTEMPIfNeeded(HWND parent, HWND hActivePanel) { SalPathAddBackslash(tmpDir, 2 * MAX_PATH); char* tmpDirEnd = tmpDir + strlen(tmpDir); - if (SalPathAppend(tmpDir, "SAL*.tmp", 2 * MAX_PATH)) // we will add a mask (it won't fit = no sense in searching anything) + if (SalPathAppend(tmpDir, "SAL*.tmp", 2 * MAX_PATH)) // append the mask (if it does not fit, there is no point in searching) { TIndirectArray tmpDirs(10, 50); @@ -1478,7 +1477,7 @@ void CDiskCache::ClearTEMPIfNeeded(HWND parent, HWND hActivePanel) while (*s != 0 && *s != '.' && (*s >= '0' && *s <= '9' || *s >= 'a' && *s <= 'f' || *s >= 'A' && *s <= 'F')) s++; - if (StrICmp(s, ".tmp") == 0) // matches "SAL" + hex-number + ".tmp" = it's almost certainly our directory + if (StrICmp(s, ".tmp") == 0) // matches "SAL" + hex number + ".tmp"; it is almost certainly our directory { char* tmp = DupStr(data.cFileName); if (tmp != NULL) @@ -1602,7 +1601,7 @@ void CDeleteManager::ProcessData() if (BlockDataProcessing) return; - // we will lower the priority of the thread - we are going to delete a file to a plugin + // lower the thread priority; we are going to delete the file via the plugin SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); if (MainWindow != NULL) @@ -1618,18 +1617,18 @@ void CDeleteManager::ProcessData() HANDLES(EnterCriticalSection(&CS)); if (Data.Count > 0) { - item = Data[0]; // we will select the oldest item (it can't be NULL) + item = Data[0]; // select the oldest item (cannot be NULL) Data.Detach(0); if (!Data.IsGood()) - Data.ResetState(); // the element has been detached, and it doesn't matter if the array is larger + Data.ResetState(); // the element has been detached, and a larger array does not matter } else WaitingForProcessing = FALSE; // we are finishing processing HANDLES(LeaveCriticalSection(&CS)); if (item == NULL) - break; // the end of data processing + break; // end of data processing - // the beginning of the processing of new data + // process new data if (lastFoundPlugin == NULL || lastFoundPlugin != item->Plugin) { plugin = Plugins.GetPluginData(item->Plugin); @@ -1659,7 +1658,7 @@ void CDeleteManager::PluginMayBeUnloaded(HWND parent, CPluginData* plugin) SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); HANDLES(EnterCriticalSection(&CS)); - if (WaitingForProcessing) // message is on its way, we will cancel it, it is unnecessary, at the end of the method data processing will take place + if (WaitingForProcessing) // The message is already pending, so cancel it; it is unnecessary because the data will be processed at the end of the method. { if (MainWindow != NULL && MainWindow->HWindow != NULL) { @@ -1670,13 +1669,13 @@ void CDeleteManager::PluginMayBeUnloaded(HWND parent, CPluginData* plugin) } } else - WaitingForProcessing = TRUE; // we will block sending WM_USER_PROCESSDELETEMAN - undesirable and unnecessary, data processing will take place at the end of the method + WaitingForProcessing = TRUE; // Block sending WM_USER_PROCESSDELETEMAN: it is undesirable and unnecessary; data will be processed at the end of the method HANDLES(LeaveCriticalSection(&CS)); - BlockDataProcessing = TRUE; // // in case we missed a WM_TIMER message posted to the main window (we block it, because it can be delivered by the first displayed messagebox and its message loop) + BlockDataProcessing = TRUE; // in case a WM_TIMER posted to the main window would otherwise be missed (we block it because it can be delivered by the first displayed message box and its message loop) int copiesCount = DiskCache.CountNamesDeletedByPlugin(plugin->GetPluginInterface()->GetInterface()); - if (copiesCount > 0) // plugin still has some tmp-files opened (and it should ensure their deletion) + if (copiesCount > 0) // The plugin still has some temporary files open (and should ensure they are deleted) { if (plugin->PrematureDeleteTmpCopy(parent, copiesCount)) { // user wants to delete tmp-files, even if they are still opened (they are in viewers, etc.) diff --git a/src/cache.h b/src/cache.h index 43737b1d2..1cd198166 100644 --- a/src/cache.h +++ b/src/cache.h @@ -4,7 +4,7 @@ #pragma once -// disck cache initialization, returns success +// initializes the disk cache, returns success BOOL InitializeDiskCache(); // how long time to wait between checking the state of watched objects @@ -43,7 +43,7 @@ class CCacheData // tmp-name, info about file or directory on disk, internal use // system objects - array of (HANDLE): state "signaled" -> remove this 'lock' TDirectArray LockObject; - // the object ownership - array of (BOOL): TRUE -> call CloseHandle('lock') + // object ownership: array of BOOL values; TRUE -> call CloseHandle('lock') TDirectArray LockObjOwner; BOOL Cached; // is it a cached tmp-file? (did CrtCache already arrive?) @@ -52,7 +52,7 @@ class CCacheData // tmp-name, info about file or directory on disk, internal use CQuadWord Size; // tmp-file size (in bytes) int LastAccess; // "time" of last access to the tmp-file (for cache - remove the oldest) BOOL Detached; // TRUE => the tmp-file should not be deleted - BOOL OutOfDate; // TRUE => once possible, we acquire a new copy (as if it's not on disk) + BOOL OutOfDate; // TRUE => obtain a new copy as soon as possible (as if it were not on disk) BOOL OwnDelete; // FALSE = delete the tmp-file using DeleteFile(), TRUE = delete using DeleteManager (the plugin OwnDeletePlugin deletes) CPluginInterfaceAbstract* OwnDeletePlugin; // plugin interface, which should delete the tmp-file (NULL = the plugin is unloaded, the tmp-file should not be deleted) @@ -64,7 +64,7 @@ class CCacheData // tmp-name, info about file or directory on disk, internal use // returns the set size of the tmp-file CQuadWord GetSize() { return Size; } - // returns TRUE if the tmp-file is deleted by the plugin 'ownDeletePlugin' + // returns TRUE if this tmp-file should be deleted by plugin 'ownDeletePlugin' BOOL IsDeletedByPlugin(CPluginInterfaceAbstract* ownDeletePlugin) { return OwnDelete && OwnDeletePlugin == ownDeletePlugin; @@ -73,7 +73,7 @@ class CCacheData // tmp-name, info about file or directory on disk, internal use // returns "time" of last access to the tmp-file int GetLastAccess() { return LastAccess; } - // cancels tmp-file on disk, returns success (Name is not on disk anymore) + // removes the temporary file from disk, returns success (Name is no longer on disk) BOOL CleanFromDisk(); // did the object initialization succeeded? @@ -104,29 +104,29 @@ class CCacheData // tmp-name, info about file or directory on disk, internal use // for description see CDiskCache::NamePrepared() BOOL NamePrepared(const CQuadWord& size); - // for description see CDiskCache::AssignName() + // see CDiskCache::AssignName() for a description // - // handles - object for watching the 'lock' object + // handles - object for tracking 'lock' handles BOOL AssignName(CCacheHandles* handles, HANDLE lock, BOOL lockOwner, CCacheRemoveType remove); - // for description see CDiskCache::ReleaseName() + // see CDiskCache::ReleaseName() for a description // - // lastLock - pointer to BOOL, which is set to TRUE if there are no links to the tmp-file anymore + // lastLock - pointer to a BOOL that is set to TRUE if there are no more links to the tmp-file BOOL ReleaseName(BOOL* lastLock, BOOL storeInCache); // returns the full name of the tmp-file const char* GetTmpName() { return TmpName; } - // detaches the object 'lock' (in "signaled" state) from the tmp-file (detaches the link) + // detaches the 'lock' object (in the "signaled" state) from the tmp-file (detaches the link) // // returns success // - // lock - object, which is in "signaled" state - // lastLock - pointer to BOOL, which is set to TRUE if there are no links to the tmp-file anymore + // lock - object that has entered the "signaled" state + // lastLock - pointer to a BOOL that is set to TRUE if there are no more links to the tmp-file BOOL WaitSatisfied(HANDLE lock, BOOL* lastLock); - // if we change our mind about deleting the tmp-file on disk (e.g. it was not possible to pack it, - // so we leave it in temp, so that the users don't kill us) + // if we decide not to delete the temporary file on disk (for example, packing failed, + // it is safer to leave it in the temp directory) void DetachTmpFile() { Detached = TRUE; } // changes type of tmp-file to crtDirect (direct deletion after use) @@ -139,10 +139,10 @@ class CCacheData // tmp-name, info about file or directory on disk, internal use // returns item identification (path to original) const char* GetName() { return Name; } - // performs premature deletion of the tmp-file, which is deleted by the plugin 'ownDeletePlugin'; - // used when unloading the plugin (the tmp-file is marked as deleted - once all links are closed, - // deletion won't occur); if 'onlyDetach' is TRUE, the tmp-file is not deleted, it's only marked - // as deleted (the plugin is detached from the tmp-file) + // performs premature deletion of the tmp-file if it is deleted by the plugin + // 'ownDeletePlugin'; used when unloading the plugin (the tmp-file is marked as deleted, + // so once all references to it are closed, no deletion occurs); if 'onlyDetach' is TRUE, + // the tmp-file is not deleted and is only marked as deleted (the plugin is detached from the tmp-file) void PrematureDeleteByPlugin(CPluginInterfaceAbstract* ownDeletePlugin, BOOL onlyDetach); }; @@ -168,30 +168,30 @@ class CCacheDirData // tmp-directory, contains unique tmp-names, internal use // (finishing of TEMP cleaning - see CDiskCache::RemoveEmptyTmpDirsOnlyFromDisk()) void RemoveEmptyTmpDirsOnlyFromDisk(); - // returns TRUE if the tmp-directory contains 'tmpName' (name of file/directory on disk) + // returns TRUE if the tmp-directory contains 'tmpName' (the name of a file/directory on disk) // rootTmpPath - path where to place the tmp-directory with the tmp-file (must not be NULL) - // rootTmpPathLen - length of the string in rootTmpPath - // canContainThisName - must not be NULL, returns TRUE in it if it's possible to place - // the tmp-file into this tmp-directory (matches tmp-root + there's - // no file with DOS-name equal to 'tmpName') + // rootTmpPathLen - length of the rootTmpPath string + // canContainThisName - must not be NULL; set to TRUE if it is possible to place + // the tmp-file into this tmp-directory (it matches tmp-root and + // contains no file with a DOS name equal to 'tmpName') BOOL ContainTmpName(const char* tmpName, const char* rootTmpPath, int rootTmpPathLen, BOOL* canContainThisName); - // searches for 'name' in the tmp-directory; if it's found, returns TRUE and values 'name' and 'tmpPath', - // so that they match expected values from CDiskCache::GetName(); if it's not found, - // returns FALSE + // Searches for 'name' in the tmp directory; if found, returns TRUE and sets 'tmpPath' + // and the related state so they match the expected values from CDiskCache::GetName(); if not found, + // returns FALSE. // - // name - unique item identification - // exists - pointer to BOOL, which is set per the description above + // name - unique item identifier + // exists - pointer to a BOOL set as described above // tmpPath - return value of CDiskCache::GetName() (NULL && 'exists'==TRUE -> fatal error) // - // if 'onlyAdd' is TRUE, it is possible to create only a new name or restore a deleted tmp-file - // (the name exists, but the tmp-file is not prepared) - if the name exists, returns TRUE, - // 'exists' FALSE and 'tmpPath' NULL ("file already exists"); - // 'canBlock' is TRUE if waiting for readiness of the tmp-file is expected, in case 'name' - // is in cache, but it's not prepared, if 'canBlock' is FALSE and the tmp-file is not prepared, - // returns TRUE, 'exists' FALSE and 'tmpPath' NULL ("not found"); - // if 'errorCode' is not NULL, the error code is returned in it (see DCGNE_XXX) + // If 'onlyAdd' is TRUE, only a new name may be created, or a deleted tmp file may be restored + // (the name exists, but the tmp file is not prepared); if the name already exists, + // returns TRUE, 'exists' FALSE, and 'tmpPath' NULL ("file already exists"); + // 'canBlock' is TRUE if the call should wait for the tmp file to become ready when + // 'name' is in the cache but is not prepared; if 'canBlock' is FALSE and the tmp file is not + // prepared, returns TRUE, 'exists' FALSE, and 'tmpPath' NULL ("not found"); + // if 'errorCode' is not NULL, it receives the error code that occurred (see DCGNE_XXX) BOOL GetName(CDiskCache* monitor, const char* name, BOOL* exists, const char** tmpPath, BOOL canBlock, BOOL onlyAdd, int* errorCode); @@ -199,64 +199,64 @@ class CCacheDirData // tmp-directory, contains unique tmp-names, internal use const char* GetName(const char* name, const char* tmpName, BOOL* exists, BOOL ownDelete, CPluginInterfaceAbstract* ownDeletePlugin, int* errorCode); - // searches for 'name' in the tmp-directory; if it's found, returns TRUE and 'ret' is set to return value - // CDiskCache::NamePrepared(name, size); if it's not found, returns FALSE - // for description see CDiskCache::NamePrepared() + // searches for 'name' in the tmp-directory; if found, returns TRUE and 'ret' is set to the return value of + // CDiskCache::NamePrepared(name, size); if not found, returns FALSE + // see CDiskCache::NamePrepared() for a description BOOL NamePrepared(const char* name, const CQuadWord& size, BOOL* ret); - // searches for 'name' in the tmp-directory; if it's found, returns TRUE and 'ret' is set to return value - // CDiskCache::AssignName(name, lock, lockOwner, remove); if it's not found, returns FALSE - // for description see CDiskCache::AssignName() + // searches for 'name' in the tmp-directory; if found, returns TRUE and 'ret' is set to the return value of + // CDiskCache::AssignName(name, lock, lockOwner, remove); if not found, returns FALSE + // see CDiskCache::AssignName() for a description // - // handles - object for watching the 'lock' object + // handles - object for tracking 'lock' objects BOOL AssignName(CCacheHandles* handles, const char* name, HANDLE lock, BOOL lockOwner, CCacheRemoveType remove, BOOL* ret); - // searches for 'name' in the tmp-directory; if it's found, returns TRUE and 'ret' is set to return value - // CDiskCache::ReleaseName(name); if it's not found, returns FALSE - // for description see CDiskCache::ReleaseName() + // searches for 'name' in the tmp directory; if found, returns TRUE and 'ret' is set to the return value of + // CDiskCache::ReleaseName(name); if not found, returns FALSE + // for a description, see CDiskCache::ReleaseName() // - // lastCached - pointer to BOOL, which is set to TRUE if this is the last link to the cached tmp-file, - // or if it's necessary to decide about its further existence + // lastCached - pointer to BOOL that is set to TRUE if this is the last link to the cached tmp file, + // i.e. if its further existence must be decided BOOL ReleaseName(const char* name, BOOL* ret, BOOL* lastCached, BOOL storeInCache); - // searches for 'data' in the tmp-directory; if it's found, returns TRUE and cancels tmp-file 'data'; - // if it's not found, returns FALSE + // searches for 'data' in the tmp directory; if found, returns TRUE and removes the tmp file 'data'; + // if not found, returns FALSE // - // data - tmp-file + // data - tmp file BOOL Release(CCacheData* data); // sum of sizes of tmp-files in the tmp-directory CQuadWord GetSizeOfFiles(); - // fills the array 'victArr' with cached tmp-files without any link (WARNING: it doesn't sort from the oldest to the newest) + // fills the array 'victArr' with cached orphaned tmp files (WARNING: not sorted from oldest to newest) void AddVictimsToArray(TDirectArray& victArr); // if we change our mind about deleting the tmp-file on disk (e.g. it was not possible to pack it // so we leave it in temp, so that the users don't kill us) BOOL DetachTmpFile(const char* tmpName); - // removes all cached tmp-files beginning with 'name' (e.g. all files from one archive) - // opened files will be marked as out-of-date, so that they will be restored when used again - // (the current copy remains, so that the viewers don't yell at us) + // removes all cached files whose names start with 'name' (e.g. all files from one archive) + // open files are marked as out-of-date so they are refreshed on next use + // (the current copy remains so viewers do not complain) void FlushCache(const char* name); - // removes cached file 'name'; the opened file will be marked as out-of-date, so that it will be - // restored when used again (the current copy remains, so that the viewers don't yell at us); - // returns TRUE if the file was found and removed + // removes cached file 'name'; the open file is marked as out-of-date so it is refreshed on next use + // (the current copy remains so viewers are not disrupted); returns TRUE + // if the file was found and removed BOOL FlushOneFile(const char* name); - // search for the name in the array Names; returns TRUE if 'name' was found (returns also where - 'index'); - // returns FALSE if 'name' is not in Names (returns also where it could be inserted - 'index') + // searches for the name in the Names array; returns TRUE if 'name' is found (and also returns its position in 'index'); + // returns FALSE if 'name' is not in Names (and also returns the insertion position in 'index') BOOL GetNameIndex(const char* name, int& index); // counts how many tmp-files are contained in tmp-directory, which are deleted by the plugin 'ownDeletePlugin' int CountNamesDeletedByPlugin(CPluginInterfaceAbstract* ownDeletePlugin); - // performs premature deletion of all tmp-files, which are deleted by the plugin 'ownDeletePlugin'; - // used when unloading the plugin (the tmp-file is marked as deleted - once all links are closed, - // deletion won't occur); if 'onlyDetach' is TRUE, it is not deleted, it's only marked - // as deleted (the plugin is detached from the tmp-file) + // performs premature deletion of all tmp-files deleted by the plugin + // 'ownDeletePlugin'; used when unloading the plugin (the tmp-files are marked as deleted, + // so once all references to them are closed, no deletion occurs); if 'onlyDetach' is TRUE, + // they are not deleted and are only marked as deleted (the plugin is detached from the tmp-files) void PrematureDeleteByPlugin(CPluginInterfaceAbstract* ownDeletePlugin, BOOL onlyDetach); }; @@ -333,7 +333,7 @@ class CCacheHandles class CDiskCache // assigns names for tmp-files { // object is synchronized - monitor protected: - CRITICAL_SECTION Monitor; // section used for synchronization of this object (behavior - monitor) + CRITICAL_SECTION Monitor; // critical section used to synchronize this object (monitor behavior) CRITICAL_SECTION WaitForIdleCS; // section used for synchronization of calling WaitForIdle() TDirectArray Dirs; // list of tmp-directories, type of item (CCacheDirData *) CCacheHandles Handles; // object, which watches the 'lock' objects @@ -349,81 +349,83 @@ class CDiskCache // assigns names for tmp-files // (e.g. Encrypt plugin has its own) after previous call of PrematureDeleteByPlugin()) void RemoveEmptyTmpDirsOnlyFromDisk(); - // returns success of object initialization + // returns whether object initialization succeeded BOOL IsGood() { return Handles.IsGood() && Dirs.IsGood(); } - // tries to find 'name' in cache; if it's found, waits until the tmp-file is prepared + // tries to find 'name' in the cache; if found, waits until the tmp-file is prepared // (e.g. downloaded from FTP), then returns the tmp-file name and sets 'exists' to TRUE; - // if it's found, but the tmp-file was deleted from disk, returns the tmp-file name and - // 'exists' to FALSE, in this case it's necessary to prepare the tmp-file again and then - // call NamePrepared(); if 'tmpName' is NULL, only find 'name' in cache (don't create new - // tmp-file); if 'onlyAdd' is TRUE, only add to cache (if the tmp-file exists, returns - // error; if the tmp-file was deleted from disk, restoring it is considered as adding, - // so in this case it doesn't return error); if it's not found and 'tmpName' is not NULL, - // creates a new name for the tmp-file, returns it immediately and sets 'exists' to FALSE, - // in this case it's necessary to call NamePrepared() when the tmp-file is prepared (e.g. - // downloaded from FTP) and then the tmp-file will be available to other threads; - // WARNING: it's necessary to call AssignName() or ReleaseName() + // if found but the tmp-file was deleted from disk, returns the tmp-file name and sets + // 'exists' to FALSE; in that case the tmp-file must be prepared again and then + // NamePrepared() must be called; if 'tmpName' is NULL, only look up 'name' in the cache + // (do not create a new tmp-file); if 'onlyAdd' is TRUE, only add to the cache (if the + // tmp-file already exists, the call fails; if someone deleted the tmp-file directly + // from disk, restoring it is treated as adding, so in that case no error is returned); + // if not found and 'tmpName' is not NULL, creates a new name for the tmp-file, + // returns it immediately and sets 'exists' to FALSE; in that case, when the tmp-file is + // prepared (e.g. downloaded from FTP), NamePrepared() must be called so that the file + // becomes available to other threads; + // WARNING: AssignName() or ReleaseName() must be called // - // return value NULL -> "fatal error" ('exists' is TRUE) or in case 'tmpName' is NULL - // "not found" ('exists' is FALSE), and in case 'onlyAdd' is TRUE - // "file already exists" ('exists' is FALSE) + // return value NULL -> "fatal error" ('exists' is TRUE) or, if 'tmpName' is NULL, + // "not found" ('exists' is FALSE), and if 'onlyAdd' is TRUE, + // "file already exists" ('exists' is FALSE) // - // name - unique item identification - // tmpName - required name of the tmp-file or directory, a tmp-directory will be selected + // name - unique item identifier + // tmpName - requested name of the tmp-file or directory; a tmp-directory will be selected // for it - // exists - pointer to BOOL, which is set per the description above - // onlyAdd - if it is TRUE, it is possible to create only a new name (if the name exists, - // returns NULL) or restore a deleted tmp-file (the name exists, but the tmp-file - // is not prepared) - // - // rootTmpPath - if NULL, the tmp-directory with the tmp-file should be placed into TEMP, otherwise - // it's the path where to place the tmp-directory with the tmp-file - // ownDelete - if FALSE, tmp-files should be deleted using DeleteFile(), otherwise using - // DeleteManager (deletion using plugin - see ownDeletePlugin) - // ownDeletePlugin - if ownDelete is TRUE, contains iface of the plugin, which should delete - // the tmp-file - // errorCode - if not NULL and an error occurs, its code is returned in this variable (for codes - // see DCGNE_XXX) + // exists - pointer to a BOOL set as described above + // onlyAdd - if TRUE, only a new name can be created (if the name already exists, + // returns NULL) or a deleted tmp-file can be restored (the name exists, but the + // tmp-file is not prepared) + // rootTmpPath - if NULL, the tmp-directory with the tmp-file should be placed in TEMP; + // otherwise this is the path where the tmp-directory with the tmp-file + // should be placed + // ownDelete - if FALSE, tmp-files should be deleted using DeleteFile(); otherwise they + // should be deleted by DeleteManager (plugin-based deletion - see + // ownDeletePlugin) + // ownDeletePlugin - if ownDelete is TRUE, contains the plugin interface that deletes the + // tmp-file + // errorCode - if not NULL and an error occurs, its code is returned in this variable (for + // codes see DCGNE_XXX) const char* GetName(const char* name, const char* tmpName, BOOL* exists, BOOL onlyAdd, const char* rootTmpPath, BOOL ownDelete, CPluginInterfaceAbstract* ownDeletePlugin, int* errorCode); - // selects tmp-file related to 'name' for a valid one, provides it to other threads, + // marks the tmp-file corresponding to 'name' as valid and makes it available to other threads; // can be called only after GetName() returns 'exists' == FALSE // // returns success // - // name - unique item identification + // name - unique item identifier // size - number of bytes occupied by the tmp-file on disk BOOL NamePrepared(const char* name, const CQuadWord& size); - // assigns system object to the acquired tmp-file, using 'lock' the minimal lifetime - // of the tmp-file is controlled (depends on 'remove') - // can be called only in pair with GetName() + // assigns a system object to the acquired tmp-file; 'lock' controls the minimum + // lifetime of the tmp-file (depends on 'remove') + // can only be called together with GetName() // // returns success // - // name - unique item identification (later for searching) - // lock - when this object is "signaled", it will be possible to "release" the tmp-file + // name - unique item identifier (used later for searching) + // lock - when this object is "signaled", the tmp-file can be "released" // (depends on 'remove') - // lockOwner - should the cache take care of calling CloseHandle(lock) ? + // lockOwner - should the cache take care of calling CloseHandle(lock)? // remove - when to delete the tmp-file BOOL AssignName(const char* name, HANDLE lock, BOOL lockOwner, CCacheRemoveType remove); - // only called when after calling GetName() it is not possible to call NamePrepared() or AssignName() - // it's present for the case of error when acquiring tmp-file or system object 'lock' - // (running application for which the tmp-file was acquired) - // in case that it was necessary to call NamePrepared(), it gives other threads the possibility - // to create tmp-file (which are waiting until the tmp-file is prepared), in case that it was - // necessary to call AssignName(), it cancels the tmp-file "waiting" for the system object 'lock', - // tmp-file cancellation can occur only if 'storeInCache' is TRUE, tmp-file is prepared and - // not locked, the tmp-file is marked as cached (if the maximum capacity of cache allows it, - // it won't be deleted) + // Called only when NamePrepared() or AssignName() cannot be called after GetName(). + // Used in case of an error while acquiring the tmp file or the 'lock' object (the + // launched application for which the tmp file was being acquired). + // If NamePrepared() would otherwise need to be called, it gives other threads a chance + // to create the tmp file (those waiting until the tmp file is prepared). If AssignName() + // would otherwise need to be called, it cancels the tmp file's waiting state for assignment + // of the 'lock' object, and the tmp file may be deleted. If 'storeInCache' is TRUE and the + // tmp file is prepared and not locked, it is marked as cached (if the maximum cache capacity + // allows it, it will not be deleted). // - // returns success + // Returns success. // - // name - unique item identification (later for searching) + // name - item identifier (used later for lookup) BOOL ReleaseName(const char* name, BOOL storeInCache); // waits for the moment when the cache-handles are "free", it's useful when mass @@ -449,10 +451,11 @@ class CDiskCache // assigns names for tmp-files // counts how many tmp-files are contained in disk-cache, which are deleted by the plugin 'ownDeletePlugin' int CountNamesDeletedByPlugin(CPluginInterfaceAbstract* ownDeletePlugin); - // performs premature deletion of all tmp-files, which are deleted by the plugin 'ownDeletePlugin'; - // used when unloading the plugin (the tmp-file is marked as deleted - once all links are closed, - // deletion won't occur); if 'onlyDetach' is TRUE, it is not deleted, it's only marked - // as deleted (the plugin is detached from the tmp-file) + // Performs early deletion of all temporary files deleted by the 'ownDeletePlugin' + // plugin; used when unloading the plugin (the temporary files are marked as + // already deleted, so once all references to them are closed, no further deletion + // occurs); if 'onlyDetach' is TRUE, they are not deleted and are only marked as + // already deleted (the plugin is detached from the temporary files). void PrematureDeleteByPlugin(CPluginInterfaceAbstract* ownDeletePlugin, BOOL onlyDetach); // the TEMP directory clean-up from the rest of previous instances; called only by the first instance @@ -503,18 +506,18 @@ class CDeleteManager // data about the files that are to be deleted (in the main thread by calling the method // CPluginInterfaceForArchiverAbstract::DeleteTmpCopy of the plugin) TIndirectArray Data; - BOOL WaitingForProcessing; // TRUE = message to the main window is on the way or the data - // processing is in progress (the added item will be processed immediately) + BOOL WaitingForProcessing; // TRUE = a message to the main window is pending or data + // processing is already in progress (the added item is processed immediately) BOOL BlockDataProcessing; // TRUE = do not process data (ProcessData() does nothing) public: CDeleteManager(); ~CDeleteManager(); - // adds file for deletion and ensures the closest call of the method - // CPluginInterfaceForArchiverAbstract::DeleteTmpCopy for file deletion; - // in case of error, the file won't be deleted - the plugin should delete its - // directory when loading/unloading (TEMP will be cleaned by Salamander) + // adds a file for deletion and ensures that the plugin method + // CPluginInterfaceForArchiverAbstract::DeleteTmpCopy is called as soon as possible + // to delete the file; if an error occurs, the file is not deleted; the plugin should clean up its + // directory on unload/load (TEMP will be cleaned by Salamander) // can be called from any thread void AddFile(const char* fileName, CPluginInterfaceAbstract* plugin); @@ -522,14 +525,14 @@ class CDeleteManager // processing of new data - deleting files in plugins void ProcessData(); - // unloading of the plugin imminent: let the plugin which is being unloaded delete tmp-copies from disk + // plugin 'plugin' may be unloaded: let it delete temporary copies from disk // (see CPluginInterfaceForArchiverAbstract::PrematureDeleteTmpCopy) void PluginMayBeUnloaded(HWND parent, CPluginData* plugin); - // unload of the plugin finished: detach the plugin from delete-manager and disk-cache; - // 'unloadedPlugin' is already invalid plugin interface (backup before unload) + // plugin 'plugin' has been unloaded: detach it from the delete-manager and disk-cache; + // 'unloadedPlugin' is already an invalid plugin interface saved before unload void PluginWasUnloaded(CPluginData* plugin, CPluginInterfaceAbstract* unloadedPlugin); }; extern CDiskCache DiskCache; // global disk-cache -extern CDeleteManager DeleteManager; // global disk-cache delete-manager (deleting tmp-files in archivers plugins) +extern CDeleteManager DeleteManager; // global disk-cache delete-manager (for deleting tmp-files in archiver plugins) diff --git a/src/callstk.cpp b/src/callstk.cpp index efcf39ef1..733029365 100644 --- a/src/callstk.cpp +++ b/src/callstk.cpp @@ -100,11 +100,11 @@ BOOL PreventSetUnhandledExceptionFilterAux() newJump[0] = 0xE9; // JMP rel32 memcpy(&newJump[1], &dwRelativeAddr, sizeof(pNewFunc)); #elif _M_X64 - // We must use R10 or R11, because these are "scratch" registers - // which need not to be preserved accross function calls - // For more info see: Register Usage for x64 64-Bit + // We must use R10 or R11 because these are "scratch" registers + // that do not need to be preserved across function calls. + // For more information, see: Register Usage for x64 64-Bit // http://msdn.microsoft.com/en-us/library/ms794547.aspx - // Thanks to Matthew Smith!!! + // Thanks to Matthew Smith. newJump[0] = 0x49; // MOV R11, ... newJump[1] = 0xBB; // ... memcpy(&newJump[2], &pNewFunc, sizeof(pNewFunc)); @@ -264,22 +264,22 @@ CCallStack::CCallStack(BOOL dontSuspend) OldUnhandledExceptionFilter = SetUnhandledExceptionFilter(TopLevelExceptionFilter); // Try to disable the unhandled exception filter for subsequent calls. - // When a DLL library (plugin, shell extension) that uses a different RTL is - // loaded into Salamander process, that RTL installs this filter during its - // initialization. Additionally, starting with MSVC 2005, various sanity checks no - // longer throw exceptions but instead print a message and directly call + // If a DLL (plugin, shell extension) that uses a different RTL is loaded + // into the Salamander process, that RTL takes over this filter during its + // initialization. Also, since MSVC 2005, various sanity checks no longer + // throw exceptions, but instead display a message and call // UnhandledExceptionFilter(), which opens the Watson dialog. - // For example, Salamander used to crash without a bug report - // from TortoiseSVN shell extension. The call below should - // ensure we catch all unhandled crashes including MSVC 2005 sanity - // checks. + // This used to make Salamander crash without a bug report, for example + // with the TortoiseSVN shell extension. + // The following call should let us catch all unhandled crashes, including + // MSVC 2005 sanity checks. // - // More on this topic in "A proposal to make Dr.Watson invocation configurable": + // More on this topic: "A proposal to make Dr.Watson invocation configurable": // http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=101337 - // and two hardcore solutions: + // and two hard-core solutions: // http://www.debuginfo.com/articles/debugfilters.html // http://blog.kalmbachnet.de/?postid=75 - // 3/2012 - update pro x64: http://blog.kalmbach-software.de/2008/04/02/unhandled-exceptions-in-vc8-and-above-for-x86-and-x64/ + // 3/2012 - x64 update: http://blog.kalmbach-software.de/2008/04/02/unhandled-exceptions-in-vc8-and-above-for-x86-and-x64/ PreventSetUnhandledExceptionFilter(); } @@ -359,7 +359,7 @@ CCallStack::~CCallStack() // TRACE_I("CCallStack::~CCallStack(): MonitoredItemsSize=" << MonitoredItemsSize); if (OldestItemIndex != -1) { - while (1) // go through the queue again and print final states of critical call-stack invocations + while (1) // Process the queue once more and print the final states of critical call-stack calls { if (!MonitoredItems[OldestItemIndex].NotAlreadyReported) // if it was already reported, print final values { @@ -404,7 +404,7 @@ CCallStack::~CCallStack() if (BugReportThread != NULL) { - // by ending this thread, the code enters here one more time because CCallStack exited for it as well + // when this thread terminates, execution reaches this code once more because CCallStack also exits for this thread SetEvent(TBRData.TerminateEvent); // terminate the bug report thread WaitForSingleObject(BugReportThread, 1000); // wait at most one second for the thread to finish NOHANDLES(CloseHandle(BugReportThread)); @@ -442,7 +442,7 @@ void CCallStack::ReleaseBeforeExitThreadBody() // TRACE_I("CCallStack::~CCallStack(): MonitoredItemsSize=" << MonitoredItemsSize); if (OldestItemIndex != -1) { - while (1) // go through the queue again and print final states of critical call-stack invocations + while (1) // go through the queue again and print the final values of critical call-stack invocations { if (!MonitoredItems[OldestItemIndex].NotAlreadyReported) // if it was already reported, print final values { @@ -620,10 +620,10 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = if (res != DIALOG_IGNORE) { HKEY hSalamander; - if (OpenKey(HKEY_CURRENT_USER, SalamanderConfigurationRoots[0], hSalamander)) // write data only if a configuration exists in the registry (hich should almost always be the cas) + if (OpenKey(HKEY_CURRENT_USER, SalamanderConfigurationRoots[0], hSalamander)) // write data only if a configuration exists in the registry (which should almost always be the case) { HKEY actKey; - if (OpenKey(hSalamander, SALAMANDER_CONFIG_REG, actKey)) // write data only if a configuration exists in the registry (hich should almost always be the cas) + if (OpenKey(hSalamander, SALAMANDER_CONFIG_REG, actKey)) // write data only if a configuration exists in the registry (which should almost always be the case) { CloseKey(actKey); if (CreateKey(hSalamander, SALAMANDER_CONFIG_REG, actKey)) @@ -791,7 +791,7 @@ int CCallStack::HandleException(EXCEPTION_POINTERS* e, DWORD shellExtCrashID, co // in the DEBUG version we check for a debugger; in SDK/RELEASE version we rather skip this test #if defined(_DEBUG) && !defined(ENABLE_BUGREPORT_DEBUGGING) if (IsDebuggerPresent()) // if the software is currently being debugged, showing the Bug Report dialog makes no sense - return EXCEPTION_CONTINUE_SEARCH; // pass the exception on ... the debugger will catch it + return EXCEPTION_CONTINUE_SEARCH; // propagate the exception further; the debugger will catch it #endif static char bugReportPath[MAX_PATH]; @@ -850,7 +850,7 @@ int CCallStack::HandleException(EXCEPTION_POINTERS* e, DWORD shellExtCrashID, co reportInThisThread = TBRData.EventProcessedRet == FALSE; // if generation failed in the thread, try here too } - // if the bug-report thread didn't run or failed to generate the report, we will try again in this thread + // if the bug-report thread did not run or failed to generate the report, we will try again in this thread if (reportInThisThread) { // Concurrent generation of two reports caused issues (with a 200 ms @@ -924,7 +924,7 @@ void CCallStack::CheckCallFrequency(DWORD_PTR callerAddress, LARGE_INTEGER* push act = MonitoredItemsSize - 1; } } - if (OldestItemIndex != -1) // first remove outdated items (make space for a new one) + if (OldestItemIndex != -1) // first remove stale items (make room for a new one) { while (1) { @@ -932,7 +932,7 @@ void CCallStack::CheckCallFrequency(DWORD_PTR callerAddress, LARGE_INTEGER* push break; else { - if (!MonitoredItems[OldestItemIndex].NotAlreadyReported) // if it was reported, print final values + if (!MonitoredItems[OldestItemIndex].NotAlreadyReported) // if it was already reported, log the final values { TRACE_I("Info for Too Frequently Used Call Stack Message: call address: 0x" << std::hex << MonitoredItems[OldestItemIndex].CallerAddress << std::dec << ", total push-time: " << (DWORD)(MonitoredItems[OldestItemIndex].PushesPerfTime * 1000 / CCallStack::SavedPerfFreq.QuadPart) << "ms, total number of calls in monitored period: " << MonitoredItems[OldestItemIndex].NumberOfCalls); } @@ -1003,7 +1003,7 @@ void CCallStack::CheckCallFrequency(DWORD_PTR callerAddress, LARGE_INTEGER* push // CCallStackMessage // -// so I do not include the entire intrin.h +// to avoid including the entire intrin.h extern "C" { void* _AddressOfReturnAddress(void); diff --git a/src/callstk.h b/src/callstk.h index 1d1c48daa..b5515cae7 100644 --- a/src/callstk.h +++ b/src/callstk.h @@ -39,8 +39,8 @@ struct CCallStackMonitoredItem DWORD_PTR CallerAddress; // address where the call-stack macro was invoked DWORD NumberOfCalls; // number of calls during the last CALLSTACK_TRACETIME milliseconds __int64 PushesPerfTime; // total "time" of Push operations for this call-stack macro - BOOL NotAlreadyReported; // TRUE = if the issue has not been reported - // (to avoid flooding the Trace Server) + BOOL NotAlreadyReported; // TRUE = the problem has not yet been reported + // (to avoid unnecessary flooding of the Trace Server) }; #endif // (defined(_DEBUG) || defined(CALLSTK_MEASURETIMES)) && !defined(CALLSTK_DISABLEMEASURETIMES) @@ -55,12 +55,12 @@ class CCallStack // terminating null, the length of the // previous string is always stored (two bytes) // followed immediately by the next string - char* End; // pointer to the last two zeros - int Skipped; // number of messages that could not be stored + char* End; // pointer to the last two nulls + int Skipped; // number of messages that could not be saved char* Enum; // pointer to the last printed text BOOL FirstCallstack; // are we the first instance? - const char* PluginDLLName; // plug-in DLL currently running in the thread + const char* PluginDLLName; // plugin DLL currently running in the thread // (NULL if it is salamand.exe) int PluginDLLNameUses; // the Pop() operation count at which PluginDLLName should be set to NULL // (nesting level) @@ -84,7 +84,7 @@ class CCallStack public: DWORD PushesCounter; // counter of Push calls invoked in this object (in one thread) LARGE_INTEGER PushPerfTimeCounter; // total time spent in Push calls invoked in this object (one thread) - LARGE_INTEGER IgnoredPushPerfTimeCounter; // total time spent in unmeasured (ignored) Push calls invoked here (one thread) + LARGE_INTEGER IgnoredPushPerfTimeCounter; // total time spent in unmeasured (ignored) Push calls invoked in this object (in one thread) static LARGE_INTEGER SavedPerfFreq; // nonzero result of QueryPerformanceFrequency #define CALLSTK_BENCHMARKTIME 100 // time in milliseconds during which the call-stack speed is measured static DWORD SpeedBenchmark; // how many measured call-stack macros can be pushed+poped within CALLSTK_BENCHMARKTIME milliseconds @@ -108,7 +108,7 @@ class CCallStack void Pop(); #endif // (defined(_DEBUG) || defined(CALLSTK_MEASURETIMES)) && !defined(CALLSTK_DISABLEMEASURETIMES) - // called only when storing a call-stack message from a plug-in + // called only when storing a call-stack message from a plugin void PushPluginDLLName(const char* dllName) { if (PluginDLLName == NULL) @@ -120,7 +120,7 @@ class CCallStack PluginDLLNameUses++; } - // called only when retrieving a call-stack message from a plug-in + // called only when retrieving a call-stack message from a plugin void PopPluginDLLName() { if (PluginDLLNameUses <= 1) @@ -193,7 +193,7 @@ class CCallStackMessage #if (defined(_DEBUG) || defined(CALLSTK_MEASURETIMES)) && !defined(CALLSTK_DISABLEMEASURETIMES) -extern BOOL __CallStk_T; // always TRUE - just to check format string and type of parameters of call-stack macros +extern BOOL __CallStk_T; // always TRUE; only used to check the format string and parameter types of call-stack macros #define CALL_STACK_MESSAGE1(p1) CCallStackMessage CALLSTK_UNIQUE(_m)(FALSE, 0, p1) #define CALL_STACK_MESSAGE2(p1, p2) CCallStackMessage CALLSTK_UNIQUE(_m)(FALSE, (__CallStk_T ? 0 : printf(p1, p2)), p1, p2) diff --git a/src/cfgdlg.h b/src/cfgdlg.h index d5d7882d0..442fc22ab 100644 --- a/src/cfgdlg.h +++ b/src/cfgdlg.h @@ -198,7 +198,6 @@ struct CConfiguration SaveWorkDirs, // store the List of Working Directories? EnableCmdLineHistory, // keep history of the command line? SaveCmdLineHistory, // store the command line history? - // LantasticCheck, // Lantastic 7.0 paranoid check (compare sizes after Copy) OnlyOneInstance, // allow just a single instance ForceOnlyOneInstance, // set from cmdline: Salamander should behave as if the OnlyOneInstance option is enabled StatusArea, // Salamander lives in the tray and won't appear in the taskbar when minimized @@ -223,7 +222,6 @@ struct CConfiguration TileSpacingVert, // vertical spacing in points between Tiles in the panel ThumbnailSpacingHorz, // horizontal spacing in points between Thumbnails in the panel ThumbnailSize, // square dimensions of thumbnails in points - // PanelTooltip, // shortened texts in panels get tooltips KeepPluginsSorted, // plugins will be sorted alphabetically (plugins manager, menu) ShowSLGIncomplete, // TRUE = if IsSLGIncomplete is not empty, show message about incomplete translation (we are looking for a translator) @@ -254,7 +252,7 @@ struct CConfiguration CnfrmCopyMoveOptionsNS, // Copy/Move: some Options are set but the target is FS/archive (options are NotSupported) // Drive specific - DrvSpecFloppyMon, // Use automatic refresh + DrvSpecFloppyMon, // Use automatic monitoring DrvSpecFloppySimple, // Use simple icons DrvSpecRemovableMon, DrvSpecRemovableSimple, @@ -274,7 +272,7 @@ struct CConfiguration int CompareSubdirs; int CompareSubdirsAttr; int CompareOnePanelDirs; // mark names of directories that exist only in one panel - int CompareMoreOptions; // is the dialog displayed in extended mode? + int CompareMoreOptions; // is the dialog shown in expanded mode? int CompareIgnoreFiles; // should specified filenames be ignored? int CompareIgnoreDirs; // should specified names of directories be ignored? CMaskGroup CompareIgnoreFilesMasks; @@ -351,7 +349,7 @@ struct CConfiguration SavePosition; // store window position / place relative to the main window CMaskGroup TextModeMasks; // mask array for files always shown in text mode - CMaskGroup HexModeMasks; // mask array for files always shown in hex mode + CMaskGroup HexModeMasks; // mask group for files always shown in hex mode WINDOWPLACEMENT WindowPlacement; // invalid unless SavePosition != TRUE @@ -405,7 +403,7 @@ struct CConfiguration // int ShowTipOfTheDay; // display Tip of the Day at program startup // int LastTipOfTheDay; // index of the last displayed tip - // plug-ins + // plugins int LastPluginVer; // ACTUAL_VERSION from plugins.ver (detect newly installed plugins) int LastPluginVerOP; // ACTUAL_VERSION from plugins.ver for the other platform (x86/x64); must be saved, otherwise we won't know if the configuration was overwritten by the other version. // Example: start x64, auto-save x64 with added pictview, start x86, auto-save x86 with added winscp (x86 pictview not added because it was already in the x64 config), exit/save x86, WARNING: exit/save x64 would remove the record of winscp (x64 knows nothing about winscp and continues running) @@ -432,7 +430,7 @@ struct CConfiguration BOOL PrepareRecycleMasks(int& errorPos); // prepare recycle-bin masks for use BOOL AgreeRecycleMasks(const char* fileName, const char* fileExt); - DWORD LastFocusedPage; // last visited page in the dialog + DWORD LastFocusedPage; // last focused page in the dialog DWORD ConfigurationHeight; // height of the configuration dialog in points BOOL ViewersAndEditorsExpanded; // expanded items in the tree BOOL PackersAndUnpackersExpanded; @@ -447,13 +445,13 @@ struct CConfiguration char SLGName[MAX_PATH]; // xxxxx.slg to use next time Salamander starts int DoNotDispCantLoadPluginSLG; // TRUE = suppress warning that an SLG with the same name cannot be loaded into the plugin as in Salamander int DoNotDispCantLoadPluginSLG2; // TRUE = suppress warning that the SLG plugin used last time (either user-selected or auto-selected) cannot be loaded - int UseAsAltSLGInOtherPlugins; // TRUE = try to use AltSLGName for plugins + int UseAsAltSLGInOtherPlugins; // TRUE = try to use AltPluginSLGName for plugins char AltPluginSLGName[MAX_PATH]; // only if UseAsAltSLGInOtherPlugins is TRUE: fallback SLG module for plugins (if LoadedSLGName for plugin does not exist) // Directory name convert\\XXX\\convert.cfg from which convert.cfg is loaded char ConversionTable[MAX_PATH]; - int TitleBarShowPath; // will we display the path in the title bar? + int TitleBarShowPath; // display the path in the title bar? int TitleBarMode; // title bar display mode (TITLE_BAR_MODE_xxx) int UseTitleBarPrefix; // should prefix be shown in the title bar? char TitleBarPrefix[TITLE_PREFIX_MAX]; // prefix for the title bar @@ -671,7 +669,7 @@ class CCfgPageUserMenu : public CCommonPropSheetPage void EnableButtons(); virtual INT_PTR DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam); - void DeleteSubmenuEnd(int index); // for opening the selected submenu ('index') remove the closing item + void DeleteSubmenuEnd(int index); // deletes the closing item for the selected submenu ('index') void RefreshGroupIconInUMItems(); // after changing colors, HGroupIcon changes; we must update it in UserMenuItems as well @@ -697,7 +695,7 @@ class CCfgPageHotPath : public CCommonPropSheetPage BOOL DisableNotification; BOOL EditMode; int EditIndex; - BOOL LabelEdit; // we are editing a label + BOOL LabelEdit; // label edit mode public: CCfgPageHotPath(BOOL editMode, int editIndex); diff --git a/src/codetbl.cpp b/src/codetbl.cpp index a08f25705..87ae34bfa 100644 --- a/src/codetbl.cpp +++ b/src/codetbl.cpp @@ -975,7 +975,7 @@ void CCodeTables::RecognizeFileType(const char* pattern, int patternLen, BOOL fo } if (*s >= 128) nonAscii++; - if (IsNotAlphaNorNum[*s]) // character is neither alpha nor numeric + if (IsNotAlphaNorNum[*s]) // character is not alphanumeric { if (*s == '?') { @@ -1066,11 +1066,12 @@ void CCodeTables::RecognizeFileType(const char* pattern, int patternLen, BOOL fo s++; } - if (s == end) // this is a text - // && penalty / patternLen <= 5) // and not a totally unreadable mess (Lukas' test: - // characters 0x04 -> only EBCDIC passed, but ratio was - // 10 -> unreadable) - WARNING: unusable because - // configuraiton files and .inf files also look like complete mess based on 'penalty' + if (s == end) // this is text + // && penalty / patternLen <= 5) // and it is not a completely unreadable mess (Lukas's test: + // characters 0x04 -> only EBCDIC passed, but the ratio was + // 10 -> unreadable) - WARNING: unusable, because + // configuration files and .inf files also look like a complete mess + // according to 'penalty' { if (isText != NULL) *isText = TRUE; @@ -1082,7 +1083,7 @@ void CCodeTables::RecognizeFileType(const char* pattern, int patternLen, BOOL fo strcpy(codePage, lastCodePage); if (i == -1 && nonAscii * 200 < patternLen) - break; // under 0.5% non-ASCII characters -> ASCII, stop searching + break; // fewer than 0.5% non-ASCII characters -> ASCII, stop searching } } } @@ -1140,4 +1141,4 @@ int CCodeTables::GetConversionToWinCodePage(const char* codePage) } } return -1; // not found -} \ No newline at end of file +} diff --git a/src/codetbl.h b/src/codetbl.h index b1afc32bf..72aa20a1a 100644 --- a/src/codetbl.h +++ b/src/codetbl.h @@ -70,16 +70,16 @@ class CCodeTables // otherwise it returns FALSE BOOL GetPreloadedIndex(const char* dirName, int* index); - // selects the best matching item from the Preloaded array + // Selects the best matching item from the Preloaded array // cfgDirName points to the recommended directory name (from the configuration) - // dirName must point to a buffer of MAX_PATH characters where the directory name is returned; - // if none exists, an empty string is returned - // criteria: + // dirName must point to a buffer of size MAX_PATH where the directory name is returned; + // if no such item exists, an empty string is returned + // Criteria: // 1. cfgDirName - // 2. item matching the OS code page + // 2. Item matching the OS code page // 3. westeuro - // 4. first in the list - // 5. if there is no item in the list, we will return an empty string + // 4. First item in the list + // 5. If the list is empty, an empty string is returned void GetBestPreloadedConversion(const char* cfgDirName, char* dirName); // prepares the object for use (loads 'convert.cfg' script), hWindow is the parent window for message boxes diff --git a/src/color.cpp b/src/color.cpp index 6595f11f7..595e07a86 100644 --- a/src/color.cpp +++ b/src/color.cpp @@ -36,7 +36,7 @@ void ColorRGBToHLS(COLORREF clrRGB, WORD* pwHue, WORD* pwLuminance, WORD* pwSatu int h, l, s; // output HLS values WORD cMax, cMin; // max and min RGB values WORD cSum, cDif; - int rDelta, gDelta, bDelta; // intermediate value: % of spread from max + int rDelta, gDelta, bDelta; // intermediate value: % of the spread from the maximum // get R, G, and B out of DWORD r = GetRValue(clrRGB); @@ -95,7 +95,7 @@ WORD HueToRGB(WORD n1, WORD n2, WORD hue) if (hue > HLSMAX) hue -= HLSMAX; - // return r,g, or b value from this tridrant + // return the r, g, or b value for this hue segment if (hue < (HLSMAX / 6)) return (n1 + (((n2 - n1) * hue + (HLSMAX / 12)) / (HLSMAX / 6))); if (hue < (HLSMAX / 2)) @@ -109,7 +109,7 @@ WORD HueToRGB(WORD n1, WORD n2, WORD hue) COLORREF ColorHLSToRGB(WORD wHue, WORD wLuminance, WORD wSaturation) { WORD r, g, b; // RGB component values - WORD magic1, magic2; // calculated magic numbers (really!) + WORD magic1, magic2; // computed magic numbers if (wSaturation == 0) { // achromatic case diff --git a/src/common/allochan.cpp b/src/common/allochan.cpp index 48c360e49..5a5492cc2 100644 --- a/src/common/allochan.cpp +++ b/src/common/allochan.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -28,15 +29,15 @@ // boundaries so we can find the real functions // that we need to call for initialization. -#pragma warning(disable : 4075) // chceme definovat poradi inicializace modulu +#pragma warning(disable : 4075) // We want to define the module initialization order. typedef void(__cdecl* _PVFV)(void); #pragma section(".i_alc$a", read) -__declspec(allocate(".i_alc$a")) const _PVFV i_allochan = (_PVFV)1; // na zacatek sekce .i_alc si dame promennou i_allochan +__declspec(allocate(".i_alc$a")) const _PVFV i_allochan = (_PVFV)1; // Place i_allochan at the start of section .i_alc. #pragma section(".i_alc$z", read) -__declspec(allocate(".i_alc$z")) const _PVFV i_allochan_end = (_PVFV)1; // a na konec sekce .i_alc si dame promennou i_allochan_end +__declspec(allocate(".i_alc$z")) const _PVFV i_allochan_end = (_PVFV)1; // Place i_allochan_end at the end of section .i_alc. void Initialize__Allochan() { @@ -56,8 +57,8 @@ class C__AllocHandlerInit C__AllocHandlerInit() { InitializeCriticalSection(&CriticalSection); - OldNewHandler = _set_new_handler(AltapNewHandler); // operator new ma volat pri nedostatku pameti nas new-handler - OldNewMode = _set_new_mode(1); // malloc ma volat pri nedostatku pameti nas new-handler + OldNewHandler = _set_new_handler(AltapNewHandler); // Have operator new call our new-handler on out-of-memory. + OldNewMode = _set_new_mode(1); // Have malloc call our new-handler on out-of-memory. } ~C__AllocHandlerInit() { @@ -101,7 +102,7 @@ int C__AllocHandlerInit::AltapNewHandler(size_t size) int ret = 1; int ti = GetTickCount(); EnterCriticalSection(&__AllocHandlerInit.CriticalSection); - if (GetTickCount() - ti <= 500) // message-box budeme ukazovat jen pokud jsme pred momentem usera nenutili resit stejny problem v jinem threadu + if (GetTickCount() - ti <= 500) // Show the message box only if another thread did not just make the user deal with the same problem. { TCHAR buf[550]; _sntprintf_s(buf, _countof(buf) - 1, __AllocHandlerMessage, size); @@ -112,7 +113,7 @@ int C__AllocHandlerInit::AltapNewHandler(size_t size) if (res == 0) { TRACE_ET(_T("AltapNewHandler: unable to open message-box!")); - Sleep(1000); // nechame masinu oddechnout a zkusime ukazat msgbox znovu + Sleep(1000); // Give the system a moment, then try to show the message box again. } } while (res == 0); if (res == IDABORT) // terminate @@ -123,15 +124,15 @@ int C__AllocHandlerInit::AltapNewHandler(size_t size) if (res == 0) { TRACE_ET(_T("AltapNewHandler: unable to open message-box with abort-warning!")); - Sleep(1000); // nechame masinu oddechnout a zkusime ukazat msgbox znovu + Sleep(1000); // Give the system a moment, then try to show the message box again. } } while (res == 0); if (res == IDYES) - TerminateProcess(GetCurrentProcess(), 777); // tvrdsi exit (ExitProcess jeste neco vola) + TerminateProcess(GetCurrentProcess(), 777); // Hard terminate the process (ExitProcess still runs additional code). } else { - if (res == IDIGNORE) // uzivatel chce poslat problem alokace do aplikace (return NULL), mista, kde se alokuji velke bloky by mely byt osetrene (jinak to spadne pri pristupu na NULL) + if (res == IDIGNORE) // Let the application handle the allocation failure (return NULL); call sites that allocate large blocks should check for this, or they will crash on NULL dereference. { do { @@ -139,16 +140,16 @@ int C__AllocHandlerInit::AltapNewHandler(size_t size) if (res == 0) { TRACE_ET(_T("AltapNewHandler: unable to open message-box with ignore-warning!")); - Sleep(1000); // nechame masinu oddechnout a zkusime ukazat msgbox znovu + Sleep(1000); // Give the system a moment, then try to show the message box again. } } while (res == 0); if (res == IDYES) - ret = 0; // vracime NULL do aplikace + ret = 0; // Return NULL to the application. } } } LeaveCriticalSection(&__AllocHandlerInit.CriticalSection); - return ret; // retry nebo NULL + return ret; // Either retry or return NULL. } #endif // ALLOCHAN_DISABLE diff --git a/src/common/allochan.h b/src/common/allochan.h index 4e570035d..45ccd94da 100644 --- a/src/common/allochan.h +++ b/src/common/allochan.h @@ -1,26 +1,20 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once -// Zavadi handler pro reseni situace, kdy dosla pamet pri volani operatoru new nebo -// funkce malloc (tu pouzivaji calloc, realloc a dalsi, viz help). Zarucuje, ze ani -// operator new ani malloc nikdy bez vedomi uzivatele nevrati NULL. Zobrazuje -// messagebox s chybou "nedostatek pameti" a uzivatel muze po zavreni dalsich -// aplikaci zopakovat pokus o alokaci pameti. Uzivatel muze tez terminovat proces -// nebo nechat propadnout chybu alokace do aplikace (operator new nebo malloc -// vrati NULL, alokace velkych bloku pameti by na to mely byt pripravene, jinak -// dojde k padu - uzivatel je o tom informovany). +// Installs a handler for out-of-memory conditions during calls to operator new or malloc (also used by calloc, realloc, and others; see help). It guarantees that neither operator new nor malloc returns NULL without notifying the user. It displays an "insufficient memory" message box, and after closing other applications the user can retry the allocation. The user can also terminate the process or let the allocation failure propagate to the application (operator new or malloc then returns NULL; allocations of large memory blocks should be prepared for this, otherwise the application may crash, and the user is warned about that). -// nastaveni lokalizovane podoby hlasky o nedostatku pameti a varovnych hlasek -// (pokud se string nema menit, pouzijte NULL); ocekavany obsah zni: +// Sets the localized text of the out-of-memory message and warning messages +// (use NULL if a string should remain unchanged); expected contents: // message: // Insufficient memory to allocate %u bytes. Try to release some memory (e.g. // close some running application) and click Retry. If it does not help, you can // click Ignore to pass memory allocation error to this application or click Abort // to terminate this application. -// title: (pouziva se pro oboji: "message" i "warning") -// doporucujeme pouzit jmeno aplikace, at user vi, ktera aplikace si stezuje +// title: (used for both "message" and "warning") +// We recommend using the application name so the user knows which application is reporting the problem // warningIgnore: // Do you really want to pass memory allocation error to this application?\n\n // WARNING: Application may crash and then all unsaved data will be lost!\n diff --git a/src/common/array.cpp b/src/common/array.cpp index 91088a3a3..c9aa91955 100644 --- a/src/common/array.cpp +++ b/src/common/array.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" diff --git a/src/common/array.h b/src/common/array.h index d311131f8..2ea3e0ba1 100644 --- a/src/common/array.h +++ b/src/common/array.h @@ -1,15 +1,16 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once -// Use the _DEBUG or __ARRAY_DEBUG defines to enable various error state checking. Errors -// are displayed using TRACE_E and TRACE_C macros. -// Use the SAFE_ALLOC define to remove source code with testing if memory allocation -// has not failed (see allochan.*). +// Use the _DEBUG or __ARRAY_DEBUG defines to enable various error-state checks. Errors +// are displayed using the TRACE_E and TRACE_C macros. +// Use the SAFE_ALLOC define to remove code that tests whether memory allocation +// failed (see allochan.*). -// We need to make this module independent on TRACE macros, so if they are not defined, -// we define their fakes. Certainly error reporting will not work in such situation. +// We need to make this module independent of the TRACE macros, so if they are not defined, +// we define dummy replacements. Error reporting will not work in that case. #if !defined(TRACE_I) && !defined(TRACE_E) && !defined(TRACE_C) inline void __TraceEmptyFunction() {} #define TRACE_I(str) __TraceEmptyFunction() @@ -32,8 +33,8 @@ enum CDeleteType enum CErrorType { etNone, // OK - etLowMemory, // new - NULL - etUnknownIndex, // index is out of array range + etLowMemory, // new returned NULL + etUnknownIndex, // index is out of range for the array etBadInsert, // index of inserted item is out of array range etBadDispose, // index of disposed item is out of array range etDestructed, // array was already destructed using Destroy() method @@ -47,26 +48,25 @@ std::ostream& operator<<(std::ostream& out, const CErrorType& err); // **************************************************************************** // TDirectArray: -// -behaves like classic array, in addition it can pre-allocate to bigger or -// smaller (look at constructor 'base' and 'delta' values). -// -when adding item to array, copy-constructor is called -// -when deleting item, item destructor is called, you can change this behaviour, -// see CallDestructor method -// -you can use this array for simple types and also for objects which does not -// contain pointers to its own data, reason: -// objects are moved in array (e.g. when reallocating array or when inserting -// item to the beginning of array) simply by using memmove, so during these -// moves contructors/destructors are not called, example: -// char Path[MAX_PATH]; // full file name -// char *Name; // points to 'Path' to file name (without path) -// SOLUTION: store only offsets instead of complete pointers +// - behaves like a classic array but can pre-allocate either more or less +// space (see the constructor parameters 'base' and 'delta') +// - calls the copy constructor when an item is added +// - calls the destructor when an item is removed; use CallDestructor to adjust +// that behavior if necessary +// - suitable for simple types and objects that do not hold pointers to their +// own data; items are shifted within the array (for example, when the +// array is reallocated or an item is inserted at the beginning) with +// memmove, so constructors and destructors are not invoked. Example: +// char Path[MAX_PATH]; // full file name +// char* Name; // points within 'Path' to the file name (without the path) +// Solution: store only offsets instead of raw pointers template class TDirectArray { public: - CErrorType State; // etNone if array is OK, otherwise some error occured - int Count; // current count of items in array + CErrorType State; // etNone if array is OK, otherwise an error occurred + int Count; // current number of items in the array TDirectArray(int base, int delta); virtual ~TDirectArray() { Destroy(); } @@ -79,12 +79,12 @@ class TDirectArray } void Insert(int index, const DATA_TYPE& member); - int Add(const DATA_TYPE& member); // adds item to the end of array, returns item index + int Add(const DATA_TYPE& member); // adds an item to the end of the array, returns its index - void Insert(int index, const DATA_TYPE* members, int count); // insert 'count' of 'members' items - int Add(const DATA_TYPE* members, int count); // add 'count' of 'members' items + void Insert(int index, const DATA_TYPE* members, int count); // insert 'count' items from 'members' + int Add(const DATA_TYPE* members, int count); // adds 'count' items from 'members' - DATA_TYPE& At(int index) // returns pointer to item at 'index' possition + DATA_TYPE& At(int index) // returns a reference to the item at 'index' { #if defined(_DEBUG) || defined(__ARRAY_DEBUG) if (index >= 0 && index < Count) @@ -96,12 +96,12 @@ class TDirectArray TRACE_C("Index is out of range (index = " << index << ", Count = " << Count << ")."); Error(etUnknownIndex); - return Data[0]; // because of compiler we must return (invalid) item + return Data[0]; // return an (invalid) item to satisfy the compiler } #endif } - DATA_TYPE& operator[](int index) // returns pointer to item at 'index' possition + DATA_TYPE& operator[](int index) // returns a reference to the item at position 'index' { #if defined(_DEBUG) || defined(__ARRAY_DEBUG) if (index >= 0 && index < Count) @@ -113,7 +113,7 @@ class TDirectArray TRACE_C("Index is out of range (index = " << index << ", Count = " << Count << ")."); Error(etUnknownIndex); - return Data[0]; // because of compiler we must return (invalid) item + return Data[0]; // return an (invalid) item to satisfy the compiler } #endif } @@ -130,10 +130,10 @@ class TDirectArray void DestroyMembers(); // release items from memory (calling destructors), keep array void DetachMembers(); // detach all items (destructors are NOT called), keep array void Destroy(); // complete array destruction (calling destructors) - void Delete(int index); // delete item at 'index' possition (calling destructor), move remaining items - void Delete(int index, int count); // delete 'count' of items at 'index' possition (calling destructors), move remaining items - void Detach(int index); // detach item at 'index' possition (destructor is NOT called), move remaining items - void Detach(int index, int count); // detach 'count' of items at 'index' possition (destructors are NOT called), move remaining items + void Delete(int index); // delete the item at position 'index' (calls the destructor) and shift the rest + void Delete(int index, int count); // delete 'count' items at position 'index' (calls destructors) and shift the rest + void Detach(int index); // detach the item at position 'index' (does NOT call the destructor) and shift the rest + void Detach(int index, int count); // detach 'count' items at position 'index' (does NOT call destructors) and shift the rest int SetDelta(int delta); // change 'Delta', return real used value; NOTE: can be used only for empty array @@ -143,7 +143,7 @@ class TDirectArray int Base; // smallest allocated size of array int Delta; // allocated array size is enlarged/reduced by this value - virtual void Error(CErrorType err) // array error handling + virtual void Error(CErrorType err) // handles array errors { if (State == etNone) State = err; @@ -153,7 +153,7 @@ class TDirectArray void EnlargeArray(); // enlarges array void ReduceArray(); // reduces array - void Move(CArrayDirection direction, int first, int count); // move selected items to next/previous index + void Move(CArrayDirection direction, int first, int count); // moves selected items to the next or previous index void CallCopyConstructor(DATA_TYPE* placement, const DATA_TYPE& member) { @@ -182,14 +182,14 @@ class TDirectArray virtual void CallDestructor(DATA_TYPE& member) { member.~DATA_TYPE(); } -private: // following methods will not be called (prevention) +private: // prevent calls to the following methods TDirectArray() {} TDirectArray(const TDirectArray&) {} TDirectArray& operator=(TDirectArray&) { return *this; } - // compiler reports error on this line: we have just wanted to catch source code designed for - // older version of TDirectArray template: use CallDestructor instead of Destructor and please - // notice that in new version of TDirectArray copy-constructors and destructors are called + // the compiler reports an error on this line: we only want to catch source code written for + // an older version of the TDirectArray template; use CallDestructor instead of Destructor, and + // note that in the new version of TDirectArray copy constructors and destructors are called virtual int Destructor(int) { return 0; } }; @@ -267,10 +267,10 @@ class TIndirectArray : public CArray // **************************************************************************** // TIndirectClassArray: -// -vhodne pro ulozeni ukazatelu na objekty, neumoznuje zmenu indexu prvku -// -nad polem se neprovadi zadne operace sesunu prvku - prvek zustava -// stale na stejnem indexu -// -pri pridavani prvku se vyplnuji mezery vznikle predchozim uvolnovanim prvku +// -suitable for storing pointers to objects; element indexes do not change +// -no element-shifting operations are performed on the array, so an element +// always stays at the same index +// -when adding elements, gaps created by earlier removals are filled template class TIndirectClassArray : public TIndirectArray @@ -302,7 +302,7 @@ class TIndirectClassArray : public TIndirectArray FirstFreeIndex = 0; } -protected: // prevence proti volani nefunkcniho kodu (posouva prvky,...) +protected: // prevent calls to code that does not work (moves items, ...) void Move(CArrayDirection, int, int) {} void Insert(int, void*) {} void Insert(int, void**, int) {} @@ -315,24 +315,24 @@ class TIndirectClassArray : public TIndirectArray // **************************************************************************** // TSmallerDirectArray: -// -popis viz TDirectArray, ale neni vhodne pro ulozeni objektu (nevola -// konstruktory ani destruktory), specializace: setri pamet potrebnou -// na spravu pole tim, ze umoznuje celkovy pocet prvku pole jen 65535 - misto -// int WORD a nema virtualni metodu CallDestructor -// -vhodne jako promenna (atribut) tridy, od ktere existuje mhoho objektu -// -pametove naroky: 6 B (jen +2 B oproti klas. poli), (TDirectArray ma 25 B) -// -zmenseni za cenu generovani tridy podle sablony pro ruzne 'Base', 'Delta' -// a zmenseni rozsahu pole - -template // jen 65535 prvku +// -see TDirectArray for a description, but it is not suitable for storing objects (it does not call +// constructors or destructors); the specialization saves memory needed to +// manage the array by allowing only 65535 elements, using WORD instead of +// int, and by not having a virtual CallDestructor method +// -suitable as a member variable of a class with many instances +// -memory requirements: 6 B (only 2 B more than the classic array); TDirectArray has 25 B +// -smaller at the cost of generating the class from the template for different 'Base', 'Delta' +// values and reducing the array range + +template // only 65535 items class TSmallerDirectArray { public: #if defined(_DEBUG) || defined(__ARRAY_DEBUG) - CErrorType State; // neni-li etNone stala se chyba + CErrorType State; // if not etNone, an error has occurred #endif - DATA_TYPE* Data; // ukazatel na pole, public nutne misto etDestructed - WORD Count; // soucasny pocet polozek v kolekci + DATA_TYPE* Data; // pointer to the array; stays public because we do not track etDestructed here + WORD Count; // current item count in the collection TSmallerDirectArray(); ~TSmallerDirectArray() { Destroy(); } @@ -355,12 +355,12 @@ class TSmallerDirectArray } void Insert(int index, const DATA_TYPE& member); - inline WORD Add(const DATA_TYPE& member); // prida prvek na konec Arraye, - // vraci index prvku - WORD Add(const DATA_TYPE* members, int count); // pridani count prvku members + inline WORD Add(const DATA_TYPE& member); // adds an item to the end of the array, + // returns the item index + WORD Add(const DATA_TYPE* members, int count); // adds 'count' items from 'members' - DATA_TYPE& At(int index) // vraci ukazatel na prvek na pozici - { // int pouzity jen kvuli warningum - rozsah do 65535 + DATA_TYPE& At(int index) // returns a reference to the item at 'index' + { // int is used only to avoid warnings; range up to 65535 #if defined(_DEBUG) || defined(__ARRAY_DEBUG) if (index >= 0 && index < Count) #endif @@ -371,13 +371,13 @@ class TSmallerDirectArray TRACE_C("Index is out of range (index = " << index << ", Count = " << Count << ")."); Error(etUnknownIndex); - return Data[0]; // kvuli kompileru vracim mozna neplatny prvek + return Data[0]; // compiler workaround: return a possibly invalid item } #endif } - DATA_TYPE& operator[](int index) // vraci ukazatel na prvek na pozici - { // int pouzity jen kvuli warningum - rozsah do 65535 + DATA_TYPE& operator[](int index) // returns a reference to the item at the given position + { // int is used only to avoid warnings; range up to 65535 #if defined(_DEBUG) || defined(__ARRAY_DEBUG) if (index >= 0 && index < Count) #endif @@ -388,7 +388,7 @@ class TSmallerDirectArray TRACE_C("Index is out of range (index = " << index << ", Count = " << Count << ")."); Error(etUnknownIndex); - return Data[0]; // kvuli kompileru vracim mozna neplatny prvek + return Data[0]; // return a possibly invalid element to satisfy the compiler } #endif } @@ -404,15 +404,15 @@ class TSmallerDirectArray DATA_TYPE* GetData() { return Data; } - void DestroyMembers(); // uvolni z pameti jen prvky, pole necha - void Destroy(); // kompletni destrukce objektu - void Delete(int index); // zrusi prvek na pozici a ostatni posune - void Reduce(WORD newCount); // zrusi prvky od indexu newCount az do konce - void Delete(WORD from, WORD to); // zrusi prvky (const TSmallerDirectArray&) {} TSmallerDirectArray& operator=(TSmallerDirectArray&) { @@ -435,19 +435,18 @@ class TSmallerDirectArray // **************************************************************************** // TClassArray: -// -vhodne pro ulozeni mnoha malych objektu, neumoznuje zmenu indexu prvku -// -alokuje objekty CLASS_TYPE primo do pole, -// provadi se volani konstruktoru i destruktoru techto objektu -// -nad polem se neprovadi zadne operace sesunu prvku - prvek zustava -// stale na stejnem indexu -// -platny prvek pole: (index_prvku < Count && !At(index_prvku).IsEmpty()) +// - suitable for storing many small objects; element indexes do not change +// - allocates CLASS_TYPE objects directly in the array and calls their +// constructors and destructors +// - never shifts entries within the array, so each item remains at the same index +// - an array slot is valid if (item_index < Count && !At(item_index).IsEmpty()) // -// naroky na CLASS_TYPE: -// 1) existence metody IsEmpty(), ktera vraci jestli uz se volal -// destruktor objektu -// 2) nadefinovani operatoru 'new' pomoci makra DEFINE_NEW(CLASS_TYPE) +// requirements on CLASS_TYPE: +// 1) provide the IsEmpty() method that returns whether the destructor has +// already been called +// 2) define the 'new' operator using the DEFINE_NEW(CLASS_TYPE) macro // -// priklad: +// Example: // class CSimpleObject // { // public: @@ -463,10 +462,10 @@ class TSmallerDirectArray // // TClassArray Simples(10, 5); // -// pridani prvku do pole: -// int index_prvku = Simples.FirstFreeIndex; // prvni volny index v poli -// new (&Simples)CSimpleObject(); // vraci adresu objektu, pri chybe NULL, -// // prvek byl pridan a ma index index_prvku +// Adding an item to the array: +// int item_index = Simples.FirstFreeIndex; // first free index in the array +// new (&Simples)CSimpleObject(); // returns the object address, NULL on error, +// // item was added and has index item_index template class TClassArray : public TDirectArray @@ -498,14 +497,14 @@ class TClassArray : public TDirectArray ~TClassArray() { Destroy(); } -private: // prevence proti volani nefunkcniho kodu (posouva prvky ...) +private: // prevent calls to code that does not work (moves items, ...) void Insert(int, const CLASS_TYPE&) {} void Insert(int, const CLASS_TYPE*, int) {} int Add(const CLASS_TYPE&) { return ULONG_MAX; } int Add(const CLASS_TYPE*, int) { return ULONG_MAX; } void Delete(int) {} void Move(CArrayDirection, int, int) {} - void DetachMembers() {} // to by nezavolalo destruktory + void DetachMembers() {} // that would not call destructors }; #define DEFINE_NEW(CLASS_TYPE) \ @@ -695,7 +694,7 @@ TDirectArray::TDirectArray(int base, int delta) template void TDirectArray::Destroy() { - if (State == etNone) // it can be also etDestructed + if (State == etNone) // State can also be etDestructed { if (Data != NULL) { @@ -784,7 +783,7 @@ void TDirectArray::Insert(int index, const DATA_TYPE* members, int co #if defined(_DEBUG) || defined(__ARRAY_DEBUG) if (State == etNone) { - if (Count + count > Available && members + count - 1 >= Data && // array will be reallocated and inserted items are from this array (items will be released after array reallocation) + if (Count + count > Available && members + count - 1 >= Data && // array will be reallocated and the inserted items come from this array (the items will be released after reallocation) members < Data + Count) { TRACE_C("Inserted items could become invalid during operation."); @@ -1190,7 +1189,7 @@ template void TSmallerDirectArray::Destroy() { #if defined(_DEBUG) || defined(__ARRAY_DEBUG) - if (State == etNone) // muze prijit etDestructed + if (State == etNone) // State can also be etDestructed { #endif if (Data != NULL) @@ -1352,7 +1351,7 @@ void TSmallerDirectArray::DestroyMembers() } template -void // int pouzity jen kvuli warningum - rozsah do 65535 +void // int is used only to avoid warnings; range up to 65535 TSmallerDirectArray::Delete(int index) { #if defined(_DEBUG) || defined(__ARRAY_DEBUG) diff --git a/src/common/crc32.cpp b/src/common/crc32.cpp index f084873ef..0749b5b91 100644 --- a/src/common/crc32.cpp +++ b/src/common/crc32.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -75,15 +76,15 @@ void MakeCrcTable(DWORD* crcTab) const DWORD poly = 0xedb88320L; //polynomial exclusive-or pattern /* - //generate crc polonomial, using precomputed poly should be faster - // terms of polynomial defining this crc (except x^32): - static const Byte p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; + // Generate the CRC polynomial; using a precomputed poly should be faster + // Terms of the polynomial defining this CRC (except x^32): + static const Byte p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; - // make exclusive-or pattern from polynomial (0xedb88320L) - poly = 0L; - for (n = 0; n < sizeof(p)/sizeof(Byte); n++) - poly |= 1L << (31 - p[n]); -*/ + // Make the exclusive-or pattern from the polynomial (0xedb88320L) + poly = 0L; + for (n = 0; n < sizeof(p)/sizeof(Byte); n++) + poly |= 1L << (31 - p[n]); + */ for (n = 0; n < 256; n++) { c = (DWORD)n; diff --git a/src/common/crc32.h b/src/common/crc32.h index c6d2cecf4..e50650ac6 100644 --- a/src/common/crc32.h +++ b/src/common/crc32.h @@ -1,11 +1,12 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once //#define STATIC_CRC_TAB -//size of crc tab in the memory +// size of the CRC table in memory #define CRC_TAB_SIZE 256 * sizeof(DWORD) //initial value of crc shift register #define INIT_CRC 0L @@ -15,7 +16,7 @@ extern const DWORD StaticCrcTab[256]; #endif -//fill up crc table +//populate the CRC table void MakeCrcTable(DWORD* crcTab); //run a set of bytes through the crc shift register, if buffer is a NULL diff --git a/src/common/dep/crypt/fileenc.h b/src/common/dep/crypt/fileenc.h index 413afeb27..3664cff3b 100644 --- a/src/common/dep/crypt/fileenc.h +++ b/src/common/dep/crypt/fileenc.h @@ -36,13 +36,13 @@ */ /* - Pouziti knihovny viz napriklad popis implementace AES do WinZIP - AES Encryption Information: Encryption Specification AE-1 and AE-2 - http://www.winzip.com/aes_info.htm - - Pripadne text autora knihovny (Brian Gladman): - http://www.gladman.me.uk/cryptography_technology/fileencrypt/ -*/ + * For an example of how to use the library, see the description of the AES implementation in WinZIP + * AES Encryption Information: Encryption Specification AE-1 and AE-2 + * http://www.winzip.com/aes_info.htm + * + * See also the library author's notes (Brian Gladman): + * http://www.gladman.me.uk/cryptography_technology/fileencrypt/ + */ #ifndef _FENC_H #define _FENC_H diff --git a/src/common/dep/sqlite/precomp.h b/src/common/dep/sqlite/precomp.h index bf35e3c94..0593ff1e3 100644 --- a/src/common/dep/sqlite/precomp.h +++ b/src/common/dep/sqlite/precomp.h @@ -1,4 +1,4 @@ -// sqlite precomp.h nepouziva, ale overime, ze je v projektu nastaven define pro exporty dll +// sqlite precomp.h is not used, but verify that the project defines the DLL export macro #ifndef SQLITE_API #pragma message ( __FILE__ "SQLITE_API not defined!" ) #endif diff --git a/src/common/dep/sqlite/readme.txt b/src/common/dep/sqlite/readme.txt index 4a9490c1a..7b81cb052 100644 --- a/src/common/dep/sqlite/readme.txt +++ b/src/common/dep/sqlite/readme.txt @@ -1,11 +1,14 @@ -Zdrojaky SQLite z webu http://www.sqlite.org/download.html -Pouzivame sqlite-amalgamation-*.zip -Koncepcne bychom meli pro nove verze Salamander pouzivat nejnovejsi verze SQLite, -abychom byli schopni cist nejnovejsi binarni verze SQLite databazi. +CommentsTranslationProject: TRANSLATED -Updatnout: +SQLite sources are available at http://www.sqlite.org/download.html +Use sqlite-amalgamation-*.zip. +Conceptually, new Salamander versions should use the newest SQLite versions +so we can read the newest binary versions of SQLite databases. + +Update: salamand\sqlite\sqlite3.c salamand\plugins\shared\sqlite\sqlite3.h -Pridat na to-do list: --otestovat novou verzi SQLite na Google Drive, podivat do TRACE, ze cteme cestu k jeho slozce \ No newline at end of file +Add to the to-do list: +- test the new SQLite version on Google Drive and inspect TRACE to confirm that + we read the path to its folder diff --git a/src/common/dib.cpp b/src/common/dib.cpp index a35bb6760..5974a76cf 100644 --- a/src/common/dib.cpp +++ b/src/common/dib.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -7,7 +8,7 @@ #include #include #include -#include // potrebuju LPCOLORMAP +#include // Needed for LPCOLORMAP. #if defined(_DEBUG) && defined(_MSC_VER) // without passing file+line to 'new' operator, list of memory leaks shows only 'crtdbg.h(552)' #define new new (_NORMAL_BLOCK, __FILE__, __LINE__) @@ -21,8 +22,8 @@ #include "dib.h" -// opatreni proti runtime check failure v debug verzi: puvodni verze makra pretypovava rgb na WORD, -// takze hlasi ztratu dat (RED slozky) +// Workaround for a runtime check failure in the debug build: the original version of the macro casts rgb to WORD, +// so it reports data loss in the RED component. #undef GetGValue #define GetGValue(rgb) ((BYTE)(((rgb) >> 8) & 0xFF)) @@ -82,7 +83,7 @@ HBITMAP LoadBitmapAndMapColors(HINSTANCE hInst, HRSRC hRsrc, int mapCount, TRACE_E("Unable to create bitmap."); HANDLES(ReleaseDC(NULL, hDCScreen)); - // free copy of bitmap info struct and resource itself + // free the copy of the bitmap info struct and the resource itself free(lpBitmapInfo); FreeResource(hglb); @@ -307,13 +308,14 @@ HBITMAP DIBToBitmap(HANDLE hDIB, HPALETTE hPal) return hBitmap; } -//--------------------------------------------------------------------- +// --------------------------------------------------------------------- // // Function: MapColor(RGB fromColor, RGB toColor) // -// vsechny barvy fromColor premapuje na barvu toColor +// Remaps every occurrence of fromColor in the DIB to +// toColor. // -//--------------------------------------------------------------------- +// --------------------------------------------------------------------- int MapColor(HANDLE hDIB, COLORREF fromColor, COLORREF toColor) { diff --git a/src/common/dib.h b/src/common/dib.h index 96d8e4291..0b169a22f 100644 --- a/src/common/dib.h +++ b/src/common/dib.h @@ -1,11 +1,12 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once -// nacte z resourcu bitmapu hRsrc (ziskan z FindResource(...)), -// premapuje mapCount barev: mapColor[i] -> toColor[i] -// a vytvori bitmapu kompatibilni s desktopem +// loads the bitmap resource hRsrc (obtained with FindResource(...)), +// remaps mapCount colors: mapColor[i] -> toColor[i], +// and creates a bitmap compatible with the desktop HBITMAP LoadBitmapAndMapColors(HINSTANCE hInst, HRSRC hRsrc, int mapCount, COLORREF* mapColor, COLORREF* toColor); diff --git a/src/common/handles.cpp b/src/common/handles.cpp index 9d0622479..5cf52a1cc 100644 --- a/src/common/handles.cpp +++ b/src/common/handles.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -7,7 +8,7 @@ #include #include #include -#include // potrebuju LPCOLORMAP +#include // Need LPCOLORMAP. #if defined(_DEBUG) && defined(_MSC_VER) // without passing file+line to 'new' operator, list of memory leaks shows only 'crtdbg.h(552)' #define new new (_NORMAL_BLOCK, __FILE__, __LINE__) @@ -25,15 +26,15 @@ // boundaries so we can find the real functions // that we need to call for initialization. -#pragma warning(disable : 4075) // chceme definovat poradi inicializace modulu +#pragma warning(disable : 4075) // We want to define the module initialization order. typedef void(__cdecl* _PVFV)(void); #pragma section(".i_hnd$a", read) -__declspec(allocate(".i_hnd$a")) const _PVFV i_handles = (_PVFV)1; // na zacatek sekce .i_hnd si dame promennou i_handles +__declspec(allocate(".i_hnd$a")) const _PVFV i_handles = (_PVFV)1; // Put the i_handles variable at the start of the .i_hnd section. #pragma section(".i_hnd$z", read) -__declspec(allocate(".i_hnd$z")) const _PVFV i_handles_end = (_PVFV)1; // a na konec sekce .i_hnd si dame promennou i_handles_end +__declspec(allocate(".i_hnd$z")) const _PVFV i_handles_end = (_PVFV)1; // Put the i_handles_end variable at the end of the .i_hnd section. void Initialize__Handles() { @@ -524,13 +525,13 @@ C__Handles::C__Handles() #ifdef MULTITHREADED_HANDLES_ENABLE ::InitializeCriticalSection(&CriticalSection); #else // MULTITHREADED_HANDLES_ENABLE - __HandlesMainThreadID = ::GetCurrentThreadId(); // jediny povoleny thread + __HandlesMainThreadID = ::GetCurrentThreadId(); // The only allowed thread. #endif // MULTITHREADED_HANDLES_ENABLE } C__Handles::~C__Handles() { - // vyrazeni handlu, ktere se uvolnuji automaticky + // Filter out handles that are released automatically. for (int i = Handles.Count - 1; i >= 0; i--) { if (Handles[i].Handle.Origin == __hoLoadAccelerators) @@ -540,15 +541,10 @@ C__Handles::~C__Handles() else if (Handles[i].Handle.Origin == __hoGetStockObject) Handles.Delete(i); } - // kontrola + vypis zbylych + // Check and list remaining open handles. if (Handles.Count != 0) { - // musel jsem nahradit nize polozeny kod vyuzivajici MESSAGE_E, protoze pri volani - // tohoto destruktoru jsou v ALTAPDB jiz zdestruovane facets streamu a pri poslani intu - // nebo handlu do streamu to proste spadne (dela jen VC2010 a VC2012, ve VC2008 - // to jeste slape); v Salamanderovi to nezlobi, asi kvuli RTL v DLLku (v ALTAPDB je - // static), ci co, po tom jsem uz dal nepatral, lepsi reseni by bylo zaridit - // destrukci facets az po tomto modulu, ale to bohuzel neumim (jen tez na "lib" urovni) + // The code below that uses MESSAGE_E had to be replaced because when this destructor runs, the stream facets in ALTAPDB have already been destroyed, and sending an int or handle to the stream simply crashes (only in VC2010 and VC2012; it still works in VC2008). It does not happen in Salamander, probably because the RTL is in the DLL (ALTAPDB uses a static one), but that was not investigated further. A better solution would be to destroy the facets only after this module, but that cannot be done here (only at the "lib" level). char msgBuf[1000]; sprintf_s(msgBuf, #ifdef MESSAGES_DEBUG @@ -572,11 +568,11 @@ C__Handles::~C__Handles() MB_YESNO | MB_SETFOREGROUND) == IDYES) */ { - ConnectToTraceServer(); // v pripade, ze nebyl nahozeny server + ConnectToTraceServer(); // in case the server has not been started TRACE_I("List of opened handles:"); for (int i = 0; i < Handles.Count; i++) { - // saskarna pres msgBuf kvuli padackam v ALTAPDB, podrobnosti viz komentar vyse + // Workaround using msgBuf because of crashes in ALTAPDB; see the comment above for details. sprintf_s(msgBuf, "%p", Handles[i].Handle.Handle); TRACE_MI(Handles[i].File, Handles[i].Line, __GetHandlesTypeName(Handles[i].Handle.Type) << " - " << __GetHandlesOrigin(Handles[i].Handle.Origin) << " - " << msgBuf); @@ -585,7 +581,7 @@ C__Handles::~C__Handles() else { ConnectToTraceServer(); - // saskarna pres msgBuf kvuli padackam v ALTAPDB, podrobnosti viz komentar vyse + // Workaround using msgBuf because of crashes in ALTAPDB; see the comment above for details. sprintf_s(msgBuf, "%d", Handles.Count); TRACE_I(__HandlesMessageNumberOpened << msgBuf); } @@ -604,7 +600,7 @@ C__Handles::SetInfo(const char* file, int line, C__HandlesOutputType outputType) ::EnterCriticalSection(&CriticalSection); if (CriticalSection.RecursionCount > 1) { - DebugBreak(); // rekurzivni volani handles !!! zase nejaka maskovana message-loopa - viz call-stack + DebugBreak(); // Recursive handles call: another hidden message loop, see the call stack. } #endif // MULTITHREADED_HANDLES_ENABLE OutputType = outputType; @@ -706,7 +702,7 @@ BOOL C__Handles::DeleteHandle(C__HandlesType& type, HANDLE handle, { C__HandlesOrigin org = Handles[i].Handle.Origin; if (org != __hoLoadAccelerators && org != __hoLoadIcon && - org != __hoGetStockObject) // nejde o handle, ktery nemusi byt uvolneny (prioritne uvolnujeme handly, ktere se musi uvolnit) + org != __hoGetStockObject) // This is not a handle exempt from release (we prioritize handles that must be released). { if (origin != NULL) *origin = org; @@ -721,7 +717,7 @@ BOOL C__Handles::DeleteHandle(C__HandlesType& type, HANDLE handle, } } } - if (foundTypeOK != -1) // nalezen jen handle, ktery nemusi byt uvolneny + if (foundTypeOK != -1) // Found only a handle that does not need to be released. { type = Handles[foundTypeOK].Handle.Type; if (origin != NULL) @@ -729,7 +725,7 @@ BOOL C__Handles::DeleteHandle(C__HandlesType& type, HANDLE handle, Handles.Delete(foundTypeOK); return TRUE; } - if (found != -1) // nalezen jen handle se shodnym cislem + if (found != -1) // Found only a handle with the same numeric value. { #if defined(_DEBUG) || defined(__HANDLES_DEBUG) C__HandlesData* data = &(Handles[found]); @@ -921,7 +917,7 @@ C__Handles::CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, dwFlagsAndAttributes, hTemplateFile); char paramsBuf[MAX_PATH + 200]; const char* params = NULL; - if (ret == INVALID_HANDLE_VALUE) // parameters to buffer only when error occurs (can be displayed) + if (ret == INVALID_HANDLE_VALUE) // Buffer the parameters only when an error occurs (so they can be displayed) { DWORD err = GetLastError(); _snprintf_s(paramsBuf, _TRUNCATE, @@ -944,13 +940,13 @@ C__Handles::CreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, HANDLE ret = ::CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); - WCHAR paramsBuf[800 + 200]; // na jmena souboru omezime na 800 znaku, stejne delsi nevytiskneme diky omezeni MESSAGES + WCHAR paramsBuf[800 + 200]; // Limit file names to 800 characters; anything longer would not be printed anyway because of the MESSAGES limit. const WCHAR* params = NULL; - if (ret == INVALID_HANDLE_VALUE) // parameters to buffer only when error occurs (can be displayed) + if (ret == INVALID_HANDLE_VALUE) // Store the parameters in the buffer only when an error occurs (so they can be displayed) { DWORD err = GetLastError(); _snwprintf_s(paramsBuf, _TRUNCATE, - L"dwDesiredAccess=0x%X,\ndwShareMode=0x%X,\ndwCreationDisposition=0x%X,\ndwFlagsAndAttributes=0x%X,\nlpFileName=%s", // lpFileName mame schvalne az na konci, muze byt az 32k dlouhe, orizne se + L"dwDesiredAccess=0x%X,\ndwShareMode=0x%X,\ndwCreationDisposition=0x%X,\ndwFlagsAndAttributes=0x%X,\nlpFileName=%s", // lpFileName is intentionally last; it can be up to 32K long and will be truncated. dwDesiredAccess, dwShareMode, dwCreationDisposition, dwFlagsAndAttributes, lpFileName); params = paramsBuf; SetLastError(err); @@ -1039,7 +1035,7 @@ HDC C__Handles::BeginPaint(HWND hwnd, LPPAINTSTRUCT lpPaint) ::LeaveCriticalSection(&CriticalSection); #endif // MULTITHREADED_HANDLES_ENABLE - HDC ret = ::BeginPaint(hwnd, lpPaint); // obsahuje message-loopu + HDC ret = ::BeginPaint(hwnd, lpPaint); // Contains a message loop. #ifdef MULTITHREADED_HANDLES_ENABLE ::EnterCriticalSection(&CriticalSection); @@ -1890,8 +1886,8 @@ BOOL C__Handles::DuplicateHandle(HANDLE hSourceProcessHandle, HANDLE hSourceHand "current process."); } - // GetCurrentProcess vraci jakysi pseudohandle, takze tahle konstrukce - // neni spravna, meli by se porovnat ID procesu a ne jejich handly ... + // GetCurrentProcess returns a pseudo-handle, so this is not correct; + // process IDs should be compared instead of process handles ... if ((dwOptions & DUPLICATE_CLOSE_SOURCE) && hSourceProcessHandle == GetCurrentProcess()) @@ -2113,7 +2109,7 @@ BOOL C__Handles::FreeLibrary(HMODULE hLibModule) ::LeaveCriticalSection(&CriticalSection); #endif // MULTITHREADED_HANDLES_ENABLE - BOOL ret = ::FreeLibrary(hLibModule); // obsahuje volani destruktoru globalek DLLka, muze obsahovat message-loopu + BOOL ret = ::FreeLibrary(hLibModule); // Calls DLL global destructors; may contain a message loop. #ifdef MULTITHREADED_HANDLES_ENABLE ::EnterCriticalSection(&CriticalSection); @@ -2133,7 +2129,7 @@ VOID C__Handles::FreeLibraryAndExitThread(HMODULE hLibModule, DWORD dwExitCode) ::LeaveCriticalSection(&CriticalSection); #endif // MULTITHREADED_HANDLES_ENABLE - ::FreeLibraryAndExitThread(hLibModule, dwExitCode); // obsahuje volani destruktoru globalek DLLka, muze obsahovat message-loopu + ::FreeLibraryAndExitThread(hLibModule, dwExitCode); // Calls DLL global destructors; may contain a message loop. #ifdef MULTITHREADED_HANDLES_ENABLE ::EnterCriticalSection(&CriticalSection); @@ -2219,7 +2215,7 @@ BOOL C__Handles::FindCloseChangeNotification(HANDLE hChangeHandle) ::LeaveCriticalSection(&CriticalSection); #endif // MULTITHREADED_HANDLES_ENABLE - BOOL ret = ::FindCloseChangeNotification(hChangeHandle); // muze se kousnout i na dost dlouho + BOOL ret = ::FindCloseChangeNotification(hChangeHandle); // Can hang for quite a long time. #ifdef MULTITHREADED_HANDLES_ENABLE ::EnterCriticalSection(&CriticalSection); @@ -2346,7 +2342,7 @@ HFILE C__Handles::OpenFile(LPCSTR lpFileName, LPOFSTRUCT lpReOpenBuff, UINT uStyle) { HFILE ret = ::OpenFile(lpFileName, lpReOpenBuff, uStyle); - CheckCreate(ret != HFILE_ERROR, __htFile, __hoOpenFile, (HANDLE)(UINT_PTR)ret, GetLastError(), TRUE); // lpFileName je jen char i v Unicode verzi = nepouzitelna funkce (zastarala), vyradil jsem ji z vypisu parametru + CheckCreate(ret != HFILE_ERROR, __htFile, __hoOpenFile, (HANDLE)(UINT_PTR)ret, GetLastError(), TRUE); // lpFileName is char-only even in the Unicode version, so this function is unusable (obsolete) and is omitted from the parameter dump. return ret; } @@ -2378,7 +2374,7 @@ HDWP C__Handles::DeferWindowPos(HDWP hWinPosInfo, HWND hWnd, HWND hWndInsertAfte { HDWP ret = ::DeferWindowPos(hWinPosInfo, hWnd, hWndInsertAfter, x, y, cx, cy, uFlags); - if (ret != hWinPosInfo) // doslo k realokaci struktury - musime zmenit hodnotu hlidaneho handlu + if (ret != hWinPosInfo) // The structure was reallocated, so we must update the tracked handle value. { CheckClose(TRUE, (HANDLE)hWinPosInfo, __htDeferWindowPos, __GetHandlesOrigin(__hoDeferWindowPos), ERROR_SUCCESS, FALSE); CheckCreate(ret != NULL, __htDeferWindowPos, __hoDeferWindowPos, (HANDLE)ret, GetLastError()); @@ -2400,7 +2396,7 @@ BOOL C__Handles::EndDeferWindowPos(HDWP hWinPosInfo) ::LeaveCriticalSection(&CriticalSection); #endif // MULTITHREADED_HANDLES_ENABLE - BOOL ret = ::EndDeferWindowPos(hWinPosInfo); // obsahuje message-loopu + BOOL ret = ::EndDeferWindowPos(hWinPosInfo); // Contains a message loop. #ifdef MULTITHREADED_HANDLES_ENABLE ::EnterCriticalSection(&CriticalSection); diff --git a/src/common/handles.h b/src/common/handles.h index d241292a1..e54f8ab20 100644 --- a/src/common/handles.h +++ b/src/common/handles.h @@ -1,17 +1,18 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once -// makro HANDLES_ENABLE - zapina monitorovani handlu -// makro _DEBUG nebo __HANDLES_DEBUG - vypis debug hlasek do TRACE -// makro MULTITHREADED_HANDLES_ENABLE - pripravi handles pro multithreadove aplikace +// HANDLES_ENABLE macro - enables handle monitoring +// _DEBUG or __HANDLES_DEBUG macro - outputs debug messages to TRACE +// MULTITHREADED_HANDLES_ENABLE macro - prepares handles for multithreaded applications #define NOHANDLES(function) function #ifndef HANDLES_ENABLE -// aby nedochazelo k problemum se stredniky v nize nadefinovanych makrech +// to avoid problems with semicolons in the macros defined below inline void __HandlesEmptyFunction() {} #define HANDLES(function) ::function @@ -26,7 +27,7 @@ inline void __HandlesEmptyFunction() {} #ifndef MULTITHREADED_HANDLES_ENABLE -// pro kontrolu pouziti nemulti-threadove verze modulu +// for checking use of the non-multithreaded module version extern DWORD __HandlesMainThreadID; #endif // MULTITHREADED_HANDLES_ENABLE @@ -47,8 +48,8 @@ enum C__HandlesOutputType enum C__HandlesType { - __htHandle_comp_with_CloseHandle, // handle kompatibilni s CloseHandle() a DuplicateHandle() - __htHandle_comp_with_DeleteObject, // handle kompatibilni s DeleteObject() a GetStockObject() + __htHandle_comp_with_CloseHandle, // handle compatible with CloseHandle() and DuplicateHandle() + __htHandle_comp_with_DeleteObject, // handle compatible with DeleteObject() and GetStockObject() __htKey, __htIcon, __htGlobal, @@ -213,7 +214,7 @@ struct C__HandlesHandle { C__HandlesType Type; C__HandlesOrigin Origin; - HANDLE Handle; // univerzalni, pro vsechny druhy handlu + HANDLE Handle; // generic, for all handle types C__HandlesHandle() {} @@ -257,11 +258,11 @@ class C_HandlesDataArray class C__Handles { protected: - C_HandlesDataArray Handles; // vsechny kontrolovane handly - C__HandlesData TemporaryHandle; // pri vkladani nastaven z SetInfo() - C__HandlesOutputType OutputType; // typ vystupu hlasek + C_HandlesDataArray Handles; // all monitored handles + C__HandlesData TemporaryHandle; // set from SetInfo() during insertion + C__HandlesOutputType OutputType; // message output type #ifdef MULTITHREADED_HANDLES_ENABLE - CRITICAL_SECTION CriticalSection; // pro synchronizaci multi-threadu + CRITICAL_SECTION CriticalSection; // for multithreaded synchronization #endif // MULTITHREADED_HANDLES_ENABLE public: @@ -655,9 +656,9 @@ class C__Handles BOOL OpenProcessToken(HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle); protected: - void AddHandle(C__HandlesHandle handle); // prida TemporaryHandle + void AddHandle(C__HandlesHandle handle); // adds TemporaryHandle - // vyjme handle, pri uspechu vraci TRUE + // removes the handle; returns TRUE on success BOOL DeleteHandle(C__HandlesType& type, HANDLE handle, C__HandlesOrigin* origin, C__HandlesType expType); diff --git a/src/common/heap.cpp b/src/common/heap.cpp index 6b16681a7..64e57f7e2 100644 --- a/src/common/heap.cpp +++ b/src/common/heap.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -28,15 +29,15 @@ // boundaries so we can find the real functions // that we need to call for initialization. -#pragma warning(disable : 4075) // chceme definovat poradi inicializace modulu +#pragma warning(disable : 4075) // Define the module initialization order typedef void(__cdecl* _PVFV)(void); #pragma section(".i_hea$a", read) -__declspec(allocate(".i_hea$a")) const _PVFV i_heap = (_PVFV)1; // na zacatek sekce .i_hea si dame promennou i_heap +__declspec(allocate(".i_hea$a")) const _PVFV i_heap = (_PVFV)1; // Place i_heap at the start of the .i_hea section #pragma section(".i_hea$z", read) -__declspec(allocate(".i_hea$z")) const _PVFV i_heap_end = (_PVFV)1; // a na konec sekce .i_hea si dame promennou i_heap_end +__declspec(allocate(".i_hea$z")) const _PVFV i_heap_end = (_PVFV)1; // Place i_heap_end at the end of the .i_hea section void Initialize__Heap() { @@ -69,8 +70,7 @@ int OurReportingFunction(int reportType, char* userMessage, int* retVal) // retVal to one. *retVal = 0; - // we'll report some information, but we also - // want _CrtDbgReport to get called - so we'll return FALSE + // Return FALSE after reporting some information so _CrtDbgReport still gets called return FALSE; } @@ -79,7 +79,7 @@ class C__GCHeapInit public: C__GCHeapInit() { - // uloz stav pameti na zacatku + // Save the initial memory state _CrtMemCheckpoint(&start_state); prev_reporting_hook = _CrtSetReportHook(OurReportingFunction); InitializeCriticalSection(&CriticalSection); @@ -87,32 +87,32 @@ class C__GCHeapInit } ~C__GCHeapInit() { - // zjisti aktualni stav pameti + // Capture the current memory state _CrtMemState end_state; _CrtMemCheckpoint(&end_state); - // zkontroluj, jestli jsou nejake leaky + // Check for memory leaks _CrtMemState diff; if (_CrtMemDifference(&diff, &start_state, &end_state)) { HMODULE hUsedModules[GCHEAP_MAX_USED_MODULES]; - // namapuju do pameti vsechny moduly, ve kterych se muzou hlasit memory leaky, - // tim se v reportu zobrazi jmena .cpp souboru (jinak by tam bylo jen "#File Error#") + // Map into memory all modules that may report memory leaks, + // so the report shows the .cpp file names (otherwise it would show only "#File Error#") for (int i = 0; i < UsedModulesCount; i++) hUsedModules[i] = LoadLibraryEx(UsedModules[i], NULL, DONT_RESOLVE_DLL_REFERENCES); - // vypise vsechny neuvolnene bloky + // Dump all unfreed blocks _CrtMemDumpAllObjectsSince(&start_state); - // kdyz uz mame diff, tak ho taky vypisem + // Dump the diff too, since we already have it _CrtMemDumpStatistics(&diff); - // zase uvolnime namapovane moduly + // Release the mapped modules again for (int i = 0; i < UsedModulesCount; i++) FreeLibrary(hUsedModules[i]); - // vyhod warning messagebox - MSG msg; // remove possibly buffered ESC key (not to close msgbox immediately) + // Show the warning message box + MSG msg; // Clear any buffered ESC key so the message box does not close immediately while (PeekMessage(&msg, NULL, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE)) ; MessageBoxA(NULL, "Detected memory leaks!", "Heap Message", diff --git a/src/common/heap.h b/src/common/heap.h index 407eb0dd4..3a49e1171 100644 --- a/src/common/heap.h +++ b/src/common/heap.h @@ -1,20 +1,16 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once -// Pridat do DEBUG verze projektu makro _CRTDBG_MAP_ALLOC, jinak se neukazuje zdroj leaku. +// Define _CRTDBG_MAP_ALLOC in the DEBUG build; otherwise the leak source is not shown. #if defined(_DEBUG) && !defined(HEAP_DISABLE) -#define GCHEAP_MAX_USED_MODULES 100 // kolik nejvic modulu se ma pamatovat pro load pred vypisem leaku +#define GCHEAP_MAX_USED_MODULES 100 // maximum number of modules to remember so they can be loaded before reporting memory leaks -// vola se pro moduly, ve kterych se muzou hlasit memory leaky, pokud se memory leaky detekuji, -// dojde k loadu "as image" (bez initu modulu) vsech takto registrovanych modulu (pri kontrole -// memory leaku uz jsou tyto moduly unloadle), a pak teprve k vypisu memory leaku = jsou videt -// jmena .cpp modulu misto "#File Error#" hlasek, zaroven MSVC neotravuje s hromadou generovanych -// exceptionu (jmena modulu jsou dostupna) -// mozne volat z libovolneho threadu +// Call this for modules that may report memory leaks. If leaks are detected, all modules registered this way are loaded "as image" (without module initialization; the modules are already unloaded when leaks are checked) before the leak report is printed. This shows .cpp module names instead of "#File Error#" messages, and MSVC does not flood the output with generated exceptions because the module names are available. Can be called from any thread. void AddModuleWithPossibleMemoryLeaks(const TCHAR* fileName); #endif // defined(_DEBUG) && !defined(HEAP_DISABLE) diff --git a/src/common/lstrfix.h b/src/common/lstrfix.h index 43b8096b8..eca077f36 100644 --- a/src/common/lstrfix.h +++ b/src/common/lstrfix.h @@ -1,13 +1,14 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once -// nasledujici funkce nepadaji pri praci s neplatnou pameti (ani pri praci s NULL): -// lstrcpy, lstrcpyn, lstrlen a lstrcat (ty jsou definovane s priponou A nebo W, proto -// je primo neredefinujeme), v zajmu snazsiho odladeni chyb potrebujeme, aby padaly, -// protoze jinak se na chybu prijde pozdeji v miste, kde uz nemusi byt jasne, co ji -// zpusobilo +// The following functions do not crash when passed invalid pointers (including NULL): +// lstrcpy, lstrcpyn, lstrlen, and lstrcat (these are defined with the A or W suffix, so +// we do not redefine them directly). For easier debugging, we need them to crash, +// because otherwise the error is only discovered later, when it may no longer be clear +// what caused it #define lstrcpyA _sal_lstrcpyA #define lstrcpyW _sal_lstrcpyW #define lstrcpynA _sal_lstrcpynA diff --git a/src/common/lstrfix.inc b/src/common/lstrfix.inc index 871e21da4..5c7521cbc 100644 --- a/src/common/lstrfix.inc +++ b/src/common/lstrfix.inc @@ -3,8 +3,8 @@ #include "lstrfix.h" -// potlaceni warningu C4996: This function or variable may be unsafe. Consider using strcat_s instead. -// duvod: lstrcat a dalsi Windows rutiny prost nejsou safe, takze to nema smysl resit tady +// Suppress warning C4996: This function or variable may be unsafe. Consider using strcat_s instead. +// Reason: lstrcat and other Windows routines simply are not safe, so it makes no sense to address it here. #pragma warning(push) #pragma warning(disable:4996) @@ -75,8 +75,8 @@ LPWSTR _sal_lstrcatW(LPWSTR lpString1, LPCWSTR lpString2) // allows us to define these names. #pragma function(strlen, wcslen, strcpy, wcscpy, strcat, wcscat) -// musel jsem si od MS pujcit implementace strlen, wcslen, strcpy, wcscpy, strcat a wcscat -// protoze se zde ignoruji default-liby, kde jsou tyto funkce umistene +// Borrowed the MS implementations of strlen, wcslen, strcpy, wcscpy, strcat, and wcscat +// because the default libraries that contain these functions are ignored here. size_t __cdecl strlen ( const char * str ) diff --git a/src/common/messages.cpp b/src/common/messages.cpp index 98f2912bb..7dc745788 100644 --- a/src/common/messages.cpp +++ b/src/common/messages.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -20,15 +21,15 @@ // boundaries so we can find the real functions // that we need to call for initialization. -#pragma warning(disable : 4075) // chceme definovat poradi inicializace modulu +#pragma warning(disable : 4075) // we want to define the module initialization order typedef void(__cdecl* _PVFV)(void); #pragma section(".i_msg$a", read) -__declspec(allocate(".i_msg$a")) const _PVFV i_messages = (_PVFV)1; // na zacatek sekce .i_msg si dame promennou i_messages +__declspec(allocate(".i_msg$a")) const _PVFV i_messages = (_PVFV)1; // put i_messages at the start of the .i_msg section #pragma section(".i_msg$z", read) -__declspec(allocate(".i_msg$z")) const _PVFV i_messages_end = (_PVFV)1; // a na konec sekce .i_msg si dame promennou i_messages_end +__declspec(allocate(".i_msg$z")) const _PVFV i_messages_end = (_PVFV)1; // put i_messages_end at the end of the .i_msg section void Initialize__Messages() { @@ -77,16 +78,16 @@ WCHAR __MessagesTitleBufW[200]; #ifdef MULTITHREADED_MESSAGES_ENABLE -// kriticka sekce pro cely modul - monitor +// module-wide critical section - monitor CRITICAL_SECTION __MessagesCriticalSection; -// handle aktualniho vlastniciho threadu +// ID of the current owning thread DWORD __MessagesOwnerThreadID = 0; -// pocet vnorenych volani EnterMessagesModul (v ramci aktualniho vlastniciho threadu) +// number of nested EnterMessagesModul calls within the current owning thread int __MessagesModulBlockCount = 0; #ifdef MESSAGES_DEBUG -// volani z threadu, ktery nema pristup k datum a funkcim modulu (nezalokoval) +// call from a thread that has no access to the module data and functions (did not allocate them) const char* __MessagesBadCall = "Incorrect call to function from modul MESSAGES."; #endif // MESSAGES_DEBUG @@ -139,20 +140,10 @@ void LeaveMessagesModul() C__Messages::C__Messages() : MessagesStrStream(&MessagesStringBuf) { #ifdef _DEBUG - // nove streamy pouzivaji interne locales, ktere maji implementovany - // jednotlive "facets" pomoci lazy creation - jsou alokovany na heapu - // kdyz jsou potreba, tedy kdyz nekdo posle do streamu neco, co ma - // formatovani zavisle na lokalich pravidlech, treba cislo, datum, - // nebo boolean. Tyto "facets" jsou pak dealokovany pri exitu - // programu s prioritou compiler, tzn. po nasi kontrole memory leaku. - // Takze pokud nekdo pouzije stream k vypisu cehokoli lokalizovatelneho, - // nas debug heap zacne hlasit memory leaky, i kdyz zadne nejsou. Abychom - // tomu predesli, donutime locales vytvorit vsechny "facets" ted, dokud - // jeste nehlidame heap. - // Zatim pouzivame pouze vystupni stream a pouze se stringy (bez konverze) - // a cisly. Takze poslat cislo do stringstreamu by melo stacit. Pokud - // v budoucnu zacneme pouzivat streamy vic a debug heap zacne hlasit - // leaky, budeme zde muset pridat vic vstupu/vystupu. + // New streams use internal locales whose individual "facets" are created lazily and allocated on the heap only when needed, for example when something with locale-dependent formatting such as a number, date, or boolean is sent to the stream. + // These "facets" are then deallocated at program exit with compiler priority, i.e. after our memory leak check. + // So if someone uses a stream to output anything locale-dependent, the debug heap starts reporting memory leaks even though there are none. To prevent that, force the locales to create all "facets" now, while we are not tracking the heap yet. + // For now we use only output streams, and only with strings (without conversion) and numbers. So sending a number to the stringstream should be enough. If we start using streams more in the future and the debug heap starts reporting leaks again, we will have to add more input/output here. std::stringstream s; s << 1; #endif // _DEBUG @@ -175,8 +166,8 @@ struct C__MessageBoxData }; int CALLBACK __MessagesMessageBoxThreadF(C__MessageBoxData* data) -{ // nesmi cekat na odezvu volajiciho threadu, protoze ten nebude reagovat - // proto je parent==NULL -> zadne disablovani oken atd. +{ // must not wait for a response from the calling thread, because it will not respond + // therefore parent == NULL -> no disabling of windows, etc. data->Return = MessageBoxA(NULL, data->Text, data->Caption, data->Type | MB_SETFOREGROUND); return 0; } @@ -188,31 +179,31 @@ int C__Messages::MessageBoxT(const char* lpCaption, UINT uType) data.Type = uType; data.Return = 0; - MessagesStrStream.flush(); // flushnuti do bufferu (v lpText) + MessagesStrStream.flush(); // flush into the buffer (lpText) #ifndef MULTITHREADED_MESSAGES_ENABLE data.Text = MessagesStringBuf.c_str(); - MessagesStringBuf.erase(); // priprava pro dalsi message + MessagesStringBuf.erase(); // prepare for the next message #else // MULTITHREADED_MESSAGES_ENABLE int len = (int)MessagesStringBuf.length() + 1; - HGLOBAL message = GlobalAlloc(GMEM_FIXED, len); // zaloha textu + HGLOBAL message = GlobalAlloc(GMEM_FIXED, len); // backup copy of the text if (message != NULL) { - memcpy((char*)message, MessagesStringBuf.c_str(), len); // je to FIXED -> HANDLE==PTR + memcpy((char*)message, MessagesStringBuf.c_str(), len); // it is FIXED, so HANDLE == PTR data.Text = (char*)message; } else data.Text = __MessagesLowMemory; - MessagesStringBuf.erase(); // priprava pro dalsi message - LeaveMessagesModul(); // ted uz muzou zacit blbnout ostatni thready + message loopy + MessagesStringBuf.erase(); // prepare for the next message + LeaveMessagesModul(); // other threads and message loops may resume now #endif // MULTITHREADED_MESSAGES_ENABLE - // MessageBox nahodime v novem threadu, aby nerozeslal message tohoto threadu + // run the MessageBox in a new thread so it does not dispatch this thread's messages DWORD threadID; HANDLE thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)__MessagesMessageBoxThreadF, &data, 0, &threadID); if (thread != NULL) { - WaitForSingleObject(thread, INFINITE); // pockame az ho user odmackne + WaitForSingleObject(thread, INFINITE); // wait until the user dismisses it CloseHandle(thread); } else @@ -229,24 +220,24 @@ int C__Messages::MessageBoxT(const char* lpCaption, UINT uType) int C__Messages::MessageBox(HWND hWnd, const char* lpCaption, UINT uType) { int ret; - MessagesStrStream.flush(); // flushnuti do bufferu (v lpText) + MessagesStrStream.flush(); // flush into the buffer (lpText) #ifndef MULTITHREADED_MESSAGES_ENABLE if (!IsWindow(hWnd)) hWnd = NULL; ret = ::MessageBoxA(hWnd, MessagesStringBuf.c_str(), lpCaption, uType); - MessagesStringBuf.erase(); // priprava pro dalsi message + MessagesStringBuf.erase(); // prepare for the next message #else // MULTITHREADED_MESSAGES_ENABLE size_t len = MessagesStringBuf.length() + 1; - HGLOBAL message = GlobalAlloc(GMEM_FIXED, len); // zaloha textu + HGLOBAL message = GlobalAlloc(GMEM_FIXED, len); // backup copy of the text char* txt; - txt = (char*)message; // je to FIXED -> HANDLE==PTR + txt = (char*)message; // it is FIXED, so HANDLE == PTR if (txt != NULL) memcpy(txt, MessagesStringBuf.c_str(), len); else txt = (char*)__MessagesLowMemory; - MessagesStringBuf.erase(); // priprava pro dalsi message - LeaveMessagesModul(); // ted uz muzou zacit blbnout ostatni thready + message loopy + MessagesStringBuf.erase(); // prepare for the next message + LeaveMessagesModul(); // other threads and message loops may resume now if (!IsWindow(hWnd)) hWnd = NULL; @@ -267,23 +258,13 @@ int C__Messages::MessageBox(HWND hWnd, const char* lpCaption, UINT uType) C__MessagesW::C__MessagesW() : MessagesStrStream(&MessagesStringBuf) { #ifdef _DEBUG - // nove streamy pouzivaji interne locales, ktere maji implementovany - // jednotlive "facets" pomoci lazy creation - jsou alokovany na heapu - // kdyz jsou potreba, tedy kdyz nekdo posle do streamu neco, co ma - // formatovani zavisle na lokalich pravidlech, treba cislo, datum, - // nebo boolean. Tyto "facets" jsou pak dealokovany pri exitu - // programu s prioritou compiler, tzn. po nasi kontrole memory leaku. - // Takze pokud nekdo pouzije stream k vypisu cehokoli lokalizovatelneho, - // nas debug heap zacne hlasit memory leaky, i kdyz zadne nejsou. Abychom - // tomu predesli, donutime locales vytvorit vsechny "facets" ted, dokud - // jeste nehlidame heap. - // Zatim pouzivame pouze vystupni stream a pouze se stringy (bez konverze) - // a cisly. Takze poslat cislo do stringstreamu by melo stacit. Pokud - // v budoucnu zacneme pouzivat streamy vic a debug heap zacne hlasit - // leaky, budeme zde muset pridat vic vstupu/vystupu. + // New streams use internal locales whose individual "facets" are created lazily and allocated on the heap only when needed, for example when something with locale-dependent formatting such as a number, date, or boolean is sent to the stream. + // These "facets" are then deallocated at program exit with compiler priority, i.e. after our memory leak check. + // So if someone uses a stream to output anything locale-dependent, the debug heap starts reporting memory leaks even though there are none. To prevent that, force the locales to create all "facets" now, while we are not tracking the heap yet. + // For now we use only output streams, and only with strings (without conversion) and numbers. So sending a number to the stringstream should be enough. If we start using streams more in the future and the debug heap starts reporting leaks again, we will have to add more input/output here. std::wstringstream s; s << 1; -#endif // _DEBUG +#endif // MULTITHREADED_MESSAGES_ENABLE } struct C__MessageBoxDataW @@ -295,8 +276,8 @@ struct C__MessageBoxDataW }; int CALLBACK __MessagesWMessageBoxThreadF(C__MessageBoxDataW* data) -{ // nesmi cekat na odezvu volajiciho threadu, protoze ten nebude reagovat - // proto je parent==NULL -> zadne disablovani oken atd. +{ // must not wait for the calling thread to respond, because it will not respond + // therefore parent == NULL -> no window disabling, etc. data->Return = MessageBoxW(NULL, data->Text, data->Caption, data->Type | MB_SETFOREGROUND); return 0; } @@ -308,31 +289,31 @@ int C__MessagesW::MessageBoxT(const WCHAR* lpCaption, UINT uType) data.Type = uType; data.Return = 0; - MessagesStrStream.flush(); // flushnuti do bufferu (v lpText) + MessagesStrStream.flush(); // flush into the buffer (lpText) #ifndef MULTITHREADED_MESSAGES_ENABLE data.Text = MessagesStringBuf.c_str(); - MessagesStringBuf.erase(); // priprava pro dalsi message + MessagesStringBuf.erase(); // prepare for the next message #else // MULTITHREADED_MESSAGES_ENABLE int len = (int)MessagesStringBuf.length() + 1; - HGLOBAL message = GlobalAlloc(GMEM_FIXED, sizeof(WCHAR) * len); // zaloha textu + HGLOBAL message = GlobalAlloc(GMEM_FIXED, sizeof(WCHAR) * len); // backup copy of the text if (message != NULL) { - memcpy((WCHAR*)message, MessagesStringBuf.c_str(), sizeof(WCHAR) * len); // je to FIXED -> HANDLE==PTR + memcpy((WCHAR*)message, MessagesStringBuf.c_str(), sizeof(WCHAR) * len); // it is FIXED, so HANDLE == PTR data.Text = (WCHAR*)message; } else data.Text = __MessagesLowMemoryW; - MessagesStringBuf.erase(); // priprava pro dalsi message - LeaveMessagesModul(); // ted uz muzou zacit blbnout ostatni thready + message loopy + MessagesStringBuf.erase(); // prepare for the next message + LeaveMessagesModul(); // other threads and message loops may resume now #endif // MULTITHREADED_MESSAGES_ENABLE - // MessageBox nahodime v novem threadu, aby nerozeslal message tohoto threadu + // run the MessageBox in a new thread so it does not dispatch this thread's messages DWORD threadID; HANDLE thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)__MessagesWMessageBoxThreadF, &data, 0, &threadID); if (thread != NULL) { - WaitForSingleObject(thread, INFINITE); // pockame az ho user odmackne + WaitForSingleObject(thread, INFINITE); // wait until the user dismisses it CloseHandle(thread); } else @@ -349,24 +330,24 @@ int C__MessagesW::MessageBoxT(const WCHAR* lpCaption, UINT uType) int C__MessagesW::MessageBox(HWND hWnd, const WCHAR* lpCaption, UINT uType) { int ret; - MessagesStrStream.flush(); // flushnuti do bufferu (v lpText) + MessagesStrStream.flush(); // flush into the buffer (lpText) #ifndef MULTITHREADED_MESSAGES_ENABLE if (!IsWindow(hWnd)) hWnd = NULL; ret = ::MessageBoxW(hWnd, MessagesStringBuf.c_str(), lpCaption, uType); - MessagesStringBuf.erase(); // priprava pro dalsi message + MessagesStringBuf.erase(); // prepare for the next message #else // MULTITHREADED_MESSAGES_ENABLE size_t len = MessagesStringBuf.length() + 1; - HGLOBAL message = GlobalAlloc(GMEM_FIXED, sizeof(WCHAR) * len); // zaloha textu + HGLOBAL message = GlobalAlloc(GMEM_FIXED, sizeof(WCHAR) * len); // backup copy of the text WCHAR* txt; - txt = (WCHAR*)message; // je to FIXED -> HANDLE==PTR + txt = (WCHAR*)message; // it is FIXED, so HANDLE == PTR if (txt != NULL) memcpy(txt, MessagesStringBuf.c_str(), sizeof(WCHAR) * len); else txt = (WCHAR*)__MessagesLowMemoryW; - MessagesStringBuf.erase(); // priprava pro dalsi message - LeaveMessagesModul(); // ted uz muzou zacit blbnout ostatni thready + message loopy + MessagesStringBuf.erase(); // prepare for the next message + LeaveMessagesModul(); // other threads and message loops may resume now if (!IsWindow(hWnd)) hWnd = NULL; diff --git a/src/common/messages.h b/src/common/messages.h index 3a6156250..b8d7d8ec2 100644 --- a/src/common/messages.h +++ b/src/common/messages.h @@ -1,11 +1,12 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once -// makro MESSAGES_DISABLE - odpojeni modulu z kompilace -// makro MESSAGES_DEBUG - vypis souboru + cisla radku pred message + povoleni zprav ukazovanych pres DMESSAGE_??? -// makro MULTITHREADED_MESSAGES_ENABLE - pripravi messages pro multithreadove aplikace +// Macro MESSAGES_DISABLE - excludes the module from compilation +// Macro MESSAGES_DEBUG - prints the file and line number before the message and enables messages shown via DMESSAGE_??? +// Macro MULTITHREADED_MESSAGES_ENABLE - prepares messages for multithreaded applications #ifndef MESSAGES_DISABLE @@ -15,47 +16,47 @@ #ifdef MULTITHREADED_MESSAGES_ENABLE -// zajisti aktualnimu threadu pristup k funkcim a datum modulu +// Ensures the current thread has access to the module's functions and data void EnterMessagesModul(); -// volat az aktualni thread nebude potrebovat pristup k funkcim a datum modulu +// Call when the current thread no longer needs access to the module's functions and data void LeaveMessagesModul(); #endif // MULTITHREADED_MESSAGES_ENABLE -/// vraci ukazatel na globalni buffer, ktery naplni retezcem z resourcu +//Returns a pointer to a global buffer filled with the resource string const char* rsc(int resID); const WCHAR* rscW(int resID); -/// vraci ukazatel na globalni buffer, ktery naplni retezcem z sprintf +//Returns a pointer to a global buffer filled with the sprintf output const char* spf(const char* formatString, ...); const WCHAR* spfW(const WCHAR* formatString, ...); -/// vraci ukazatel na globalni buffer, ktery naplni retezcem z sprintf +//Returns a pointer to a global buffer filled with the sprintf output const char* spf(int formatStringResID, ...); const WCHAR* spfW(int formatStringResID, ...); -/// vraci ukazatel na globalni buffer, ktery naplni popisem chyby +//Returns a pointer to a global buffer filled with the error description const char* err(DWORD error); const WCHAR* errW(DWORD error); extern const char* __MessagesTitle; extern const WCHAR* __MessagesTitleW; extern HWND __MessagesParent; -extern HINSTANCE HInstance; // predpokladana promenna s handlem instance +extern HINSTANCE HInstance; // Expected variable holding the instance handle -/// Nastaveni titulu messageboxu generovanych makry MESSAGExx. Dela se kopie stringu. -/// Nastavuje vzdy titulek pro obe verze (ANSI + unicode). +//Sets the title of message boxes generated by the MESSAGExx macros. The string is copied. +//Always sets the title for both versions (ANSI + Unicode) void SetMessagesTitle(const char* title); void SetMessagesTitleW(const WCHAR* title); -/// Nastaveni parenta messageboxu generovanych makry MESSAGExx +//Sets the parent window of message boxes generated by the MESSAGExx macros void SetMessagesParent(HWND parent); class C__Messages { protected: - C__StringStreamBuf MessagesStringBuf; // string buffer drzici data messages streamu - C__TraceStream MessagesStrStream; // vlastni messages stream + C__StringStreamBuf MessagesStringBuf; // String buffer holding the messages stream data + C__TraceStream MessagesStrStream; // The messages stream itself public: C__Messages(); @@ -79,8 +80,8 @@ class C__Messages class C__MessagesW { protected: - C__StringStreamBufW MessagesStringBuf; // string buffer drzici data messages streamu - C__TraceStreamW MessagesStrStream; // vlastni messages stream + C__StringStreamBufW MessagesStringBuf; // String buffer holding the messages stream data + C__TraceStreamW MessagesStrStream; // The messages stream itself public: C__MessagesW(); @@ -98,18 +99,20 @@ class C__MessagesW extern C__Messages __Messages; extern C__MessagesW __MessagesW; -/**@name Makra generujici messageboxy. - * je-li nadefinovano makro MESSAGES_DEBUG, zobrazuje se v messageboxich - * na prvnim radku soubor a radek, na kterem je v kodu MESSAGExx\\ - * +/* + * @name Macros that generate message boxes. + * If MESSAGES_DEBUG is defined, the first line of each message box shows + * the file and line where MESSAGExx\ appears in the code */ #ifdef MESSAGES_DEBUG #ifndef MULTITHREADED_MESSAGES_ENABLE -/** zobrazi messagebox se zadanym textem, neni v novem threadu, distribuje message - volajiciho threadu */ +/* + * Displays a message box with the specified text in the current thread; + * dispatches the calling thread's messages + */ #define MESSAGE(parent, str, buttons) \ (__Messages.OStream() << __FILE__ << " " << __LINE__ << ":\n\n", __Messages.OStream() << str, \ __Messages) \ @@ -120,8 +123,10 @@ extern C__MessagesW __MessagesW; __MessagesW) \ .MessageBox(((parent) == NULL) ? __MessagesParent : (parent), __MessagesTitleW, (buttons)) -/** zobrazi messagebox se zadanym textem, v novem threadu, nerozdistribuje message - volajiciho threadu */ +/* + * Displays a message box with the specified text in a new thread; does not + * dispatch the calling thread's messages + */ #define MESSAGE_T(str, buttons) \ (__Messages.OStream() << __FILE__ << " " << __LINE__ << ":\n\n", __Messages.OStream() << str, \ __Messages) \ @@ -200,48 +205,60 @@ extern C__MessagesW __MessagesW; #endif // MESSAGES_DEBUG -/** zobrazi messagebox se zadanym textem a ikonou informaci, neni v novem - threadu, distribuje message volajiciho threadu */ +/* + * Displays a message box with the specified text and an information icon in + * the current thread; dispatches the calling thread's messages + */ #define MESSAGE_I(parent, str, buttons) \ MESSAGE(parent, str, MB_ICONINFORMATION | (buttons)) #define MESSAGE_IW(parent, str, buttons) \ MESSAGEW(parent, str, MB_ICONINFORMATION | (buttons)) -/** zobrazi messagebox se zadanym textem a ikonou otazky, neni v novem - threadu, distribuje message volajiciho threadu */ +/* + * Displays a message box with the specified text and a question icon in + * the current thread; dispatches the calling thread's messages + */ #define MESSAGE_Q(parent, str, buttons) \ MESSAGE(parent, str, MB_ICONQUESTION | (buttons)) #define MESSAGE_QW(parent, str, buttons) \ MESSAGEW(parent, str, MB_ICONQUESTION | (buttons)) -/** zobrazi messagebox se zadanym textem a ikonou chyby, neni v novem - threadu, distribuje message volajiciho threadu */ +/* + * Displays a message box with the specified text and an error icon in + * the current thread; dispatches the calling thread's messages + */ #define MESSAGE_E(parent, str, buttons) \ MESSAGE(parent, str, MB_ICONEXCLAMATION | (buttons)) #define MESSAGE_EW(parent, str, buttons) \ MESSAGEW(parent, str, MB_ICONEXCLAMATION | (buttons)) -/** zobrazi messagebox se zadanym textem a ikonou informaci, v novem threadu, - nerozdistribuje message volajiciho threadu */ +/* + * Displays a message box with the specified text and an information icon in a new + * thread; does not dispatch the calling thread's messages + */ #define MESSAGE_TI(str, buttons) \ MESSAGE_T(str, MB_ICONINFORMATION | (buttons)) #define MESSAGE_TIW(str, buttons) \ MESSAGE_TW(str, MB_ICONINFORMATION | (buttons)) -/** zobrazi messagebox se zadanym textem a ikonou otazky, v novem threadu, - nerozdistribuje message volajiciho threadu */ +/* + * Displays a message box with the specified text and a question icon in a new + * thread; does not dispatch the calling thread's messages + */ #define MESSAGE_TQ(str, buttons) \ MESSAGE_T(str, MB_ICONQUESTION | (buttons)) #define MESSAGE_TQW(str, buttons) \ MESSAGE_TW(str, MB_ICONQUESTION | (buttons)) -/** zobrazi messagebox se zadanym textem a ikonou chyby, v novem threadu, - nerozdistribuje message volajiciho threadu */ +/* + * Displays a message box with the specified text and an error icon in a new + * thread; does not dispatch the calling thread's messages + */ #define MESSAGE_TE(str, buttons) \ MESSAGE_T(str, MB_ICONEXCLAMATION | (buttons)) @@ -250,33 +267,33 @@ extern C__MessagesW __MessagesW; #ifdef MESSAGES_DEBUG -/// MESSAGE_I zavisla na existenci makra MESSAGES_DEBUG +//MESSAGE_I depends on MESSAGES_DEBUG being defined #define DMESSAGE_I(parent, str, buttons) MESSAGE_I(parent, str, (buttons)) #define DMESSAGE_IW(parent, str, buttons) MESSAGE_IW(parent, str, (buttons)) -/// MESSAGE_Q zavisla na existenci makra MESSAGES_DEBUG +//MESSAGE_Q depends on MESSAGES_DEBUG being defined #define DMESSAGE_Q(parent, str, buttons) MESSAGE_Q(parent, str, (buttons)) #define DMESSAGE_QW(parent, str, buttons) MESSAGE_QW(parent, str, (buttons)) -/// MESSAGE_E zavisla na existenci makra MESSAGES_DEBUG +//MESSAGE_E depends on MESSAGES_DEBUG being defined #define DMESSAGE_E(parent, str, buttons) MESSAGE_E(parent, str, (buttons)) #define DMESSAGE_EW(parent, str, buttons) MESSAGE_EW(parent, str, (buttons)) -/// MESSAGE_TI zavisla na existenci makra MESSAGES_DEBUG +//MESSAGE_TI depends on MESSAGES_DEBUG being defined #define DMESSAGE_TI(str, buttons) MESSAGE_TI(str, (buttons)) #define DMESSAGE_TIW(str, buttons) MESSAGE_TIW(str, (buttons)) -/// MESSAGE_TQ zavisla na existenci makra MESSAGES_DEBUG +//MESSAGE_TQ depends on MESSAGES_DEBUG being defined #define DMESSAGE_TQ(str, buttons) MESSAGE_TQ(str, (buttons)) #define DMESSAGE_TQW(str, buttons) MESSAGE_TQW(str, (buttons)) -/// MESSAGE_E zavisla na existenci makra MESSAGES_DEBUG +//MESSAGE_E depends on MESSAGES_DEBUG being defined #define DMESSAGE_TE(str, buttons) MESSAGE_TE(str, (buttons)) #define DMESSAGE_TEW(str, buttons) MESSAGE_TEW(str, (buttons)) #else // MESSAGES_DEBUG -// aby nedochazelo k problemum se stredniky v nize nadefinovanych makrech +// To avoid semicolon problems in the macros defined below inline int __MessagesEmptyFunction() { return 0; } #define DMESSAGE_I(parent, str, buttons) __MessagesEmptyFunction() @@ -296,13 +313,13 @@ inline int __MessagesEmptyFunction() { return 0; } #else // MESSAGES_DISABLE -// aby nedochazelo k problemum se stredniky v nize nadefinovanych makrech +// To avoid semicolon problems in the macros defined below inline int __MessagesEmptyFunction() { return 0; } #define EnterMessagesModul() __MessagesEmptyFunction() #define LeaveMessagesModul() __MessagesEmptyFunction() -/* tyhle funkce musi hlasit kompilacni chybu +/* These functions must trigger a compile-time error const char *rsc(int resID); const WCHAR *rscW(int resID); const char *spf(const char *formatString, ...); diff --git a/src/common/moore.cpp b/src/common/moore.cpp index e91023415..ed3c01d1a 100644 --- a/src/common/moore.cpp +++ b/src/common/moore.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -7,7 +8,7 @@ #include #include #include -#include // potrebuju LPCOLORMAP +#include // need LPCOLORMAP #if defined(_DEBUG) && defined(_MSC_VER) // without passing file+line to 'new' operator, list of memory leaks shows only 'crtdbg.h(552)' #define new new (_NORMAL_BLOCK, __FILE__, __LINE__) @@ -22,11 +23,9 @@ #include "str.h" #include "moore.h" -// // **************************************************************************** // Initialize -// vypocet poli Fail1 a Fail2 -// +// Calculation of the Fail1 and Fail2 arrays BOOL CSearchData::Initialize() { @@ -74,7 +73,7 @@ BOOL CSearchData::Initialize() Fail1[Pattern[i - 1]] = Length - i; Fail2[i - 1] = 2 * Length - i; } - Fail2[Length] = Length - 1; // doplneno, algoritmus na tuto hodnotu saha, dale neni treba + Fail2[Length] = Length - 1; // filled in; the algorithm uses this value, nothing else is needed i = Length; int t = Length + 1; @@ -162,7 +161,7 @@ void CSearchData::Set(const char* pattern, WORD flags) if (OriginalPattern != NULL) { memcpy(OriginalPattern, pattern, Length); - OriginalPattern[Length] = 0; // pro kompatibilitu s beznym stringem + OriginalPattern[Length] = 0; // for compatibility with regular strings } if (Pattern != NULL) { @@ -189,7 +188,7 @@ void CSearchData::Set(const char* pattern, const int length, WORD flags) if (OriginalPattern != NULL) { memcpy(OriginalPattern, pattern, Length); - OriginalPattern[Length] = 0; // pro kompatibilitu s beznym stringem + OriginalPattern[Length] = 0; // for compatibility with regular strings } if (Pattern != NULL) { diff --git a/src/common/moore.h b/src/common/moore.h index b39a2b806..e3d3cc639 100644 --- a/src/common/moore.h +++ b/src/common/moore.h @@ -1,8 +1,9 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED // **************************************************************************** -// Boyer-Mooruv algoritmus hledani podretezce +// Boyer-Moore substring search algorithm // **************************************************************************** #pragma once @@ -49,8 +50,8 @@ class CSearchData Fail1 != NULL && Fail2 != NULL; } void SetFlags(WORD flags); void Set(const char* pattern, WORD flags); - // pro patterny obsahujici '\0' - // buffer pattern musi mit delku (length + 1) znaku (kompatibilita se stringy) + // for patterns containing '\0' + // the pattern buffer must be (length + 1) characters long (for string compatibility) void Set(const char* pattern, const int length, WORD flags); inline int SearchForward(const char* text, int length, int start); @@ -60,26 +61,24 @@ class CSearchData int Minimum(int a, int b) { return (a < b) ? a : b; } int Maximum(int a, int b) { return (a > b) ? a : b; } - int* Fail1; // fail pole pro akt. pismeno - int* Fail2; // fail pole pro vyskyt substringu zprava - char* OriginalPattern; // puvodni vzorek ke hledani - char* Pattern; // vzorek ke hledani v prislusnem tvaru (Flag) - int Length; // delka vzorku + int* Fail1; // fail array for the current character + int* Fail2; // fail array for substring occurrence from the right + char* OriginalPattern; // original search pattern + char* Pattern; // search pattern in the corresponding flag-dependent form + int Length; // pattern length private: - BOOL Initialize(); // vola se jen ze SetFlags + BOOL Initialize(); // called only from SetFlags - WORD Flags; // menit pres SetFlags + WORD Flags; // modify via SetFlags }; -// // **************************************************************************** // SearchForward -// vraci pozici Patternu nebo -1 -// text - v cem ma hledat -// length - delka stringu text -// start - prvni znak cislovano od 0 -// +// returns the index of Pattern or -1 +// text - text to search in +// length - length of the text string +// start - index of the first character, starting at 0 int CSearchData::SearchForward(const char* text, int length, int start) { @@ -118,13 +117,11 @@ int CSearchData::SearchForward(const char* text, int length, int start) return -1; } -// // **************************************************************************** // SearchBackward -// vraci pozici Patternu nebo -1 -// text - v cem ma hledat -// length - delka stringu text -// +// returns the index of Pattern or -1 +// text - text to search in +// length - length of the text string int CSearchData::SearchBackward(const char* text, int length) { diff --git a/src/common/ms_init.cpp b/src/common/ms_init.cpp index 70909dddf..21670acb7 100644 --- a/src/common/ms_init.cpp +++ b/src/common/ms_init.cpp @@ -1,12 +1,13 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" #include -// modul MS_INIT zajistuje volani konstruktoru statickych objektu ve spravnem poradi -// a na urovni "lib" (pred "user") +// MS_INIT ensures that constructors of static objects are called in the correct order +// and at the "lib" level (before "user") #pragma warning(3 : 4706) // warning C4706: assignment within conditional expression diff --git a/src/common/multimon.cpp b/src/common/multimon.cpp index 10b5e8d23..68748778d 100644 --- a/src/common/multimon.cpp +++ b/src/common/multimon.cpp @@ -1,11 +1,12 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" #include #include -#include // potrebuju LPCOLORMAP +#include // Need LPCOLORMAP. #include #include #include @@ -24,7 +25,7 @@ HWND GetTopVisibleParent(HWND hParent) { - // hledame parenta, ktery uz neni child window (jde o POPUP/OVERLAPPED window) + // Find the first parent that is not a child window (a POPUP/OVERLAPPED window). HWND hIterator = hParent; while ((GetWindowLongPtr(hIterator, GWL_STYLE) & WS_CHILD) && (hIterator = ::GetParent(hIterator)) != NULL && @@ -46,20 +47,20 @@ void MultiMonGetClipRectByRect(const RECT* rect, RECT* workClipRect, RECT* monit void MultiMonGetClipRectByWindow(HWND hByWnd, RECT* workClipRect, RECT* monitorClipRect) { - HMONITOR hMonitor; // na tento monitor okno umistime + HMONITOR hMonitor; // Place the window on this monitor. MONITORINFO mi; mi.cbSize = sizeof(mi); - if (hByWnd != NULL && IsWindowVisible(hByWnd) && !IsIconic(hByWnd)) // pozor, tato podminka je take v MultiMonCenterWindow + if (hByWnd != NULL && IsWindowVisible(hByWnd) && !IsIconic(hByWnd)) // Note: the same condition is also used in MultiMonCenterWindow. { hMonitor = MonitorFromWindow(hByWnd, MONITOR_DEFAULTTONEAREST); - // vytahneme working area desktopu + // Get the monitor work area. GetMonitorInfo(hMonitor, &mi); } else { - // pokud nalezneme foreground okno patrici nasi aplikaci, - // centrujeme okno na stejny desktop + // If the foreground window belongs to our application, + // center the window on the same desktop. HWND hForegroundWnd = GetForegroundWindow(); DWORD processID; GetWindowThreadProcessId(hForegroundWnd, &processID); @@ -69,14 +70,14 @@ void MultiMonGetClipRectByWindow(HWND hByWnd, RECT* workClipRect, RECT* monitorC } else { - // jinak okno centrujeme k primarnimu desktopu + // Otherwise, center the window on the primary desktop. POINT pt; - pt.x = 0; // primarni monitor + pt.x = 0; // Primary monitor. pt.y = 0; hMonitor = MonitorFromPoint(pt, MONITOR_DEFAULTTOPRIMARY); } - // vytahneme working area desktopu + // Get the desktop work area. GetMonitorInfo(hMonitor, &mi); } *workClipRect = mi.rcWork; @@ -88,18 +89,18 @@ void MultiMonCenterWindow(HWND hWindow, HWND hByWnd, BOOL findTopWindow) { if (hWindow == NULL) { - // pri praci s NULL hwnd dochazi k nechtenemu blikani oken + // Using a NULL HWND causes unwanted window flicker. TRACE_E("MultiMonCenterWindow: hWindow == NULL"); return; } if (IsZoomed(hWindow)) { - // s maximalizovany oknem nebudeme hybat + // Do not move a maximized window. return; } - // mame dohledat top-level window + // Need to find the top-level window. if (findTopWindow) { if (hByWnd != NULL) @@ -111,7 +112,7 @@ void MultiMonCenterWindow(HWND hWindow, HWND hByWnd, BOOL findTopWindow) RECT clipR; MultiMonGetClipRectByWindow(hByWnd, &clipR, NULL); RECT byR; - if (hByWnd != NULL && IsWindowVisible(hByWnd) && !IsIconic(hByWnd)) // pozor, tato podminka je take v MultiMonGetClipRectByWindow + if (hByWnd != NULL && IsWindowVisible(hByWnd) && !IsIconic(hByWnd)) // Note: the same condition is also used in MultiMonGetClipRectByWindow. GetWindowRect(hByWnd, &byR); else byR = clipR; @@ -123,14 +124,14 @@ void MultiMonCenterWindowByRect(HWND hWindow, const RECT& clipR, const RECT& byR { if (hWindow == NULL) { - // pri praci s NULL hwnd dochazi k nechtenemu blikani oken + // Using a NULL HWND causes unwanted window flicker. TRACE_E("MultiMonCenterWindowByRect: hWindow == NULL"); return; } if (IsZoomed(hWindow)) { - // s maximalizovany oknem nebudeme hybat + // Do not move a maximized window. return; } @@ -139,20 +140,20 @@ void MultiMonCenterWindowByRect(HWND hWindow, const RECT& clipR, const RECT& byR int wndWidth = wndRect.right - wndRect.left; int wndHeight = wndRect.bottom - wndRect.top; - // vycentrujeme + // Center it. wndRect.left = byR.left + (byR.right - byR.left - wndWidth) / 2; wndRect.top = byR.top + (byR.bottom - byR.top - wndHeight) / 2; wndRect.right = wndRect.left + wndWidth; wndRect.bottom = wndRect.top + wndHeight; - // ohlidame hranice - if (wndRect.left < clipR.left) // pokud je okno vetsi nez clipR, nechame zobrazit jeho levou cast + // Keep it within bounds. + if (wndRect.left < clipR.left) // If the window is larger than clipR, leave its left part visible. { wndRect.left = clipR.left; wndRect.right = wndRect.left + wndWidth; } - if (wndRect.top < clipR.top) // pokud je okno vetsi nez clipR, nechame zobrazit jeho hotni cast + if (wndRect.top < clipR.top) // If the window is larger than clipR, leave its top part visible. { wndRect.top = clipR.top; wndRect.bottom = wndRect.top + wndHeight; @@ -160,7 +161,7 @@ void MultiMonCenterWindowByRect(HWND hWindow, const RECT& clipR, const RECT& byR if (wndWidth <= clipR.right - clipR.left) { - // pokud je okno mensi nez clipR, osetrime aby nelezlo vpravo za hranici clipR + // If the window is smaller than clipR, make sure it does not extend past the right edge of clipR. if (wndRect.right >= clipR.right) { wndRect.left = clipR.right - wndWidth; @@ -169,14 +170,14 @@ void MultiMonCenterWindowByRect(HWND hWindow, const RECT& clipR, const RECT& byR } else { - // pokud je okno vetsi nez clipR + // If the window is larger than clipR. if (wndRect.left > clipR.left) - wndRect.left = clipR.left; // vyuzijeme maximalne prostor + wndRect.left = clipR.left; // Use as much space as possible. } if (wndHeight <= clipR.bottom - clipR.top) { - // pokud je okno mensi nez clipR, osetrime aby nelezlo dole za hranici clipR + // If the window is smaller than clipR, make sure it does not extend past the bottom edge of clipR. if (wndRect.bottom >= clipR.bottom) { wndRect.top = clipR.bottom - wndHeight; @@ -185,9 +186,9 @@ void MultiMonCenterWindowByRect(HWND hWindow, const RECT& clipR, const RECT& byR } else { - // pokud je okno vetsi nez clipR + // If the window is larger than clipR. if (wndRect.top > clipR.top) - wndRect.top = clipR.top; // vyuzijeme maximalne prostor + wndRect.top = clipR.top; // Use as much space as possible. } SetWindowPos(hWindow, NULL, wndRect.left, wndRect.top, 0, 0, @@ -239,10 +240,10 @@ BOOL MultiMonGetDefaultWindowPos(HWND hByWnd, POINT* p) HMONITOR hTmpMonitor = MonitorFromWindow(wnd.HWindow, MONITOR_DEFAULTTONEAREST); if (hTmpMonitor != hMonitor) { - // trik s dummy oknem funguje pekne pod MSVC, ale pri spusteni salamandera bez MSVC - // se okno otevira na primarnim monitoru (nezjistil jsem proc, kdyz ma parenta) + // The dummy-window trick works fine under MSVC, but when Salamander runs without MSVC + // the window opens on the primary monitor (I do not know why, even though it has a parent). - // pomuzeme si -- posuneme okno na nas monitor + // Work around it by moving the window to our monitor. MONITORINFO tmpInfo; tmpInfo.cbSize = sizeof(tmpInfo); GetMonitorInfo(hTmpMonitor, &tmpInfo); @@ -271,12 +272,12 @@ BOOL MultiMonEnsureRectVisible(RECT* rect, BOOL partialOK) RECT intersectRect; BOOL intersect = IntersectRect(&intersectRect, rect, &clipRect); if (EqualRect(&intersectRect, rect)) - return FALSE; // lezime celou plochou na jednom z monitoru, neni co resit + return FALSE; // The entire rectangle is on one monitor, so return FALSE. if (intersect && partialOK) - return FALSE; // jsme zcasti viditelni, neni co resit + return FALSE; // The rectangle is already partially visible, so return FALSE. - // zajistim, aby obdelnik nepresahl pres monitor + // Ensure the rectangle does not extend beyond the monitor work area. if (rect->right - rect->left > clipRect.right - clipRect.left) rect->right = clipRect.right - clipRect.left + rect->left; if (rect->bottom - rect->top > clipRect.bottom - clipRect.top) @@ -310,6 +311,6 @@ BOOL MultiMonEnsureRectVisible(RECT* rect, BOOL partialOK) rect->bottom += y; } - // zmenili jsme nekterou z hodnot, vratime TRUE + // We changed one of the values, so return TRUE. return TRUE; } diff --git a/src/common/regexp.cpp b/src/common/regexp.cpp index cdb28cee1..8c5a87e4b 100644 --- a/src/common/regexp.cpp +++ b/src/common/regexp.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED /* * regcomp and regexec -- regsub and regerror are elsewhere @@ -39,14 +40,14 @@ #pragma warning(3 : 4706) // warning C4706: assignment within conditional expression -//#include "trace.h" aby to slo pripojit i k pluginum, stejne tu zatim zadny TRACE neni +//needed so this can also be built for plugins; there is no TRACE here yet #include "str.h" #include "regexp.h" //***************************************************************************** //***************************************************************************** // -// moje cast regexp.cpp +// my section of regexp.cpp // //***************************************************************************** //***************************************************************************** @@ -65,7 +66,7 @@ class C__RegExpSection C__RegExpSection __RegExpSection; -/* - moznost definice svych vlastnich hlasek, jinak staci nakopirovat do kodu +/* - custom error messages can be defined here; otherwise, copying this into the code is sufficient const char *RegExpErrorText(CRegExpErrors err) { @@ -159,7 +160,7 @@ BOOL CRegularExpression::SetFlags(WORD flags) Expression = regcomp(pattern, LastErrorText); if (Expression != NULL && (Flags & sfForward) == 0) - { // vyraz je syntakticky o.k. + backward search + { // Expression is syntactically correct; backward search. if (Expression != NULL) free(Expression); Expression = NULL; @@ -208,7 +209,7 @@ BOOL CRegularExpression::SetLine(const char* start, const char* end) memcpy(Line, start, LineLength); Line[LineLength] = 0; } - else // insensitive + else // case-insensitive { char* l = Line; while (start < end) @@ -225,7 +226,7 @@ BOOL CRegularExpression::SetLine(const char* start, const char* end) *l++ = *--end; *l = 0; } - else // insensitive + else // case-insensitive { char* l = Line; while (start < end) @@ -263,16 +264,16 @@ BOOL CRegularExpression::ExpandVariables(char* pattern, char* buffer, int bufSiz { char* sour = pattern; char* dest = buffer; - bufSize--; //rezervujeme si misto pro NULL + bufSize--; // Reserve space for the NULL terminator. while (*sour) { if (!bufSize) - return FALSE; //dosel nam buffer + return FALSE; // Out of buffer space. if (*sour == '\\') { sour++; if (!*sour) - break; // tady bych asi mnel hodit chybu takovato sekvence neni definovana + break; // An error should probably be reported here; this sequence is undefined. if (*sour >= '1' && *sour <= '9') { int n = *sour - '0'; @@ -308,9 +309,9 @@ int CRegularExpression::ReplaceForward(int start, char* pattern, BOOL global, char* output = buffer; int len; while (start <= LineLength && regexec(Expression, Line, start) == 1 && - Expression->endp[0] - Expression->startp[0] > 0 /*zero sized match neberem*/) + Expression->endp[0] - Expression->startp[0] > 0 /* Ignore zero-length matches. */) { - //zkopirujeme nezmeny text, ktery predchazi match + //Copy the unchanged text before the match. len = (int)((Expression->startp[0] - Line) - start); if (len + 1 > bufSize) { @@ -319,7 +320,7 @@ int CRegularExpression::ReplaceForward(int start, char* pattern, BOOL global, memcpy(output, OrigLineStart + start, len); output += len; bufSize -= len; - //nahradime co jsme nasli + //Replace the matched text. if (!ExpandVariables(pattern, output, bufSize, &len)) { return FALSE; @@ -334,7 +335,7 @@ int CRegularExpression::ReplaceForward(int start, char* pattern, BOOL global, if (ret && start < LineLength) { - //dokopirujeme text nasledujici match + //Copy the text after the match. if (LineLength - start + 1 > bufSize) { return FALSE; @@ -350,9 +351,9 @@ void CRegularExpression::ReverseRegExp(char*& dstExpEnd, char* srcExp, char* src while (s < srcExpEnd) { - //--- hledani konce atomu - pro zopakovani '*', '+' a '?' - char* ss; // ukazuje za atom - BOOL addPar; // paruji zavorky? (ma se pridat zavorka do paru) + //--- find the end of the atom for '*', '+' and '?' repetition + char* ss; // Points past the atom. + BOOL addPar; // Should a matching parenthesis be added? switch (*s) { case '\\': @@ -362,8 +363,8 @@ void CRegularExpression::ReverseRegExp(char*& dstExpEnd, char* srcExp, char* src case '(': case '[': { - int parNum = (*s == '(') ? 1 : 0; // pocty zavorek - int braNum = (*s == '[') ? 1 : 0; // pocty zavorek + int parNum = (*s == '(') ? 1 : 0; // Parenthesis count. + int braNum = (*s == '[') ? 1 : 0; // Bracket count. char* lastBra = (*s == '[') ? s : NULL; ss = s + 1; while (*ss != 0 && (parNum != 0 || braNum != 0)) @@ -373,10 +374,10 @@ void CRegularExpression::ReverseRegExp(char*& dstExpEnd, char* srcExp, char* src case '(': if (braNum == 0) parNum++; - break; // [..(..] je povoleno + break; // [..(..] is allowed. case '[': { - if (braNum == 0) // [..[..] je povoleno + if (braNum == 0) // [..[..] is allowed. { braNum++; lastBra = ss - 1; @@ -387,13 +388,13 @@ void CRegularExpression::ReverseRegExp(char*& dstExpEnd, char* srcExp, char* src case ')': if (braNum == 0 && parNum > 0) parNum--; - break; // [..)..] je povoleno + break; // [..)..] is allowed. case ']': { - if (braNum != 0) // ..].. je povoleno + if (braNum != 0) // ..].. is allowed. { - if (ss - 2 != lastBra && // []..] je povoleno - (ss - 3 != lastBra || *(ss - 2) != '^')) // [^]..] je take povoleno + if (ss - 2 != lastBra && // []..] is allowed. + (ss - 3 != lastBra || *(ss - 2) != '^')) // [^]..] is also allowed. { braNum--; } @@ -405,7 +406,7 @@ void CRegularExpression::ReverseRegExp(char*& dstExpEnd, char* srcExp, char* src { if (*ss != 0) ss++; - break; // znak za '\\' nemuze byt brany jako zavorka + break; // The character after '\\' cannot be treated as a parenthesis. } } } @@ -422,12 +423,12 @@ void CRegularExpression::ReverseRegExp(char*& dstExpEnd, char* srcExp, char* src break; } - //--- nakopirovani vsech '*', '+' a '?' obsazenych za atomem + //--- copy all '*', '+' and '?' following the atom char* oldSS = ss; while (*ss == '*' || *ss == '?' || *ss == '+') *--dstExpEnd = *ss++; - //--- nakopirovani obraceneho atomu + //--- copy the reversed atom switch (*s) { case '\\': @@ -446,13 +447,13 @@ void CRegularExpression::ReverseRegExp(char*& dstExpEnd, char* srcExp, char* src else *--dstExpEnd = (*s == '(') ? ')' : ']'; - if (oldSS - s >= 2) // pokud vyraz nekonci otevrenou zavorkou + if (oldSS - s >= 2) // if the expression does not end with an opening bracket { if (*s == '(') - { // kopie reversovaneho vyrazu - ohraniceni + { // Copy the reversed expression - parenthesized group. ReverseRegExp(dstExpEnd, s + 1, oldSS - 1); } - else // prosta kopie vnitrku - mnozina + else // Simple copy of the character set contents. { dstExpEnd -= (oldSS - 1) - (s + 1); memcpy(dstExpEnd, s + 1, (oldSS - 1) - (s + 1)); @@ -476,7 +477,7 @@ void CRegularExpression::ReverseRegExp(char*& dstExpEnd, char* srcExp, char* src break; } - //--- prechod na dalsi atom + //--- move to the next atom s = ss; } } @@ -484,7 +485,7 @@ void CRegularExpression::ReverseRegExp(char*& dstExpEnd, char* srcExp, char* src //***************************************************************************** //***************************************************************************** // -// puvodni regexp.cpp +// original regexp.cpp // //***************************************************************************** //***************************************************************************** @@ -608,7 +609,7 @@ void CRegularExpression::ReverseRegExp(char*& dstExpEnd, char* srcExp, char* src /* * Flags to be passed up and down. */ -#define HASWIDTH 01 /* Known never to match null string. */ +#define HASWIDTH 01 /* Known never to match the empty string. */ #define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */ #define SPSTART 04 /* Starts with * or +. */ #define WORST 0 /* Worst case. */ @@ -745,7 +746,7 @@ regexp* regcomp(char* exp, const char*& lastErrorText) } } - lastErrorText = NULL; // uspesny navrat + lastErrorText = NULL; // Successful return. __RegExpSection.Leave(); return (r); } @@ -829,7 +830,7 @@ char* reg(int paren /* Parenthesized? */, int* flagp) } /* - - regbranch - one alternative of an | operator + * regbranch - one alternative of the | operator * * Implements the concatenation operator. */ @@ -902,7 +903,7 @@ char* regpiece(int* flagp) regoptail(ret, regnode(BACK)); /* and loop */ regoptail(ret, ret); /* back */ regtail(ret, regnode(BRANCH)); /* or */ - regtail(ret, regnode(NOTHING)); /* null. */ + regtail(ret, regnode(NOTHING)); /* empty branch. */ } else if (op == '+' && (flags & SIMPLE)) reginsert(PLUS, ret); @@ -1067,7 +1068,7 @@ char* regnode(char op) /* Location. */ ptr = ret; *ptr++ = op; - *ptr++ = '\0'; /* Null "next" pointer. */ + *ptr++ = '\0'; /* Null "next" pointer byte. */ *ptr++ = '\0'; regcode = ptr; @@ -1086,9 +1087,9 @@ void regc(char b) } /* - - reginsert - insert an operator in front of already-emitted operand + * reginsert - insert an operator in front of an already-emitted operand * - * Means relocating the operand. + * This means relocating the operand. */ void reginsert(char op, char* opnd) { @@ -1168,14 +1169,14 @@ char** regstartp; /* Pointer to startp array. */ char** regendp; /* Ditto for endp. */ /* - * Forwards. + * Forward declarations. */ int regtry(regexp* prog, char* string); int regmatch(char* prog); int regrepeat(char* p); /* - - regexec - match a regexp against a string + - regexec - match a regular expression against a string */ int regexec(regexp* prog, char* string, int offset) { @@ -1238,7 +1239,7 @@ int regexec(regexp* prog, char* string, int offset) s++; } else - /* We don't -- general case. */ + /* We don't know the start character -- general case. */ do { if (regtry(prog, s)) @@ -1254,9 +1255,9 @@ int regexec(regexp* prog, char* string, int offset) } /* - - regtry - try match at specific point + - regtry - try a match at a specific point */ -int regtry(regexp* prog, char* string) /* 0 failure, 1 success */ +int regtry(regexp* prog, char* string) /* Returns 0 on failure, 1 on success. */ { int i; char** sp; @@ -1284,13 +1285,13 @@ int regtry(regexp* prog, char* string) /* 0 failure, 1 success */ } /* - - regmatch - main matching routine + * regmatch - main matching routine * - * Conceptually the strategy is simple: check to see whether the current - * node matches, call self recursively to see whether the rest matches, - * and then act accordingly. In practice we make some effort to avoid - * recursion, in particular by going through "ordinary" nodes (that don't - * need to know whether the rest of the match failed) by a loop instead of + * Conceptually the strategy is simple: check whether the current + * node matches, call itself recursively to see whether the rest matches, + * and then act accordingly. In practice, some effort is made to avoid + * recursion, in particular by going through "ordinary" nodes (that do not + * need to know whether the rest of the match failed) in a loop instead of * by recursion. */ int regmatch(char* prog) /* 0 failure, 1 success */ @@ -1448,11 +1449,11 @@ int regmatch(char* prog) /* 0 failure, 1 success */ no = regrepeat(OPERAND(scan)); while (no >= min) { - /* If it could work, try it. */ + /* Try it if it might match. */ if (nextch == '\0' || *reginput == nextch) if (regmatch(next)) return (1); - /* Couldn't or didn't -- back up. */ + /* Match failed or was skipped; back up. */ no--; reginput = save + no; } @@ -1460,7 +1461,7 @@ int regmatch(char* prog) /* 0 failure, 1 success */ } case END: - return (1); /* Success! */ + return (1); /* Match succeeded. */ default: return (0); /* memory corruption */ } diff --git a/src/common/regexp.h b/src/common/regexp.h index 916edfbc3..03337fcaa 100644 --- a/src/common/regexp.h +++ b/src/common/regexp.h @@ -1,12 +1,13 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once //***************************************************************************** //***************************************************************************** // -// puvodni regexp.h +// original regexp.h // //***************************************************************************** //***************************************************************************** @@ -36,12 +37,12 @@ void regerror(const char* error); //***************************************************************************** //***************************************************************************** // -// moje cast regexp.h +// my section of regexp.h // //***************************************************************************** //***************************************************************************** -// chyby, ktere mohou nastat pri compilaci a hledani reg. expr. +// Errors that may occur during regexp compilation and search. enum CRegExpErrors { reeNoError, @@ -59,7 +60,7 @@ enum CRegExpErrors reeInternalDisaster, }; -// funkce, ktera vraci text nastale chyby +// Function that returns the error text. const char* RegExpErrorText(CRegExpErrors err); // search flags @@ -74,18 +75,18 @@ const char* RegExpErrorText(CRegExpErrors err); class CRegularExpression { public: - static const char* LastError; // text posledni chyby + static const char* LastError; // Last error text. protected: const char* LastErrorText; char* OriginalPattern; - regexp* Expression; // nakompilovany regularni vyraz + regexp* Expression; // Compiled regular expression. WORD Flags; - char* Line; // buffer pro radek - const char* OrigLineStart; // pointer na zacatek puvodniho textu (predaneho do SetLine() jako 'start') - int Allocated; // kolik bytu je alokovano - int LineLength; // aktualni delka radky + char* Line; // Line buffer. + const char* OrigLineStart; // Pointer to the start of the original text (passed to SetLine() as 'start'). + int Allocated; // Number of allocated bytes. + int LineLength; // Current line length. public: CRegularExpression() @@ -114,33 +115,33 @@ class CRegularExpression const char* GetPattern() const { return OriginalPattern; } const char* GetLastErrorText() const { return LastErrorText; } - BOOL Set(const char* pattern, WORD flags); // vraci FALSE pri chybe (volat metodu GetLastErrorText) - BOOL SetFlags(WORD flags); // vraci FALSE pri chybe (volat metodu GetLastErrorText) + BOOL Set(const char* pattern, WORD flags); // Returns FALSE on error (call GetLastErrorText). + BOOL SetFlags(WORD flags); // Returns FALSE on error (call GetLastErrorText). - BOOL SetLine(const char* start, const char* end); // radek textu, ve kterem vyhledava, vraci FALSE pri chybe (volat metodu GetLastErrorText) + BOOL SetLine(const char* start, const char* end); // Sets the line of text to search in; returns FALSE on error (call GetLastErrorText). int SearchForward(int start, int& foundLen); int SearchBackward(int length, int& foundLen); - // nahradi promnene \1 ... \9 textem zachycenym odpovidajicima zavorkama - // 'pattern' je vzor kterym se nahrazuje nalezeny match, 'buffer' buffer - // pro vystup, 'bufSize' maximalni velikost textu vcetne ukoncovaciho NULL - // znaku, v promnene 'count' vraci pocet znaku zkopirovanych do bufferu - // vraci TRUE pokud se vyraz vesel cely do bufferu + // Replaces variables \1 ... \9 with the text captured by the corresponding groups. + // 'pattern' is the replacement pattern for the matched text, 'buffer' is the output + // buffer, 'bufSize' is the maximum buffer size including the terminating NULL + // character, and 'count' receives the number of characters copied to 'buffer' + // Returns TRUE if the entire expanded text fit in 'buffer' BOOL ExpandVariables(char* pattern, char* buffer, int bufSize, int* count); - // navratove hodnoty + // Return values // - // 0 hledany text nebyl nalezen, do 'buffer' se nic nekopirovalo - // 1 text byl uspesne nahrazen - // 2 'buffer' je prilis maly + // 0 the text was not found, nothing was copied to 'buffer' + // 1 the text was replaced successfully + // 2 'buffer' is too small int ReplaceForward(int start, char* pattern, BOOL global, char* buffer, int bufSize); protected: - // Obraci regularni vyraz - pro hledani od zadu - // VYRAZ MUSI BYT SYNTAKTICKY SPRAVNY ! JINAK NEFUNGUJE SPRAVNE ! - // napr. "a)b(d)(" -> "((d)b)a" coz je chybne + // Reverses the regular expression for backward search. + // THE EXPRESSION MUST BE SYNTACTICALLY CORRECT, OR IT WILL NOT WORK PROPERLY! + // e.g. "a)b(d)(" -> "((d)b)a", which is incorrect void ReverseRegExp(char*& dstExpEnd, char* srcExp, char* srcExpEnd); }; diff --git a/src/common/sheets.cpp b/src/common/sheets.cpp index da97ef7c8..7f3bbad54 100644 --- a/src/common/sheets.cpp +++ b/src/common/sheets.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -44,7 +45,7 @@ void CElasticLayout::AddResizeCtrl(int resID) RECT r; GetWindowRect(hChild, &r); - // pokud je spodni hrana prvku vetsi nez SplitY, posuneme SplitY hranici + // if the control's bottom edge is below SplitY, move the SplitY boundary POINT p = {r.right, r.bottom}; ScreenToClient(HWindow, &p); if (p.y > SplitY) @@ -67,7 +68,7 @@ CElasticLayout::FindMoveControls(HWND hChild, LPARAM lParam) { CElasticLayout* el = (CElasticLayout*)lParam; - // pokud prvek lezi pod SplitY, pridame ho do seznamu prvku, ktere budou posouvat + // if the control is below SplitY, add it to the list of controls to move RECT r; GetWindowRect(hChild, &r); POINT p = {r.left, r.top}; @@ -87,7 +88,7 @@ void CElasticLayout::FindMoveCtrls() { EnumChildWindows(HWindow, FindMoveControls, (LPARAM)this); - // najdeme obalku vsech 'move' prvku + // find the bounding box of all 'move' controls RECT rEnvelope = {0}; for (int i = 0; i < MoveCtrls.Count; i++) { @@ -107,11 +108,11 @@ void CElasticLayout::FindMoveCtrls() POINT p = {rEnvelope.right, rEnvelope.bottom}; ScreenToClient(HWindow, &p); int envelopeBottom = p.y; - // souradnice 'MoveCtrlsY' budou vztazene od spodni hrany obalky + // 'MoveCtrlsY' coordinates are relative to the bottom edge of the bounding box for (int i = 0; i < MoveCtrls.Count; i++) MoveCtrls[i].Pos.y = envelopeBottom - MoveCtrls[i].Pos.y; - // pro prvky ResizeCtrls ulozime jejich vzdalenost spodni hrany od spodni hrany obalky + // for ResizeCtrls, store the distance from their bottom edge to the bottom edge of the bounding box for (int i = 0; i < ResizeCtrls.Count; i++) { if (ResizeCtrls[i].Pos.y == 0) @@ -198,7 +199,7 @@ void CPropSheetPage::Init(const TCHAR* title, HINSTANCE modul, int resID, Flags = flags; Icon = icon; - ParentDialog = NULL; // nastavuje se z CPropertyDialog::Execute() + ParentDialog = NULL; // set from CPropertyDialog::Execute() ParentPage = NULL; HTreeItem = NULL; Expanded = NULL; @@ -290,7 +291,7 @@ CPropSheetPage::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) TransferData(ttDataToWindow); if (ElasticLayout != NULL) ElasticLayout->LayoutCtrls(); - return TRUE; // chci focus od DefDlgProc + return TRUE; // let DefDlgProc set the focus } case WM_SIZE: @@ -309,7 +310,7 @@ CPropSheetPage::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) (GetKeyState(VK_SHIFT) & 0x8000) != 0); return TRUE; } - break; // F1 nechame propadnout do parenta + break; // Let F1 propagate to the parent } case WM_CONTEXTMENU: @@ -321,26 +322,26 @@ CPropSheetPage::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_NOTIFY: { - if (((NMHDR*)lParam)->code == PSN_KILLACTIVE) // deaktivace stranky + if (((NMHDR*)lParam)->code == PSN_KILLACTIVE) // page deactivation { if (ValidateData()) SetWindowLongPtr(HWindow, DWLP_MSGRESULT, FALSE); - else // nepovolime deaktivaci stranky + else // do not allow the page to be deactivated SetWindowLongPtr(HWindow, DWLP_MSGRESULT, TRUE); return TRUE; } - if (((NMHDR*)lParam)->code == PSN_SETACTIVE) // aktivace stranky + if (((NMHDR*)lParam)->code == PSN_SETACTIVE) // page activation { if (ParentDialog != NULL && ParentDialog->LastPage != NULL) - { // zapamatovani posledni stranky + { // remember the last page *ParentDialog->LastPage = ParentDialog->GetCurSel(); } break; } if (((NMHDR*)lParam)->code == PSN_APPLY) - { // stisknuto tlacitko ApplyNow nebo OK + { // ApplyNow or OK button pressed if (TransferData(ttDataFromWindow)) SetWindowLongPtr(HWindow, DWLP_MSGRESULT, PSNRET_NOERROR); else @@ -349,15 +350,15 @@ CPropSheetPage::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) } if (((NMHDR*)lParam)->code == PSN_WIZFINISH) - { // stisknuto tlacitko Finish - // neprislo PSN_KILLACTIVE - provedu validaci + { // Finish button pressed + // PSN_KILLACTIVE did not arrive, so run validation if (!ValidateData()) { SetWindowLongPtr(HWindow, DWLP_MSGRESULT, TRUE); return TRUE; } - // obehnu vsechny stranky pro transfer + // iterate over all pages for transfer for (int i = 0; i < ParentDialog->Count; i++) { if (ParentDialog->At(i)->HWindow != NULL) @@ -385,7 +386,7 @@ CPropSheetPage::CPropSheetPageProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, CPropSheetPage* dlg; switch (uMsg) { - case WM_INITDIALOG: // prvni zprava - pripojeni objektu k dialogu + case WM_INITDIALOG: // first message - attach the object to the dialog { dlg = (CPropSheetPage*)((PROPSHEETPAGE*)lParam)->lParam; if (dlg == NULL) @@ -397,25 +398,25 @@ CPropSheetPage::CPropSheetPageProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, { dlg->HWindow = hwndDlg; dlg->Parent = ::GetParent(hwndDlg); - //--- zarazeni okna podle hwndDlg do seznamu oken - if (!WindowsManager.AddWindow(hwndDlg, dlg)) // chyba + //--- add the window identified by hwndDlg to the window list + if (!WindowsManager.AddWindow(hwndDlg, dlg)) // error { TRACE_ET(_T("Unable to create dialog.")); return TRUE; } - dlg->NotifDlgJustCreated(); // zavedeno jako misto pro upravu layoutu dialogu + dlg->NotifDlgJustCreated(); // added as a place to adjust the dialog layout } break; } - case WM_DESTROY: // posledni zprava - odpojeni objektu od dialogu + case WM_DESTROY: // last message - detach the object from the dialog { dlg = (CPropSheetPage*)WindowsManager.GetWindowPtr(hwndDlg); - INT_PTR ret = FALSE; // pro pripad, ze ji nezpracuje + INT_PTR ret = FALSE; // in case it does not handle the message if (dlg != NULL && dlg->Is(otDialog)) { - // Petr: posunul jsem dolu pod wnd->WindowProc(), aby behem WM_DESTROY - // jeste dochazely zpravy (potreboval Lukas) + // Petr: moved this below wnd->WindowProc() so messages still arrive during WM_DESTROY + // (Lukas needed this) // WindowsManager.DetachWindow(hwndDlg); ret = dlg->DialogProc(uMsg, wParam, lParam); @@ -424,7 +425,7 @@ CPropSheetPage::CPropSheetPageProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, if (dlg->IsAllocated()) delete dlg; else - dlg->HWindow = NULL; // informace o odpojeni + dlg->HWindow = NULL; // detached state } return ret; } @@ -441,11 +442,11 @@ CPropSheetPage::CPropSheetPageProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, #endif } } - //--- zavolani metody DialogProc(...) prislusneho objektu dialogu + //--- call DialogProc(...) of the corresponding dialog object if (dlg != NULL) return dlg->DialogProc(uMsg, wParam, lParam); else - return FALSE; // chyba nebo message neprisla mezi WM_INITDIALOG a WM_DESTROY + return FALSE; // Error, or the message was not received between WM_INITDIALOG and WM_DESTROY } // @@ -511,14 +512,14 @@ int CPropertyDialog::GetCurSel() #define _TPD_IDC_CAPTION 3 #define _TPD_IDC_RECT 4 #define _TPD_IDC_OK 5 -// rozmery v dlg units -#define _TPD_LEFTMARGIN 4 // odsazeni TreeView a Captionu od leveho okraje -#define _TPD_TOPMARGIN 4 // odsazeni TreeView a Captionu od horniho okraje -#define _TPD_TREE_W 100 // sirka TreeView -#define _TPD_CAPTION_H 16 // vyska captionu -#define _TPD_BUTTON_W 50 // sirka tlacitek -#define _TPD_BUTTON_H 14 // vyska tlacitek -#define _TPD_BUTTON_MARG 4 // rozestup mezi tlacitky +// dimensions in dialog units +#define _TPD_LEFTMARGIN 4 // TreeView and caption left margin +#define _TPD_TOPMARGIN 4 // TreeView and caption top margin +#define _TPD_TREE_W 100 // TreeView width +#define _TPD_CAPTION_H 16 // caption height +#define _TPD_BUTTON_W 50 // button width +#define _TPD_BUTTON_H 14 // button height +#define _TPD_BUTTON_MARG 4 // button spacing CTPHCaptionWindow::CTPHCaptionWindow(HWND hDlg, int ctrlID) : CWindow(hDlg, ctrlID, ooAllocated) @@ -568,7 +569,7 @@ CTPHCaptionWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) GetClientRect(HWindow, &r); int devCaps = GetDeviceCaps(hdc, NUMCOLORS); - if (devCaps == -1) // gradient pouzijeme pouze pri vice nez 256 barvach + if (devCaps == -1) // use the gradient only when more than 256 colors are available { HBRUSH hOldBrush = (HBRUSH)GetCurrentObject(hdc, OBJ_BRUSH); #define TPH_STEPS 100 @@ -609,7 +610,7 @@ CTPHCaptionWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) HFONT hSrcFont = (HFONT)HANDLES(GetStockObject(DEFAULT_GUI_FONT)); GetObject(hSrcFont, sizeof(srcLF), &srcLF); srcLF.lfHeight = (int)(srcLF.lfHeight * 1.2); - // srcLF.lfWeight = FW_BOLD; // na vistach vypada bold dost hnusne + necitelne + // srcLF.lfWeight = FW_BOLD; // bold looks quite ugly and unreadable on Vista hFont = CreateFontIndirect(&srcLF); hOldFont = (HFONT)SelectObject(hdc, hFont); @@ -641,7 +642,7 @@ CTPHGripWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { case WM_SETCURSOR: { - // chceme pouze north-south kurzor + // we only want the north-south cursor SetCursor(LoadCursor(NULL, IDC_SIZENS)); return TRUE; } @@ -666,9 +667,9 @@ CTreePropHolderDlg::CTreePropHolderDlg(HWND hParent, DWORD* windowHeight) INT_PTR CTreePropHolderDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { - // WM_INITDIALOG zavolame az ve chvili, kdy budeme znat rozmery okna + // call WM_INITDIALOG only once we know the window size if (TPD != NULL && uMsg != WM_INITDIALOG) - TPD->DialogProc(uMsg, wParam, lParam); // forward zprav + TPD->DialogProc(uMsg, wParam, lParam); // forward messages switch (uMsg) { case WM_INITDIALOG: @@ -695,8 +696,8 @@ CTreePropHolderDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (appIsThemed) { RECT rect = {0, 0, 4, 8}; - MapDialogRect(HWindow, &rect); // ziskame baseUnitX a baseUnitY pro prepocet dlg-units na pixels - treeIndent = MulDiv(9 /* odsazeni v dlg-units */, rect.right /* baseUnitX */, 4); + MapDialogRect(HWindow, &rect); // get baseUnitX and baseUnitY for converting dialog units to pixels + treeIndent = MulDiv(9 /* indent in dialog units */, rect.right /* baseUnitX */, 4); TreeView_SetIndent(HTreeView, treeIndent); } @@ -722,7 +723,7 @@ CTreePropHolderDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) GripWindow = new CTPHGripWindow(HWindow, _TPD_IDC_GRIP); - // default rozmery jsou minimalni - ulozime si je, abychom je nasledne mohli hlidat + // the default dimensions are the minimum - save them so we can enforce them later GetWindowRect(HWindow, &r); RECT cR; GetClientRect(HWindow, &cR); @@ -734,9 +735,9 @@ CTreePropHolderDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) MarginSize.cy + 1 + MarginSize.cy + ButtonSize.cy + MarginSize.cy + marginH; - // nastavime uzivatelsky rozmer okna a provedeme layout prvku + // apply the user window size and lay out the controls int height = (int)*WindowHeight; - RECT clipR; // nechceme byt vetsi nez vyska obrazovky + RECT clipR; // do not exceed the screen height MultiMonGetClipRectByWindow(HWindow, &clipR, NULL); if (height > clipR.bottom - clipR.top) height = clipR.bottom - clipR.top; @@ -748,7 +749,7 @@ CTreePropHolderDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) LayoutControls(); TreeView_EnsureVisible(HTreeView, TPD->At(TPD->StartPage)->HTreeItem); - TPD->DialogProc(uMsg, wParam, lParam); // forward zprav + TPD->DialogProc(uMsg, wParam, lParam); // forward messages break; } @@ -761,7 +762,7 @@ CTreePropHolderDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) (GetKeyState(VK_CONTROL) & 0x8000) != 0, (GetKeyState(VK_SHIFT) & 0x8000) != 0); } - return TRUE; // F1 nenechame propadnout do parenta ani pokud nevolame WinLibHelp->OnHelp() + return TRUE; // do not let F1 propagate to the parent even if we do not call WinLibHelp->OnHelp() } case WM_COMMAND: @@ -787,11 +788,11 @@ CTreePropHolderDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case _TPD_IDC_OK: { - // musim provest validaci aktualni stranky + // validate the current page if (!ChildDialog->ValidateData()) return TRUE; - // obehnu vsechny stranky pro transfer + // iterate over all pages for transfer for (int i = 0; i < TPD->Count; i++) if (TPD->At(i)->HWindow != NULL) if (!TPD->At(i)->TransferData(ttDataFromWindow)) @@ -805,7 +806,7 @@ CTreePropHolderDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) } } - // preposleme message, aby chodil enter na default tlacitka + // forward the message so Enter is routed to the default buttons if (ChildDialog != NULL && HIWORD(wParam) == BN_CLICKED) ::SendMessage(ChildDialog->HWindow, uMsg, wParam, lParam); @@ -873,7 +874,7 @@ CTreePropHolderDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_NCHITTEST: { - // Resize chceme pouze ve svyslem smeru + // resize only vertically LRESULT ht = DefWindowProc(HWindow, uMsg, wParam, lParam); switch (ht) { @@ -902,7 +903,7 @@ CTreePropHolderDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_GETMINMAXINFO: { - // Resize chceme pouze ve svyslem smeru + // resize only vertically LPMINMAXINFO lpmmi = (LPMINMAXINFO)lParam; lpmmi->ptMinTrackSize.x = MinWindowSize.cx; lpmmi->ptMaxTrackSize.x = MinWindowSize.cx; @@ -1025,9 +1026,9 @@ void CTreePropHolderDlg::LayoutControls() SWP_NOZORDER)); HANDLES(EndDeferWindowPos(hdwp)); - // hack: v treeview/common controls je zrejme chyba: pokud naskoci diky obsahu scrollbar, - // neprekresli se selected polozka, takze je vpravo orizla; muze to souviset s full row - // select a jeste aero lookem; kazdopadne prekresleni pod W7 neblika, asi si ho muzeme dovolit + // hack: TreeView/common controls apparently have a bug: if a scrollbar appears because of the content, + // the selected item is not redrawn, so it gets clipped on the right; this may be related to full-row + // selection and the Aero look; in any case, repainting under W7 does not flicker, so we can probably afford it InvalidateRect(HTreeView, NULL, false); } } @@ -1046,19 +1047,19 @@ int CTreePropHolderDlg::BuildAndMeasureTree() tvis.item.pszText = TPD->At(i)->Title; tvis.item.cchTextMax = (int)_tcslen(TPD->At(i)->Title); tvis.item.state = 0; - // POZOR: expandovatelne polozky zde musime expandovat, jinak nasledne TreeView_GetItemRect() vrati FALSE - // a nahodna data v obdelniku RECT r + // WARNING: expandable items must be expanded here, otherwise TreeView_GetItemRect() returns FALSE + // and RECT r contains random data if (TPD->At(i)->Expanded != NULL) tvis.item.state |= TVIS_EXPANDED; tvis.item.stateMask = tvis.item.state; tvis.item.lParam = (LPARAM)TPD->At(i); TPD->At(i)->HTreeItem = TreeView_InsertItem(HTreeView, &tvis); RECT r; - // Radeji navratovou hodnotu TreeView_GetItemRect() vezmeme v potaz + // take the return value of TreeView_GetItemRect() into account if (TreeView_GetItemRect(HTreeView, TPD->At(i)->HTreeItem, &r, TRUE) && r.right - r.left > width) width = r.right - r.left; } - // Nyni jiz muzeme pozavirat neexpandovane polozky + // now we can collapse the items that were not expanded for (int i = 0; i < TPD->Count; i++) { if (TPD->At(i)->Expanded != NULL && *TPD->At(i)->Expanded == FALSE) @@ -1224,7 +1225,7 @@ int CTreePropDialog::Execute(const TCHAR* buttonOK, RECT maxPageRect; SetRectEmpty(&maxPageRect); - // zjistim maximalni rozmery + // determine the maximum dimensions for (int i = 0; i < Count; i++) { At(i)->ParentDialog = this; @@ -1252,9 +1253,9 @@ int CTreePropDialog::Execute(const TCHAR* buttonOK, dlgStyle = *(DWORD*)(pageTemplate + 6); // style dlgCX = *(short*)(pageTemplate + 11); // cx dlgCY = *(short*)(pageTemplate + 12); // cy - WORD* t = pageTemplate + 13; // menu, preskocime na tridu dialogu, a pak na jeho titulek + WORD* t = pageTemplate + 13; // menu, skip to the dialog class, then to its title if (*t == 0) - t++; // zadne menu + t++; // no menu else { if (*t == 0xffff) @@ -1263,13 +1264,13 @@ int CTreePropDialog::Execute(const TCHAR* buttonOK, t += wcslen((wchar_t*)t) + 1; // menu string } if (*t == 0) - t++; // zadna trida dialogu + t++; // no dialog class else { if (*t == 0xffff) - t += 2; // ID tridy dialogu + t += 2; // dialog class ID else - t += wcslen((wchar_t*)t) + 1; // string tridy dialogu + t += wcslen((wchar_t*)t) + 1; // dialog class string } dlgTitle = (WCHAR*)t; @@ -1302,7 +1303,7 @@ int CTreePropDialog::Execute(const TCHAR* buttonOK, maxPageRect.bottom = dlgCY; } - // vyska od spodniho okraje dialogu ke spodku TreeView a ChildDialogu + // height from the dialog bottom to the bottom of TreeView and ChildDialog int lowMargin = 2 * _TPD_TOPMARGIN + _TPD_BUTTON_H + _TPD_TOPMARGIN + _TPD_TOPMARGIN / 2; SIZE dialogSize; dialogSize.cx = _TPD_LEFTMARGIN + _TPD_TREE_W + _TPD_LEFTMARGIN + maxPageRect.right + @@ -1310,8 +1311,8 @@ int CTreePropDialog::Execute(const TCHAR* buttonOK, dialogSize.cy = _TPD_TOPMARGIN + _TPD_CAPTION_H + _TPD_TOPMARGIN + maxPageRect.bottom + lowMargin; - // postavim template dialogu: DLG nebo DLGEX, podle formatu stranek, musi byt shodny, - // jinak dochazi k orezu controlu a lisi se pisma stranek a zbytku tree property dialogu + // build the dialog template as DLG or DLGEX to match the page format; + // otherwise controls get clipped and page fonts differ from the rest of the tree property dialog HGLOBAL hgbl; @@ -1340,7 +1341,7 @@ int CTreePropDialog::Execute(const TCHAR* buttonOK, *lpw++ = 0; // predefined dialog box class (by default) lpwsz = (LPWSTR)lpw; lpw += WinLibCopyText(lpwsz, Caption, 100); // title - *lpw++ = 8; // velikost fontu + *lpw++ = 8; // font size *lpw++ = FW_NORMAL; // font weight *(BYTE*)lpw = FALSE; // is font italic? *((BYTE*)lpw + 1) = ANSI_CHARSET; // font charset @@ -1361,7 +1362,7 @@ int CTreePropDialog::Execute(const TCHAR* buttonOK, AddItemEx(lpw, _T("static"), _TPD_IDC_CAPTION, 0, 0, 0, 0, WS_CHILD | WS_VISIBLE, 0, NULL); - // Static, ktery je behem initu nahrazen child dialogem + // static control replaced by the child dialog during init AddItemEx(lpw, _T("static"), _TPD_IDC_RECT, 0, 0, maxPageRect.right, maxPageRect.bottom, WS_CHILD, 0, NULL); @@ -1369,7 +1370,7 @@ int CTreePropDialog::Execute(const TCHAR* buttonOK, AddItemEx(lpw, _T("static"), _TPD_IDC_SEP, 0, 0, 0, 0, WS_GROUP | WS_CHILD | WS_VISIBLE | SS_ETCHEDHORZ, 0, NULL); - // Spodni rada tlacitek + // bottom row of buttons AddItemEx(lpw, _T("button"), _TPD_IDC_OK, 0, 0, 0, 0, WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON | WS_TABSTOP, 0, buttonOK); diff --git a/src/common/sheets.h b/src/common/sheets.h index 3ab5b249d..8a6197c24 100644 --- a/src/common/sheets.h +++ b/src/common/sheets.h @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once @@ -10,17 +11,17 @@ class CTreePropHolderDlg; struct CElasticLayoutCtrl { - HWND HCtrl; // handl prvku, ktery mame posouvat - POINT Pos; // pozice prvku vuci spodni hrane opsane obalky + HWND HCtrl; // handle of the control to move + POINT Pos; // control position relative to the bottom edge of the bounding box }; -// pomocna trida slouzici pro layout prvku dialogu na zaklade jeho velikosti +// helper class for laying out dialog controls based on the dialog size class CElasticLayout { public: CElasticLayout(HWND hWindow); void AddResizeCtrl(int resID); - // provede rozmisteni prvku + // lays out the controls void LayoutCtrls(); protected: @@ -29,25 +30,25 @@ class CElasticLayout void FindMoveCtrls(); protected: - // handle dialogu, jehoz layout zajistujeme + // handle of the dialog whose layout we manage HWND HWindow; - // delici linka, od ktere jiz prvky posouvame (lezi na spodni hrane ResizeCntrls) - // client souradnice v bodech + // divider line from which controls start moving (lies on the bottom edge of ResizeCtrls) + // client coordinates, in pixels int SplitY; - // prvky ktere s velikosti natahujeme (typicky listview) + // controls that resize with the dialog (typically list views) TDirectArray ResizeCtrls; - // docasne pole plnene z FindMoveCtrls; idealne by slo o lokalni promennou, ale - // pro pohodlne volani callbacku FindMoveControls (kam ho potrebujeme predat) - // ho umistuji jako atribut tridy + // temporary array populated by FindMoveCtrls; ideally this would be a local variable, but + // for convenient calls to the FindMoveControls callback (to which it must be passed) + // it is stored as a class member TDirectArray MoveCtrls; }; class CPropSheetPage : protected CDialog { public: - CDialog::SetObjectOrigin; // zpristupneni povolenych metod predku + CDialog::SetObjectOrigin; // expose selected base-class methods CDialog::Transfer; - CDialog::HWindow; // HWindow zustane take pristupne + CDialog::HWindow; // HWindow also remains accessible CPropSheetPage(const TCHAR* title, HINSTANCE modul, int resID, DWORD flags /* = PSP_USETITLE*/, HICON icon, @@ -79,13 +80,13 @@ class CPropSheetPage : protected CDialog DWORD Flags; HICON Icon; - CPropertyDialog* ParentDialog; // vlastnik teto stranky - // pro TreeDialog + CPropertyDialog* ParentDialog; // owner of this page + // for TreeDialog CPropSheetPage* ParentPage; HTREEITEM HTreeItem; BOOL* Expanded; - // pokud je ruzne od NULL, se zmenou velikosti dialogu menime layout prvku + // if not NULL, resizing the dialog also updates the control layout CElasticLayout* ElasticLayout; friend class CPropertyDialog; @@ -119,7 +120,7 @@ class CPropertyDialog : public TIndirectArray virtual int GetCurSel(); protected: - HWND Parent; // parametry pro vytvareni dialogu + HWND Parent; // dialog creation parameters HWND HWindow; HINSTANCE Modul; HICON Icon; @@ -128,7 +129,7 @@ class CPropertyDialog : public TIndirectArray DWORD Flags; PFNPROPSHEETCALLBACK Callback; - DWORD* LastPage; // posledni zvolena stranka (muze byt NULL, pokud nezajima) + DWORD* LastPage; // last selected page (may be NULL if not needed) friend class CPropSheetPage; }; @@ -137,8 +138,8 @@ class CPropertyDialog : public TIndirectArray class CTreePropDialog; -// sedivy stinovany pruh nad property sheet v tree variante PropertyDialog, -// kde je zobrazen nazev aktualni stranky +// gray shaded bar above the property sheet in the tree variant of PropertyDialog, +// showing the name of the current page class CTPHCaptionWindow : protected CWindow { protected: @@ -155,7 +156,7 @@ class CTPHCaptionWindow : protected CWindow virtual LRESULT WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam); }; -// na grip controlu chceme pouze top-down kurzor +// show only the resize cursor over the grip control class CTPHGripWindow : public CWindow { public: @@ -165,7 +166,7 @@ class CTPHGripWindow : public CWindow virtual LRESULT WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam); }; -// dialog, ktery drzi treeview, stinovany nadpis a aktualni property sheet +// dialog that hosts the tree view, shaded caption, and current property sheet class CTreePropHolderDlg : public CDialog { protected: @@ -176,17 +177,17 @@ class CTreePropHolderDlg : public CDialog RECT ChildDialogRect; int CurrentPageIndex; CPropSheetPage* ChildDialog; - int ExitButton; // idcko tlacitka, ktere ukoncilo dialog - - // rozmery v bodech - SIZE MinWindowSize; // minimalni rozmery dialogu (urcene podle nejvetsiho child dlg) - DWORD* WindowHeight; // aktualni vyska dialogu - int TreeWidth; // sirka treeview, pocitana na zaklade obsahu - int CaptionHeight; // vyska titulku - SIZE ButtonSize; // rozmery tlacitek na spodni hrane dialogu - int ButtonMargin; // mezera mezi tlacitky - SIZE GripSize; // rozmery resize gripu v pravem spodnim rohu dialogu - SIZE MarginSize; // vodorovny a svisly okraj + int ExitButton; // ID of the button that closed the dialog + + // dimensions in points + SIZE MinWindowSize; // minimum dialog size (determined by the largest child dialog) + DWORD* WindowHeight; // current dialog height + int TreeWidth; // tree view width, calculated from the contents + int CaptionHeight; // caption height + SIZE ButtonSize; // size of the buttons along the bottom edge of the dialog + int ButtonMargin; // spacing between buttons + SIZE GripSize; // size of the resize grip in the dialog's bottom-right corner + SIZE MarginSize; // horizontal and vertical margins public: CTreePropHolderDlg(HWND hParent, DWORD* windowHeight); @@ -205,7 +206,7 @@ class CTreePropHolderDlg : public CDialog friend class CTreePropDialog; }; -// datovy drzak stranek pro tree verzi PropertyDialog +// page data holder for the tree version of PropertyDialog class CTreePropDialog : public CPropertyDialog { protected: @@ -235,6 +236,6 @@ class CTreePropDialog : public CPropertyDialog // DLGTEMPLATE *DoLockDlgRes(int page); friend class CTreePropHolderDlg; - // pouze pro forwarding zprav z CTreePropHolderDlg + // only for forwarding messages from CTreePropHolderDlg virtual void DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) {}; }; diff --git a/src/common/str.cpp b/src/common/str.cpp index 88b762b3b..94cde9e2d 100644 --- a/src/common/str.cpp +++ b/src/common/str.cpp @@ -1,12 +1,13 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" #include #include #include -#include // potrebuju LPCOLORMAP +#include // need LPCOLORMAP #if defined(_DEBUG) && defined(_MSC_VER) // without passing file+line to 'new' operator, list of memory leaks shows only 'crtdbg.h(552)' #define new new (_NORMAL_BLOCK, __FILE__, __LINE__) @@ -14,7 +15,7 @@ #ifndef STR_DISABLE -#ifdef INSIDE_SPL // pro pouziti v pluginech +#ifdef INSIDE_SPL // for use in plugins #include "spl_base.h" #include "dbg.h" #else //INSIDE_SPL @@ -26,7 +27,7 @@ #include "str.h" -#ifndef INSIDE_SPL // krome pouziti v pluginech +#ifndef INSIDE_SPL // except for use in plugins // The order here is important. // Section names must be 8 characters or less. @@ -38,15 +39,15 @@ // boundaries so we can find the real functions // that we need to call for initialization. -#pragma warning(disable : 4075) // chceme definovat poradi inicializace modulu +#pragma warning(disable : 4075) // define the module initialization order typedef void(__cdecl* _PVFV)(void); #pragma section(".i_str$a", read) -__declspec(allocate(".i_str$a")) const _PVFV i_str = (_PVFV)1; // na zacatek sekce .i_str si dame promennou i_str +__declspec(allocate(".i_str$a")) const _PVFV i_str = (_PVFV)1; // place the i_str variable at the start of the .i_str section #pragma section(".i_str$z", read) -__declspec(allocate(".i_str$z")) const _PVFV i_str_end = (_PVFV)1; // a na konec sekce .i_str si dame promennou i_str_end +__declspec(allocate(".i_str$z")) const _PVFV i_str_end = (_PVFV)1; // and place the i_str_end variable at the end of the .i_str section void Initialize__Str() { @@ -65,7 +66,7 @@ BYTE UpperCase[256]; void InitializeCase(); -class C__STR_module // automaticka inicializace modulu +class C__STR_module // automatic module initialization { public: C__STR_module() { InitializeCase(); } @@ -125,16 +126,16 @@ int StrICpy(char* dest, const char* src) while (*src != 0) *dest++ = LowerCase[*src++]; *dest = 0; - return (int)(src - s); // vratime pocet nakopirovanych znaku + return (int)(src - s); // return the number of copied characters } // //***************************************************************************** #ifdef _WIN64 -// Ani ve VC11 MS nedodali x64 ASM verze stringovych operaci, takze zatim take zustavame v C++ +// Even in VC11, MS did not provide x64 ASM versions of the string operations, so for now we stay with C++. -// puvodni funkce +// original function int StrICmp(const char* s1, const char* s2) { int res; @@ -142,7 +143,7 @@ int StrICmp(const char* s1, const char* s2) { res = (unsigned)LowerCase[*s1] - (unsigned)LowerCase[*s2++]; if (res != 0) - return (res < 0) ? -1 : 1; // < a > + return (res < 0) ? -1 : 1; // < or > if (*s1++ == 0) return 0; // == } @@ -159,14 +160,14 @@ int StrICmp(const char* s1, const char* s2) mov edi,[s1] // edi = s1 mov edx,table // edx = LowerCase - mov eax,255 // fall into loop + mov eax,255 // enter the loop xor ebx,ebx align 4 // compare chk_null: - or al,al // not that if al == 0, then eax == 0! + or al,al // note that if al == 0, then eax == 0 jz short done mov al,[esi] // al = *s2 @@ -190,8 +191,8 @@ int StrICmp(const char* s1, const char* s2) } - // navratova hodnota je v eax, abychom obesli warning prekladace - // pro funkce bez navratove hodnoty, udelame nasledujici opicarnu + // the return value is in eax to avoid a compiler warning + // for functions without a return value, use the following hack BOOL retVal; __asm {mov retVal, eax} return retVal; @@ -202,8 +203,8 @@ int StrICmp(const char* s1, const char* s2) //***************************************************************************** /* -// puvodni funkce -// pozor, zde je chyba StrNICmp("a", "aa", 2) vraci 0 +// original function +// warning: StrNICmp("a", "aa", 2) incorrectly returns 0 int StrNICmp(const char *s1, const char *s2, int n) { int res; @@ -218,9 +219,9 @@ int StrNICmp(const char *s1, const char *s2, int n) */ #ifdef _WIN64 -// Ani ve VC11 MS nedodali x64 ASM verze stringovych operaci, takze zatim take zustavame v C++ +// Even in VC11, MS did not provide x64 ASM versions of the string operations, so for now we stay with C++. -// opravena verze +// fixed version int StrNICmp(const char* s1, const char* s2, int n) { int res; @@ -258,14 +259,14 @@ int StrNICmp(const char* s1, const char* s2, int n) lupe: mov al,[esi] // al = *s1 - or eax,eax // see if *s1 is null + or eax,eax // check whether *s1 is null mov bl,[edi] // bl = *s2 jz short eject // jump if *s1 is null or ebx,ebx // see if *s2 is null - jz short eject // jump if so + jz short eject // jump if *s2 is null inc esi inc edi @@ -293,8 +294,8 @@ int StrNICmp(const char* s1, const char* s2, int n) toend: mov eax,ecx // move return value to eax } - // navratova hodnota je v eax, abychom obesli warning prekladace - // pro funkce bez navratove hodnoty, udelame nasledujici opicarnu + // the return value is in eax to avoid a compiler warning + // for functions without a return value, use the following hack BOOL retVal; __asm {mov retVal, eax} return retVal; @@ -306,11 +307,11 @@ int StrNICmp(const char* s1, const char* s2, int n) //***************************************************************************** #ifdef _WIN64 -// Ani ve VC11 MS nedodali x64 ASM verze stringovych operaci, takze zatim take zustavame v C++ +// Even in VC11, MS did not provide x64 ASM versions of the string operations, so for now we stay with C++. int MemICmp(const void* buf1, const void* buf2, int n) { int ret = _memicmp(buf1, buf2, n); - // normalizujeme navratovou hodnotu dle nasi specifikace + // normalize the return value to match our specification if (ret == 0) return 0; return (ret < 0) ? -1 : 1; @@ -365,8 +366,8 @@ int MemICmp(const void* buf1, const void* buf2, int n) toend: mov eax,ecx // move return value to eax } - // navratova hodnota je v eax, abychom obesli warning prekladace - // pro funkce bez navratove hodnoty, udelame nasledujici opicarnu + // the return value is in eax to avoid a compiler warning + // for functions without a return value, use the following hack BOOL retVal; __asm {mov retVal, eax} return retVal; @@ -377,9 +378,9 @@ int MemICmp(const void* buf1, const void* buf2, int n) //***************************************************************************** #ifdef _WIN64 -// Ani ve VC11 MS nedodali x64 ASM verze stringovych operaci, takze zatim take zustavame v C++ +// Even in VC11, MS did not provide x64 ASM versions of the string operations, so for now we stay with C++. -// puvodni funkce +// original function int StrICmpEx(const char* s1, int l1, const char* s2, int l2) { int res, l = (l1 < l2) ? l1 : l2; @@ -387,16 +388,16 @@ int StrICmpEx(const char* s1, int l1, const char* s2, int l2) { res = (unsigned)LowerCase[*s1++] - (unsigned)LowerCase[*s2++]; if (res != 0) - return (res < 0) ? -1 : 1; // < a > + return (res < 0) ? -1 : 1; // < or > } if (l1 != l2) - return (l1 < l2) ? -1 : 1; // < a > + return (l1 < l2) ? -1 : 1; // < or > else return 0; } /* -// princip asm funkce +// logic of the assembly function int StrICmpEx(const char *s1, int l1, const char *s2, int l2) { int l = (l1 < l2) ? l1 : l2; @@ -425,7 +426,7 @@ int StrICmpEx(const char* s1, int l1, const char* s2, int l2) // load up arguments mov ecx,[l] // ecx = byte count or ecx,ecx - jz toend // if count = 0, we are done + jz toend // if the byte count is 0, we are done mov esi,s1 // esi = buf1 mov edi,s2 // edi = buf2 @@ -466,8 +467,8 @@ int StrICmpEx(const char* s1, int l1, const char* s2, int l2) toend: mov eax,ecx // move return value to eax } - // navratova hodnota je v eax, abychom obesli warning prekladace - // pro funkce bez navratove hodnoty, udelame nasledujici opicarnu + // the return value is in eax to avoid a compiler warning + // for functions without a return value, use the following hack BOOL retVal; __asm {mov retVal, eax} if (retVal != 0) return retVal; @@ -484,7 +485,7 @@ int StrICmpEx(const char* s1, int l1, const char* s2, int l2) //***************************************************************************** /* -// puvodni funkce +// original function int StrCmpEx(const char *s1, int l1, const char *s2, int l2) { int res, l = (l1 < l2) ? l1 : l2; @@ -498,7 +499,7 @@ int StrCmpEx(const char *s1, int l1, const char *s2, int l2) } */ -// rychlejsi varianta +// faster variant int StrCmpEx(const char* s1, int l1, const char* s2, int l2) { int l = (l1 < l2) ? l1 : l2; @@ -566,7 +567,7 @@ int StrLen(const char *str) while (1) { if ((((*(DWORD *)s) & 0xF0F0F0F0) - 0x10101010) & 0x8F0F0F0F) - { // je tam znak < 16 + { // contains a character < 16 if (*s != 0) s++; else break; if (*s != 0) s++; @@ -585,7 +586,7 @@ int StrLen(const char *str) /* //***************************************************************************** // -// Tabulky pro prevod kodu Kamenickych do MS Windows +// Tables for converting Kamenicky encoding to MS Windows // BYTE KodKamenickych[CONVERT_TAB_CHARS] = diff --git a/src/common/str.h b/src/common/str.h index 8aa76a078..d99c2f1b6 100644 --- a/src/common/str.h +++ b/src/common/str.h @@ -1,26 +1,27 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once //***************************************************************************** // // 20.1.2003 -// Poznamka k optimalizacim prevodem do ASM: optimalizace se projevi predevsim -// u porovnani shodnych retezcu, tedy da-li se funkcim prilezitost k prohledavat -// retezce cele. Navic je optimalizace znatelnejsi na starsich procesorech, kde -// ASM varianty dokazou pracovat 8x rychleji (stara pentia). // -// Moderni procesory (AMD Athlon, Pentium Pro) dokazou optimalizovanou C++ -// variantu vykonat temer stejne rychle jako jeji ASM variantu. Protoze ale -// zatim nejsou optimalizovane C++ varianty rychlejsi a ASM je mnohem rychlejsi -// nez debug C++ varianta, pouzivame ASM varianty. +// Note on optimizations by converting to ASM: the benefit shows up mainly +// when comparing identical strings, that is, when the functions get a chance to scan +// entire strings. The optimization is also more noticeable on older processors, +//where the ASM variants can run up to 8x faster (old Pentiums). // -// Funkce StrNICmp v C++ na Pentiu Pro beha rychleji nez v ASM varianta. +// Modern processors (AMD Athlon, Pentium Pro) can execute the optimized C++ +// variant almost as fast as its ASM variant. Because the optimized C++ variants +// are not faster yet, and ASM is much faster than the debug C++ variant, we use +//the ASM variants. // +//The C++ version of StrNICmp runs faster on Pentium Pro than the ASM variant. -extern BYTE LowerCase[256]; // premapovani vsech znaku na male; generovano pomoci API CharLower -extern BYTE UpperCase[256]; // premapovani vsech znaku na velke; generovano pomoci API CharUpper +extern BYTE LowerCase[256]; // maps all characters to lowercase; generated using the CharLower API +extern BYTE UpperCase[256]; // maps all characters to uppercase; generated using the CharUpper API //***************************************************************************** // @@ -142,30 +143,30 @@ int StrNICmp(const char* s1, const char* s2, int n); // int MemICmp(const void* buf1, const void* buf2, int n); -// rychlejsi strlen, jede po ctyrech znacich -// do str se saha po ctyrech bytech -> nutny vetsi buffer -// int StrLen(const char *str); // pouze 2 x rychlejsi, zbytecne riziko pristupu do nezarovnane pameti +// faster strlen; processes four characters at a time +// the string is accessed four bytes at a time -> requires a larger buffer +// int StrLen(const char *str); // only 2x faster; unnecessary risk of unaligned memory access -// nakopiruje text do nove naalokovaneho prostoru, NULL = malo pameti +// copies the text into newly allocated memory; returns NULL on out-of-memory char* DupStr(const char* txt); -// nakopiruje text do nove naalokovaneho prostoru, NULL = malo pameti, -// navic pri nedostatku pameti nastavi 'err' na TRUE +// copies the text into newly allocated memory; returns NULL on out-of-memory, +// and also sets 'err' to TRUE on out-of-memory char* DupStrEx(const char* str, BOOL& err); -// vraci prvni vyskyt 'pattern' v 'txt' nebo NULL, je case-insensitive +// returns the first case-insensitive occurrence of 'pattern' in 'txt', or NULL const char* StrIStr(const char* txt, const char* pattern); -// vraci prvni vyskyt 'pattern' v 'txt' nebo NULL, je case-insensitive +// returns the first case-insensitive occurrence of 'pattern' in 'txt', or NULL const char* StrIStr(const char* txtStart, const char* txtEnd, const char* patternStart, const char* patternEnd); -// pripoji retezec 'src' za retezec 'dest', ale neprekroci delku 'dstSize' -// retezec zakoncuje nulou, ktera spada do delky 'dstSize' -// vraci 'dst' +// appends 'src' to 'dst', but does not exceed 'dstSize' +// null-terminates the string within 'dstSize' +// returns 'dst' char* StrNCat(char* dst, const char* src, int dstSize); -// tento historicky kod uz nikdo nepouziva +// this legacy code is no longer used /* #define CONVERT_TAB_CHARS 44 #define CONVERT_TAB_MAX_CHARS 256 @@ -183,11 +184,12 @@ class CConvertTab extern CConvertTab ConvertTab; */ -//***************************************************************************** +// ***************************************************************************** // // SWPrintFToEnd_s // -// jedina odlisnost od swprintf_s je, ze zapisuje az za text umisteny v bufferu +// The only difference from swprintf_s is that it writes after the text already +// stored in the buffer template inline int SWPrintFToEnd_s(WCHAR (&_Dst)[_Size], const WCHAR* _Format, ...) @@ -206,11 +208,12 @@ inline int SWPrintFToEnd_s(WCHAR* _Dst, size_t _SizeInWords, const WCHAR* _Forma return vswprintf_s(_Dst + len, _SizeInWords - len, _Format, _ArgList); } -//***************************************************************************** +// ***************************************************************************** // // SPrintFToEnd_s // -// jedina odlisnost od swprintf_s je, ze zapisuje az za text umisteny v bufferu +// The only difference from sprintf_s is that it writes after the text already +// stored in the buffer template inline int SPrintFToEnd_s(char (&_Dst)[_Size], const char* _Format, ...) diff --git a/src/common/strutils.cpp b/src/common/strutils.cpp index e197337c9..3e209ea7a 100644 --- a/src/common/strutils.cpp +++ b/src/common/strutils.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -32,23 +33,23 @@ int ConvertU2A(const WCHAR* src, int srcLen, char* buf, int bufSize, BOOL compos int res = WideCharToMultiByte(codepage, compositeCheck ? WC_COMPOSITECHECK : 0, src, srcLen, buf, bufSize, NULL, NULL); if (srcLen != -1 && res > 0) res++; - if (compositeCheck && res == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) // nektere codepage nepodporuji WC_COMPOSITECHECK + if (compositeCheck && res == 0 && GetLastError() != ERROR_INSUFFICIENT_BUFFER) // some code pages do not support WC_COMPOSITECHECK { res = WideCharToMultiByte(codepage, 0, src, srcLen, buf, bufSize, NULL, NULL); if (srcLen != -1 && res > 0) res++; } if (res > 0 && res <= bufSize) - buf[res - 1] = 0; // uspech, zakoncime string nulou + buf[res - 1] = 0; // success, null-terminate the string else { if (res > bufSize || res == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER) { SetLastError(ERROR_INSUFFICIENT_BUFFER); - buf[bufSize - 1] = 0; // maly buffer, vratime chybu, ale castecne prelozeny string nechame v bufferu + buf[bufSize - 1] = 0; // buffer too small: return an error, but leave the partially converted string in the buffer } else - buf[0] = 0; // jina chyba, zajistime prazdny buffer + buf[0] = 0; // other error: ensure the buffer is empty res = 0; } return res; @@ -85,7 +86,7 @@ char* ConvertAllocU2A(const WCHAR* src, int srcLen, BOOL compositeCheck, UINT co int len = WideCharToMultiByte(codepage, flags = (compositeCheck ? WC_COMPOSITECHECK : 0), src, srcLen, NULL, 0, NULL, NULL); if (srcLen != -1 && len > 0) len++; - if (compositeCheck && len == 0) // nektere codepage nepodporuji WC_COMPOSITECHECK + if (compositeCheck && len == 0) // some code pages do not support WC_COMPOSITECHECK { len = WideCharToMultiByte(codepage, flags = 0, src, srcLen, NULL, 0, NULL, NULL); if (srcLen != -1 && len > 0) @@ -104,7 +105,7 @@ char* ConvertAllocU2A(const WCHAR* src, int srcLen, BOOL compositeCheck, UINT co if (srcLen != -1 && res > 0) res++; if (res > 0 && res <= len) - txt[res - 1] = 0; // uspech, zakoncime string nulou + txt[res - 1] = 0; // success, null-terminate the string else { DWORD err = GetLastError(); @@ -142,16 +143,16 @@ int ConvertA2U(const char* src, int srcLen, WCHAR* buf, int bufSizeInChars, UINT if (srcLen != -1 && res > 0) res++; if (res > 0 && res <= bufSizeInChars) - buf[res - 1] = 0; // uspech, zakoncime string nulou + buf[res - 1] = 0; // success, null-terminate the string else { if (res > bufSizeInChars || res == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER) { SetLastError(ERROR_INSUFFICIENT_BUFFER); - buf[bufSizeInChars - 1] = 0; // maly buffer, vratime chybu, ale castecne prelozeny string nechame v bufferu + buf[bufSizeInChars - 1] = 0; // buffer too small: return an error, but leave the partially converted string in the buffer } else - buf[0] = 0; // jina chyba, zajistime prazdny buffer + buf[0] = 0; // other error: ensure the buffer is empty res = 0; } return res; @@ -200,7 +201,7 @@ WCHAR* ConvertAllocA2U(const char* src, int srcLen, UINT codepage) if (srcLen != -1 && res > 0) res++; if (res > 0 && res <= len) - txt[res - 1] = 0; // uspech, zakoncime string nulou + txt[res - 1] = 0; // success, null-terminate the string else { DWORD err = GetLastError(); @@ -290,7 +291,7 @@ LPTSTR FindString( // Return value: pointer to matched substring of text, or nul res = ConvertU2A(s1 = L"ahoj", 4, buf, 4, TRUE); res = ConvertU2A(s1 = L"ahoj", 4, buf, 3, TRUE); res = ConvertU2A(s1 = L"D:\\\x0061\x0308", -1, buf, 10, TRUE); // L"D:\\\x00e4" - res = ConvertU2A(s2 = L"D:\\á", -1, buf, 4); + res = ConvertU2A(s2 = L"D:\\\x00e1", -1, buf, 4); res = ConvertU2A(s1 = L"D:\\\xfb01-\x0061\x0308-\x00e4.txt", -1, buf, 10, TRUE); res = ConvertU2A(s2 = L"fi", -1, buf, 4); @@ -298,24 +299,24 @@ LPTSTR FindString( // Return value: pointer to matched substring of text, or nul WCHAR *f = FindString(LOCALE_USER_DEFAULT, 0, s1, -1, L"fi", -1, &fLen); f = FindString(LOCALE_USER_DEFAULT, 0, s1, -1, L"f", -1, &fLen); f = FindString(LOCALE_USER_DEFAULT, 0, s1, -1, L"\x00e4", -1, &fLen); - f = FindString(LOCALE_USER_DEFAULT, 0, s1, -1, L"a", -1, &fLen); // NEFUNGUJE !!! + f = FindString(LOCALE_USER_DEFAULT, 0, s1, -1, L"a", -1, &fLen); // DOES NOT WORK !!! WCHAR *ss = wcsstr(s1, L"\x00e4"); / * -procist X:\ZUMPA\!\unicode\ch05.pdf - jak vubec ma vypadat to hledani v Unicode ??? +Read X:\ZUMPA\!\unicode\ch05.pdf - what should Unicode searching actually look like? -Nekam odswapnout + casem proverit + odladit: +Move this elsewhere, then verify and debug it later: Some time ago I implemented a FindString function which in most cases takes only O(n) time (around 1.5*n CompareString calls most of which return immediately). In the end I didn't use it because I wasn't sure whether the relevant statement in the CompareString documentation can be relied on in a strict sense: "If the two strings are of different lengths, they are compared up to the length of the shortest one. If they are equal to that point, then the return value will indicate that the longer string is greater." More specifically, the function fails for TCHAR strings that are lexically -before any of their substrings (from the beginning). For example, when looking for "á" = {U+00E1}, the function will not -find the "a?" = {U+0061, U+0301} representation, if it sorts before "a" = {U+0061} in the specified locale. In other -words: The function assumes that CompareString(lcid, flags, string, m, string, n never returns CSTR_GREATER_THAN if +before any of their substrings (from the beginning). For example, when looking for the precomposed U+00E1 form, the function will not +find the U+0061 U+0301 representation if it sorts before U+0061 in the specified locale. In other +words: The function assumes that CompareString(lcid, flags, string, m, string, n) never returns CSTR_GREATER_THAN if m <= n and the strings agree in the first m TCHARs. -Mozna by se hodilo pouzit "StringInfo Class", ktery umi rozebrat retezec -na zobrazitelne znaky (sekvence WCHARu odpovidajici jednomu zobrazenemu znaku). +It might be useful to use the "StringInfo Class", which can split a string +into display characters (a sequence of WCHARs corresponding to one displayed character). * / @@ -329,7 +330,7 @@ na zobrazitelne znaky (sekvence WCHARu odpovidajici jednomu zobrazenemu znaku). res = CompareString(LOCALE_USER_DEFAULT, 0, s1, -1, s2, -1); - res = ConvertA2U("Âëŕäčěčđ", -1, wbuf, 10, 1251); + res = ConvertA2U("sample CP1251 text", -1, wbuf, 10, 1251); res = ConvertA2U("ahoj", 0, wbuf, 10); res = ConvertA2U("ahoj", -1, wbuf, 5); res = ConvertA2U("ahoj", -1, wbuf, 4); @@ -351,10 +352,10 @@ na zobrazitelne znaky (sekvence WCHARu odpovidajici jednomu zobrazenemu znaku). res = ConvertU2A(L"D:\\\xfb01-\x0061\x0308-\x00e4.txt", -1, TRUE); WCHAR *wres; - wres = ConvertA2U("Âëŕäčěčđ", -1, 1251); + wres = ConvertA2U("sample CP1251 text", -1, 1251); wres = ConvertA2U("", -1); - wres = ConvertA2U("ahoj čěšťíňká", 0); - wres = ConvertA2U("ahoj čěšťíňká", 2); - wres = ConvertA2U("ahoj čěšťíňká", -1); + wres = ConvertA2U("hello with accents", 0); + wres = ConvertA2U("hello with accents", 2); + wres = ConvertA2U("hello with accents", -1); } */ diff --git a/src/common/strutils.h b/src/common/strutils.h index c983d798b..d2b2b938c 100644 --- a/src/common/strutils.h +++ b/src/common/strutils.h @@ -1,54 +1,55 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once -// makro SAFE_ALLOC odstranuje kod, ve kterem se testuje, jestli se povedla alokace pameti (viz allochan.*) +// The SAFE_ALLOC macro removes the code that checks whether memory allocation succeeded (see allochan.*) -// prevod Unicodoveho stringu (UTF-16) na ANSI multibytovy string; 'src' je Unicodovy string; -// 'srcLen' je delka Unicodoveho stringu (bez zakoncujici nuly; pri zadani -1 se delka urci -// podle zakoncujici nuly); 'bufSize' (musi byt vetsi nez 0) je velikost ciloveho bufferu -// 'buf' pro ANSI string; je-li 'compositeCheck' TRUE, pouziva flag WC_COMPOSITECHECK -// (viz MSDN), nesmi se pouzit pro jmena souboru (NTFS rozlisuje jmena zapsana jako -// precomposed a composite, aneb neprovadi normalizaci jmen); 'codepage' je kodova stranka -// ANSI stringu; vraci pocet znaku zapsanych do 'buf' (vcetne zakoncujici nuly); pri chybe -// vraci nulu (detaily viz GetLastError()); vzdy zajisti nulou zakonceny 'buf' (i pri chybe); -// je-li 'buf' maly, vraci funkce nulu, ale v 'buf' je prevedena aspon cast stringu +// Converts a Unicode (UTF-16) string to an ANSI multibyte string; 'src' is the Unicode string; +// 'srcLen' is the length of the Unicode string (excluding the terminating null; if -1 is passed, +// the length is determined from the terminating null); 'bufSize' (must be greater than 0) is the size of the destination buffer +// 'buf' for the ANSI string; if 'compositeCheck' is TRUE, the WC_COMPOSITECHECK flag is used +// (see MSDN); it must not be used for file names (NTFS distinguishes between names written as +// precomposed and composite, i.e. it does not normalize names); 'codepage' is the code page of the +// ANSI string; returns the number of characters written to 'buf' (including the terminating null); on error +// returns 0 (see GetLastError()); always ensures 'buf' is null-terminated (even on error); +// if 'buf' is too small, the function returns 0, but at least part of the string is converted into 'buf' int ConvertU2A(const WCHAR* src, int srcLen, char* buf, int bufSize, BOOL compositeCheck = FALSE, UINT codepage = CP_ACP); -// prevod Unicodoveho stringu (UTF-16) na alokovany ANSI multibytovy string (volajici je -// odpovedny za dealokaci stringu); 'src' je Unicodovy string; 'srcLen' je delka Unicodoveho -// stringu (bez zakoncujici nuly; pri zadani -1 se delka urci podle zakoncujici nuly); -// je-li 'compositeCheck' TRUE, pouziva flag WC_COMPOSITECHECK (viz MSDN), nesmi se pouzit -// pro jmena souboru (NTFS rozlisuje jmena zapsana jako precomposed a composite, aneb -// neprovadi normalizaci jmen); 'codepage' je kodova stranka ANSI stringu; vraci alokovany -// ANSI string; pri chybe vraci NULL (detaily viz GetLastError()) +// Converts a Unicode (UTF-16) string to an allocated ANSI multibyte string (the caller is +// responsible for freeing the string); 'src' is the Unicode string; 'srcLen' is the length of the Unicode +// string (excluding the terminating null; if -1 is passed, the length is determined from the terminating null); +// if 'compositeCheck' is TRUE, the WC_COMPOSITECHECK flag is used (see MSDN); it must not be used +// for file names (NTFS distinguishes between names written as precomposed and composite, i.e. +// it does not normalize names); 'codepage' is the code page of the ANSI string; returns the allocated +// ANSI string; on error returns NULL (see GetLastError()) char* ConvertAllocU2A(const WCHAR* src, int srcLen, BOOL compositeCheck = FALSE, UINT codepage = CP_ACP); -// prevod ANSI multibytoveho stringu na Unicodovy string (UTF-16); 'src' je ANSI string; -// 'srcLen' je delka ANSI stringu (bez zakoncujici nuly; pri zadani -1 se delka urci -// podle zakoncujici nuly); 'bufSize' (musi byt vetsi nez 0) je velikost ciloveho bufferu -// 'buf' pro Unicodovy string; 'codepage' je kodova stranka ANSI stringu; -// vraci pocet znaku zapsanych do 'buf' (vcetne zakoncujici nuly); pri chybe vraci nulu -// (detaily viz GetLastError()); vzdy zajisti nulou zakonceny 'buf' (i pri chybe); -// je-li 'buf' maly, vraci funkce nulu, ale v 'buf' je prevedena aspon cast stringu +// Converts an ANSI multibyte string to a Unicode (UTF-16) string; 'src' is the ANSI string; +// 'srcLen' is the length of the ANSI string (excluding the terminating null; if -1 is passed, +// the length is determined from the terminating null); 'bufSize' (must be greater than 0) is the size of the destination buffer +// 'buf' for the Unicode string; 'codepage' is the code page of the ANSI string; +// returns the number of characters written to 'buf' (including the terminating null); on error returns 0 +// (see GetLastError()); always ensures 'buf' is null-terminated (even on error); +// if 'buf' is too small, the function returns 0, but at least part of the string is converted into 'buf' int ConvertA2U(const char* src, int srcLen, WCHAR* buf, int bufSizeInChars, UINT codepage = CP_ACP); -// prevod ANSI multibytoveho stringu na alokovany (volajici je odpovedny za dealokaci -// stringu) Unicodovy string (UTF-16); 'src' je ANSI string; 'srcLen' je delka ANSI -// stringu (bez zakoncujici nuly; pri zadani -1 se delka urci podle zakoncujici nuly); -// 'codepage' je kodova stranka ANSI stringu; vraci alokovany Unicodovy string; pri -// chybe vraci NULL (detaily viz GetLastError()) +// Converts an ANSI multibyte string to an allocated Unicode (UTF-16) string (the caller is responsible for freeing +// the string); 'src' is the ANSI string; 'srcLen' is the length of the ANSI +// string (excluding the terminating null; if -1 is passed, the length is determined from the terminating null); +// 'codepage' is the code page of the ANSI string; returns the allocated Unicode string; on +// error returns NULL (see GetLastError()) WCHAR* ConvertAllocA2U(const char* src, int srcLen, UINT codepage = CP_ACP); -// nakopiruje string 'txt' do nove naalokovaneho stringu, NULL = malo pameti (hrozi jen pokud -// se nepouziva allochan.*) nebo 'txt'==NULL +// Copies 'txt' into a newly allocated string; returns NULL on out of memory (only possible when +// allochan.* is not used) or if 'txt'==NULL WCHAR* DupStr(const WCHAR* txt); -// drzi ukazatel na alokovanou pamet, postara se o jeji uvolneni pri prepisu jinym ukazatelem na -// alokovanou pamet a pri sve destrukci +// Holds a pointer to allocated memory and frees it when overwritten by another pointer to allocated memory +// and when destroyed template class CAllocP { @@ -79,6 +80,6 @@ class CAllocP } }; -// drzi alokovany string, postara se o uvolneni pri prepisu jinym stringem (tez alokovanym) -// a pri sve destrukci +// Holds an allocated string and frees it when overwritten by another allocated string +// and when destroyed typedef CAllocP CStrP; diff --git a/src/common/trace.cpp b/src/common/trace.cpp index c4aa31749..a2184f089 100644 --- a/src/common/trace.cpp +++ b/src/common/trace.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -19,15 +20,15 @@ // boundaries so we can find the real functions // that we need to call for initialization. -#pragma warning(disable : 4075) // chceme definovat poradi inicializace modulu +#pragma warning(disable : 4075) // define the module initialization order typedef void(__cdecl* _PVFV)(void); #pragma section(".i_trc$a", read) -__declspec(allocate(".i_trc$a")) const _PVFV i_trace = (_PVFV)1; // na zacatek sekce .i_trc si dame promennou i_trace +__declspec(allocate(".i_trc$a")) const _PVFV i_trace = (_PVFV)1; // put the i_trace variable at the start of the .i_trc section #pragma section(".i_trc$z", read) -__declspec(allocate(".i_trc$z")) const _PVFV i_trace_end = (_PVFV)1; // a na konec sekce .i_trc si dame promennou i_trace_end +__declspec(allocate(".i_trc$z")) const _PVFV i_trace_end = (_PVFV)1; // put the i_trace_end variable at the end of the .i_trc section void Initialize__Trace() { @@ -161,25 +162,25 @@ BOOL C__TraceThreadCache::GetIndex(DWORD tid, int& index) { m = (l + r) / 2; DWORD hw = Data[m].TID; - if (hw == tid) // nalezeno + if (hw == tid) // found { index = m; return TRUE; } else if (hw > tid) { - if (l == r || l > m - 1) // nenalezeno + if (l == r || l > m - 1) // not found { - index = m; // mel by byt na teto pozici + index = m; // should be at this position return FALSE; } r = m - 1; } else { - if (l == r) // nenalezeno + if (l == r) // not found { - index = m + 1; // mel by byt az za touto pozici + index = m + 1; // should be after this position return FALSE; } l = m + 1; @@ -193,18 +194,18 @@ BOOL C__TraceThreadCache::Add(HANDLE handle, DWORD tid) BOOL found = GetIndex(tid, index); if (!found) { - if (Available == Count) // je plno, vyhazime mrtvy thready + if (Available == Count) // full, remove dead threads { DWORD code; for (int i = Count - 1; i >= 0; i--) { if (!GetExitCodeThread(Data[i].Handle, &code) || code != STILL_ACTIVE) { - DWORD id = Data[i].TID; // aktualizace cache: - if (CacheUID[__TraceCacheGetIndex(id)] != -1 && // platny zaznam - CacheTID[__TraceCacheGetIndex(id)] == id) // shodny TID + DWORD id = Data[i].TID; // cache update: + if (CacheUID[__TraceCacheGetIndex(id)] != -1 && // valid entry + CacheTID[__TraceCacheGetIndex(id)] == id) // matching TID { - CacheUID[__TraceCacheGetIndex(id)] = -1; // zneplatneni + CacheUID[__TraceCacheGetIndex(id)] = -1; // invalidate } CloseHandle(Data[i].Handle); @@ -219,7 +220,7 @@ BOOL C__TraceThreadCache::Add(HANDLE handle, DWORD tid) if (Available == Count && !EnlargeArray()) return FALSE; - Move(1, index, Count - index); // vlozime novy zaznam + Move(1, index, Count - index); // insert a new entry Data[index].Handle = handle; Data[index].TID = tid; Data[index].UID = UniqueThreadID; @@ -231,7 +232,7 @@ BOOL C__TraceThreadCache::Add(HANDLE handle, DWORD tid) Data[index].Handle = handle; Data[index].UID = UniqueThreadID; } - // aktualizace cache + // cache update CacheTID[__TraceCacheGetIndex(tid)] = tid; CacheUID[__TraceCacheGetIndex(tid)] = UniqueThreadID++; @@ -241,10 +242,10 @@ BOOL C__TraceThreadCache::Add(HANDLE handle, DWORD tid) DWORD C__TraceThreadCache::GetUniqueThreadId(DWORD tid) { - if (CacheUID[__TraceCacheGetIndex(tid)] != -1 && // je-li platny zaznam - CacheTID[__TraceCacheGetIndex(tid)] == tid) // a je-li shodny s tid + if (CacheUID[__TraceCacheGetIndex(tid)] != -1 && // valid entry + CacheTID[__TraceCacheGetIndex(tid)] == tid) // and the TID matches { - return CacheUID[__TraceCacheGetIndex(tid)]; // uid je v cache + return CacheUID[__TraceCacheGetIndex(tid)]; // UID is in the cache } int index; @@ -255,7 +256,7 @@ C__TraceThreadCache::GetUniqueThreadId(DWORD tid) return Data[index].UID; } else - return -1; // nenalezeno -> to by se nemelo stat + return -1; // not found -> this should not happen } //***************************************************************************** @@ -371,20 +372,20 @@ CWStr::CWStr(const char* s) C__Trace::C__Trace() : TraceStrStream(&TraceStringBuf), TraceStrStreamW(&TraceStringBufW) { #ifdef _DEBUG - // nove streamy pouzivaji interne locales, ktere maji implementovany - // jednotlive "facets" pomoci lazy creation - jsou alokovany na heapu - // kdyz jsou potreba, tedy kdyz nekdo posle do streamu neco, co ma - // formatovani zavisle na lokalich pravidlech, treba cislo, datum, - // nebo boolean. Tyto "facets" jsou pak dealokovany pri exitu - // programu s prioritou compiler, tzn. po nasi kontrole memory leaku. - // Takze pokud nekdo pouzije stream k vypisu cehokoli lokalizovatelneho, - // nas debug heap zacne hlasit memory leaky, i kdyz zadne nejsou. Abychom - // tomu predesli, donutime locales vytvorit vsechny "facets" ted, dokud - // jeste nehlidame heap. - // Zatim pouzivame pouze vystupni stream a pouze se stringy (bez konverze) - // a cisly. Takze poslat cislo do stringstreamu by melo stacit. Pokud - // v budoucnu zacneme pouzivat streamy vic a debug heap zacne hlasit - // leaky, budeme zde muset pridat vic vstupu/vystupu. + // new streams use internal locales whose individual "facets" are implemented + // with lazy creation - they are allocated on the heap + // when needed, that is, when something is sent to the stream whose formatting + // depends on locale rules, such as a number, date, + // or boolean. These "facets" are then deallocated on + // program exit with compiler priority, i.e. after our memory-leak check. + // So if someone uses a stream to print anything localizable, + // our debug heap starts reporting memory leaks even though there are none. To prevent + // that, we force the locales to create all "facets" now, while + // we are not watching the heap yet. + // For now we use only output streams, and only with strings (without conversion) + // and numbers. So sending a number to stringstream should be enough. If + // we start using streams more in the future and the debug heap starts reporting + // leaks, we will have to add more input/output here. std::stringstream s; s << 1; std::wstringstream s2; @@ -446,7 +447,7 @@ BOOL C__Trace::Connect(BOOL onUserRequest) lstrcpynW(s, L"altap_traces", int(end - s)); s += wcslen(s); - if ((s - tmpDir) + 15 < MAX_PATH) // dost mista pro pripojeni "_2000000000.log" + if ((s - tmpDir) + 15 < MAX_PATH) // enough room to append "_2000000000.log" { int num = 1; while (1) @@ -462,11 +463,11 @@ BOOL C__Trace::Connect(BOOL onUserRequest) } DWORD err = GetLastError(); if (err != ERROR_FILE_EXISTS && err != ERROR_ALREADY_EXISTS) - break; // neocekavana chyba (a neni ji kam vypsat) + break; // unexpected error (and nowhere to print it) } if (HTraceFile == INVALID_HANDLE_VALUE) HTraceFile = NULL; - else // zapis headeru do souboru (identifikace sloupcu) + else // write the file header (column labels) { DWORD wr; const WCHAR* fileHeader = L"\xFEFF" /* BOM */ L"Type\tTID\t" @@ -482,20 +483,20 @@ BOOL C__Trace::Connect(BOOL onUserRequest) } #endif // TRACE_TO_FILE - if (HWritePipe != NULL) // test spojeni se serverem, jestli je down, HWritePipe se zavre a nasledne zkusime reconnect + if (HWritePipe != NULL) // test the server connection; if it is down, HWritePipe is closed and we then try to reconnect TRACE_I("Connect request received when already connected to Trace Server."); BOOL ret = FALSE; if (HWritePipe != NULL) - ret = TRUE; // pokud je jiz spojeni navazano + ret = TRUE; // if the connection is already established else { - // pokusim se otevrit Mutex pro pristup ke sdilene pameti + // try to open the mutex for access to the shared memory HANDLE hOpenConnectionMutex; hOpenConnectionMutex = OpenMutex(/*MUTEX_ALL_ACCESS*/ SYNCHRONIZE, FALSE, __OPEN_CONNECTION_MUTEX); - if (hOpenConnectionMutex != NULL) // server nalezen + if (hOpenConnectionMutex != NULL) // server found { - // prevezmu ConnectionMutex + // acquire ConnectionMutex DWORD waitRet; while (1) { @@ -504,16 +505,16 @@ BOOL C__Trace::Connect(BOOL onUserRequest) if (waitRet != WAIT_ABANDONED) break; } - if (waitRet == WAIT_OBJECT_0) // podaril se prevzit + if (waitRet == WAIT_OBJECT_0) // acquired successfully { - // otevru FileMapping + // open FileMapping HANDLE hFileMapping; hFileMapping = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, __FILE_MAPPING_NAME); if (hFileMapping != NULL) { - // namapuju spolecnou pamet + // map the shared memory char* mapAddress; - mapAddress = (char*)MapViewOfFile(hFileMapping, FILE_MAP_ALL_ACCESS, // FIXME_X64 nepredavame x86/x64 nekompatibilni data? + mapAddress = (char*)MapViewOfFile(hFileMapping, FILE_MAP_ALL_ACCESS, // FIXME_X64 are we passing x86/x64-incompatible data? 0, 0, __SIZEOF_CLIENTSERVERINITDATA); if (mapAddress != NULL) { @@ -523,7 +524,7 @@ BOOL C__Trace::Connect(BOOL onUserRequest) { HANDLE HReadPipe; - // vytvorim anonymous pipe + // create an anonymous pipe SECURITY_ATTRIBUTES sa; char secDesc[SECURITY_DESCRIPTOR_MIN_LENGTH]; sa.nLength = sizeof(sa); @@ -534,104 +535,104 @@ BOOL C__Trace::Connect(BOOL onUserRequest) SetSecurityDescriptorDacl(sa.lpSecurityDescriptor, TRUE, 0, FALSE); if (CreatePipe(&HReadPipe, &HWritePipe, &sa, __PIPE_SIZE * 1024)) { - // zapisu do sdilene pameti handle pro cteni z pipy + // write the pipe read handle to shared memory int expectedServerVer = TRACE_CLIENT_VERSION; - *(int*)&mapAddress[0] = expectedServerVer - 1; // Version (zkousime nejdrive starsi zpusob connectu) - *(DWORD*)&mapAddress[4] = GetCurrentProcessId(); // ClientOrServerProcessId (tady jde o PID klienta) - *(DWORD*)&mapAddress[8] = (DWORD)(DWORD_PTR)HReadPipe; // HReadOrWritePipe (tady jde o HReadPipe) + *(int*)&mapAddress[0] = expectedServerVer - 1; // Version (we try the older connect method first) + *(DWORD*)&mapAddress[4] = GetCurrentProcessId(); // ClientOrServerProcessId (here it is the client PID) + *(DWORD*)&mapAddress[8] = (DWORD)(DWORD_PTR)HReadPipe; // HReadOrWritePipe (here it is HReadPipe) *(DWORD*)&mapAddress[12] = (DWORD)(DWORD_PTR)HPipeSemaphore; // HPipeSemaphore - // otevru hReadyEvent + // open hReadyEvent HANDLE hReadyEvent; hReadyEvent = OpenEvent(EVENT_ALL_ACCESS, TRUE, __CONNECT_DATA_READY_EVENT_NAME); - // otevru hAcceptedEvent + // open hAcceptedEvent HANDLE hAcceptedEvent; hAcceptedEvent = OpenEvent(EVENT_ALL_ACCESS, TRUE, __CONNECT_DATA_ACCEPTED_EVENT_NAME); if (hReadyEvent != NULL && hAcceptedEvent != NULL) { - ResetEvent(hAcceptedEvent); // chci jen cerstvou odpoved serveru + ResetEvent(hAcceptedEvent); // wait only for a fresh response from the server while (1) { - SetEvent(hReadyEvent); // reknu serveru, ze jsem pripravil data + SetEvent(hReadyEvent); // tell the server the data is ready - // pockam, az server data zpracuje + // wait for the server to process the data waitRet = WaitForSingleObject(hAcceptedEvent, __COMMUNICATION_WAIT_TIMEOUT); if (waitRet == WAIT_OBJECT_0) { - // hlaska vypisovana na starem neunikodovem Trace Serveru (musi byt ANSI) + // message shown on the old non-Unicode Trace Server (must be ANSI) const char* oldTraceServerA = "Disconnecting: this is not Unicode version of Trace Server."; - // podivam se na vysledek ze serveru + // check the result from the server if (*((BOOL*)mapAddress) == TRUE) { - if (expectedServerVer == TRACE_CLIENT_VERSION) // hura, povedlo se pripojit na novy Trace Server! + if (expectedServerVer == TRACE_CLIENT_VERSION) // success, connected to the new Trace Server! { #ifdef TRACE_IGNORE_AUTOCLEAR - ret = SendIgnoreAutoClear(TRUE); // ignorovat, pri chybe provedeme disconnect + ret = SendIgnoreAutoClear(TRUE); // ignore; disconnect on error #else // TRACE_IGNORE_AUTOCLEAR - ret = SendIgnoreAutoClear(FALSE); // neignorovat, pri chybe provedeme disconnect + ret = SendIgnoreAutoClear(FALSE); // do not ignore; disconnect on error #endif // TRACE_IGNORE_AUTOCLEAR } else TRACE_E(oldTraceServerA); } - else // nepovedlo se: zkusime pipe vytvorit na strane serveru + else // failed; try creating the pipe on the server side { - // zapisu do sdilene pameti novou verzi, tim pozadam server o poslani handlu pro zapis do pipy + // write the new version to shared memory to ask the server to send the pipe write handle *(int*)&mapAddress[0] = expectedServerVer; // Version - SetEvent(hReadyEvent); // reknu serveru, ze jsem pripravil data + SetEvent(hReadyEvent); // tell the server the data is ready - // pockam, az server data zpracuje + // wait for the server to process the data waitRet = WaitForSingleObject(hAcceptedEvent, __COMMUNICATION_WAIT_TIMEOUT); - if (waitRet == WAIT_OBJECT_0 && *((BOOL*)mapAddress) == TRUE) // podivam se na vysledek ze serveru + if (waitRet == WAIT_OBJECT_0 && *((BOOL*)mapAddress) == TRUE) // check the result from the server { HANDLE hWritePipeFromSrv = NULL; HANDLE hPipeSemaphoreFromSrv = NULL; - // ziskani handlu server procesu + // get the server process handle HANDLE hServerProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, - *(DWORD*)&mapAddress[4] /* ClientOrServerProcessId (tady jde o PID serveru) */); - // ziskani handlu pipy a semaforu + *(DWORD*)&mapAddress[4] /* ClientOrServerProcessId (here it is the server PID) */); + // get the pipe and semaphore handles if (hServerProcess != NULL && - DuplicateHandle(hServerProcess, (HANDLE)(DWORD_PTR)(*(DWORD*)&mapAddress[8]) /* HReadOrWritePipe (tady jde o HWritePipe) */, // server - GetCurrentProcess(), &hWritePipeFromSrv, // klient + DuplicateHandle(hServerProcess, (HANDLE)(DWORD_PTR)(*(DWORD*)&mapAddress[8]) /* HReadOrWritePipe (here it is HWritePipe) */, // client + GetCurrentProcess(), &hWritePipeFromSrv, // client GENERIC_WRITE, FALSE, 0) && DuplicateHandle(hServerProcess, (HANDLE)(DWORD_PTR)(*(DWORD*)&mapAddress[12]) /* HPipeSemaphore */, // server - GetCurrentProcess(), &hPipeSemaphoreFromSrv, // klient + GetCurrentProcess(), &hPipeSemaphoreFromSrv, // client 0, FALSE, DUPLICATE_SAME_ACCESS)) { - *((int*)mapAddress) = 3; // zapis vysledku -> 3 = povedlo se, handly mame - *(DWORD*)&mapAddress[4] = GetCurrentProcessId(); // ClientOrServerProcessId (tady jde o PID klienta) + *((int*)mapAddress) = 3; // write result -> 3 = success, we have the handles + *(DWORD*)&mapAddress[4] = GetCurrentProcessId(); // ClientOrServerProcessId (client PID here) } else { - *((BOOL*)mapAddress) = FALSE; // zapis vysledku -> nepovedlo se + *((BOOL*)mapAddress) = FALSE; // write result -> failure } if (hServerProcess != NULL) CloseHandle(hServerProcess); - SetEvent(hReadyEvent); // reknu serveru, ze jsem data precetl a zapsal vysledek + SetEvent(hReadyEvent); // tell the server I read the data and wrote the result - // pri uspechu: pockam, az server nastartuje thread cteni dat z pipy a posle vysledek - // pri neuspechu: dame serveru vedet, ze se to nepovedlo, vrati nam opet neuspech + // on success: wait until the server starts the thread that reads data from the pipe and sends the result + // on failure: tell the server it failed; it will return failure again waitRet = WaitForSingleObject(hAcceptedEvent, __COMMUNICATION_WAIT_TIMEOUT); - if (waitRet == WAIT_OBJECT_0 && // podivam se na vysledek ze serveru - *((int*)mapAddress) == 2 /* 2 = uspesne nastartovany cteci thread v serveru */) + if (waitRet == WAIT_OBJECT_0 && // check the result from the server + *((int*)mapAddress) == 2 /* 2 = the reader thread was started successfully in the server */) { CloseHandle(HPipeSemaphore); - HPipeSemaphore = hPipeSemaphoreFromSrv; // pouzijeme semafor ze serveru (ten klientsky zavreme) + HPipeSemaphore = hPipeSemaphoreFromSrv; // use the semaphore from the server (close the client one) CloseHandle(HWritePipe); - HWritePipe = hWritePipeFromSrv; // pouzijeme pipu ze serveru (tu klientskou zavreme) + HWritePipe = hWritePipeFromSrv; // use the pipe from the server (close the client one) - if (expectedServerVer == TRACE_CLIENT_VERSION) // hura, povedlo se pripojit na novy Trace Server! + if (expectedServerVer == TRACE_CLIENT_VERSION) // success, connected to the new Trace Server { #ifdef TRACE_IGNORE_AUTOCLEAR - ret = SendIgnoreAutoClear(TRUE); // ignorovat, pri chybe provedeme disconnect + ret = SendIgnoreAutoClear(TRUE); // ignore; disconnect on error #else // TRACE_IGNORE_AUTOCLEAR - ret = SendIgnoreAutoClear(FALSE); // neignorovat, pri chybe provedeme disconnect + ret = SendIgnoreAutoClear(FALSE); // do not ignore; disconnect on error #endif // TRACE_IGNORE_AUTOCLEAR } else @@ -645,12 +646,12 @@ BOOL C__Trace::Connect(BOOL onUserRequest) CloseHandle(hPipeSemaphoreFromSrv); } } - else // connect se nepovedl ani jednim zpusobem (asi stary Trace Server) + else // connect failed both ways (probably an old Trace Server) { - if (expectedServerVer == TRACE_CLIENT_VERSION) // zkouseli jsme novou verzi serveru + if (expectedServerVer == TRACE_CLIENT_VERSION) // we tried the new server version { - expectedServerVer = TRACE_CLIENT_VERSION - 2; // ted zkusime starsi verzi serveru - // zapisu do sdilene pameti verzi, kterou zvlada stara verze serveru + expectedServerVer = TRACE_CLIENT_VERSION - 2; // now try the older server version + // write the version supported by the old server to shared memory *(int*)&mapAddress[0] = expectedServerVer - 1; // Version continue; } @@ -681,7 +682,7 @@ BOOL C__Trace::Connect(BOOL onUserRequest) } CloseHandle(hFileMapping); } - ReleaseMutex(hOpenConnectionMutex); // muzou se connectit jini clienti + ReleaseMutex(hOpenConnectionMutex); // other clients can connect now } CloseHandle(hOpenConnectionMutex); } @@ -752,12 +753,12 @@ BOOL C__Trace::WritePipe(LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite) BytesAllocatedForWriteToPipe += 1024; else { - if (res == WAIT_TIMEOUT) // timeout, zkontrolujem, jestli pipe na server jeste zije + if (res == WAIT_TIMEOUT) // timeout, check whether the server pipe is still alive { if (!WriteFile(HWritePipe, lpBuffer, 0, &numberOfBytesWritten, NULL)) return FALSE; } - else // jina chyba, radsi koncime, at z toho neni nekonecny cyklus + else // another error, stop to avoid an infinite loop return FALSE; } } @@ -811,7 +812,7 @@ BOOL C__Trace::SendIgnoreAutoClear(BOOL ignore) { char data[__SIZEOF_PIPEDATAHEADER]; *(int*)&data[0] = __mtIgnoreAutoClear; // Type - *(DWORD*)&data[4] = ignore ? 1 : 0; // ThreadID: 0 = neignorovat, 1 = ignorovat auto-clear na Trace Serveru + *(DWORD*)&data[4] = ignore ? 1 : 0; // ThreadID: 0 = do not ignore, 1 = ignore Trace Server auto-clear return WritePipe(data, __SIZEOF_PIPEDATAHEADER); } @@ -838,7 +839,7 @@ void C__Trace::SetThreadName(const char* name) EnterCriticalSection(&CriticalSection); DWORD storedLastError = GetLastError(); #ifdef MULTITHREADED_TRACE_ENABLE - if (ThreadCache.GetUniqueThreadId(GetCurrentThreadId()) != -1) // jen s pridelenym UID, jinak by vsechny "unknown" byly najednou pojmenovany timto jmenem + if (ThreadCache.GetUniqueThreadId(GetCurrentThreadId()) != -1) // only with an assigned UID, otherwise all "unknown" threads would suddenly get this name SendSetNameMessageToServer(name, NULL, __mtSetThreadName); #else // MULTITHREADED_TRACE_ENABLE SendSetNameMessageToServer(name, NULL, __mtSetThreadName); @@ -852,7 +853,7 @@ void C__Trace::SetThreadNameW(const WCHAR* name) EnterCriticalSection(&CriticalSection); DWORD storedLastError = GetLastError(); #ifdef MULTITHREADED_TRACE_ENABLE - if (ThreadCache.GetUniqueThreadId(GetCurrentThreadId()) != -1) // jen s pridelenym UID, jinak by vsechny "unknown" byly najednou pojmenovany timto jmenem + if (ThreadCache.GetUniqueThreadId(GetCurrentThreadId()) != -1) // only with an assigned UID, otherwise all "unknown" threads would suddenly get this name SendSetNameMessageToServer(NULL, name, __mtSetThreadNameW); #else // MULTITHREADED_TRACE_ENABLE SendSetNameMessageToServer(NULL, name, __mtSetThreadNameW); @@ -881,8 +882,8 @@ C__Trace::SetInfoW(const WCHAR* file, int line) struct C__TraceMsgBoxThreadData { - char* Msg; // alokovany text hlasky - const char* File; // jen odkaz na staticky string + char* Msg; // allocated message text + const char* File; // only a pointer to a static string int Line; }; @@ -907,8 +908,8 @@ DWORD WINAPI __TraceMsgBoxThread(void* param) struct C__TraceMsgBoxThreadDataW { - WCHAR* Msg; // alokovany text hlasky - const WCHAR* File; // jen odkaz na staticky string + WCHAR* Msg; // allocated message text + const WCHAR* File; // only a pointer to a static string int Line; }; @@ -945,7 +946,7 @@ C__Trace& C__Trace::SendMessageToServer(C__MessageType type, BOOL crash) { BOOL unicode = type == __mtInformationW || type == __mtErrorW; - // flushnuti do bufferu + // flush into the buffer if (unicode) TraceStrStreamW.flush(); else @@ -966,9 +967,9 @@ C__Trace::SendMessageToServer(C__MessageType type, BOOL crash) ::QueryPerformanceCounter(&perfCounter); static LONGLONG lastPC = 0; - if (lastPC != 0 && lastPC > perfCounter.QuadPart) // counter musi stale rust, snizeni je chyba (na vicejadrovych procesorech se tahle chyba objevuje, resenim je nastaveni affinity na jedine jadro pro ladeny proces v Task Manageru) + if (lastPC != 0 && lastPC > perfCounter.QuadPart) // the counter must keep increasing; a decrease is a bug (this happens on multicore processors; the workaround is to set the debugged process affinity to a single core in Task Manager) { - perfCounter.QuadPart = lastPC + 1; // umele zvysime hodnotu counteru na posledni hodnotu plus jedna (jen aby se nesnizil a nedoslo k uplne spatnemu zarazeni v Trace Serveru) + perfCounter.QuadPart = lastPC + 1; // artificially increase the counter to the last value plus one (just to keep it from decreasing and getting completely misordered in Trace Server) pcWarningLen = unicode ? (int)wcslen(pcWarningW) : (int)strlen(pcWarning); addToMessageSize = pcWarningLen; writePCWarning = TRUE; @@ -985,12 +986,12 @@ C__Trace::SendMessageToServer(C__MessageType type, BOOL crash) { DWORD wr; WCHAR bufW[5000]; - swprintf_s(bufW, unicode ? L"%s\t%d\t" // jmeno souboru ve FileW (unicode) + swprintf_s(bufW, unicode ? L"%s\t%d\t" // file name in FileW (Unicode) #ifdef MULTITHREADED_TRACE_ENABLE L"%d\t" #endif // MULTITHREADED_TRACE_ENABLE L"%d.%d.%d\t%d:%02d:%02d.%03d\t%.3lf\t%s\t%d\t" - : L"%s\t%d\t" // jmeno souboru ve File (ANSI) + : L"%s\t%d\t" // file name in File (ANSI) #ifdef MULTITHREADED_TRACE_ENABLE L"%d\t" #endif // MULTITHREADED_TRACE_ENABLE @@ -1018,15 +1019,15 @@ C__Trace::SendMessageToServer(C__MessageType type, BOOL crash) } } WriteFile(HTraceFile, L"\r\n", sizeof(WCHAR) * 2, &wr, NULL); - FlushFileBuffers(HTraceFile); // flushneme data na disk + FlushFileBuffers(HTraceFile); // flush the data to disk #ifdef __TRACESERVER - // pro ladeni Trace Serveru: TRACE hlasky jdou jen do souboru, kdyz prijde TRACE_E, upozornime msgboxem + // for Trace Server debugging: TRACE messages go only to the file; when TRACE_E arrives, notify with a message box if (!crash && (type == __mtError || type == __mtErrorW)) { swprintf_s(bufW, L"Error message from Trace Server has been written to file with traces:\n%s", TraceFileName); - // vypiseme hlasku v jinem threadu, aby nepumpovala zpravy aktualniho threadu + // show the message in another thread so the current thread does not pump messages DWORD id; HANDLE msgBoxThread = CreateThread(NULL, 0, __TraceMsgBoxThreadErrInTS, bufW, 0, &id); if (msgBoxThread != NULL) @@ -1061,30 +1062,30 @@ C__Trace::SendMessageToServer(C__MessageType type, BOOL crash) if (!WritePipe(data, __SIZEOF_PIPEDATAHEADER) || !WritePipe(unicode ? (void*)FileW : (void*)File, (DWORD)((unicode ? sizeof(WCHAR) : 1) * fileSize)) || writePCWarning && !WritePipe(unicode ? (void*)pcWarningW : (void*)pcWarning, - (unicode ? sizeof(WCHAR) : 1) * pcWarningLen) || // na zacatek zpravy vypisu chybu PC, pri ladeni je to dost zasadni vec (zpravy jsou mimo realne poradi) + (unicode ? sizeof(WCHAR) : 1) * pcWarningLen) || // put the PC error at the start of the message; this is quite important when debugging (messages are out of actual order) !WritePipe(unicode ? (void*)TraceStringBufW.c_str() : (void*)TraceStringBuf.c_str(), (unicode ? sizeof(WCHAR) : 1) * textSize)) { CloseWritePipeAndSemaphore(); } } - // jen je-li crash==TRUE: - // vyrobime kopii dat, start threadu pro msgbox totiz muze vyvolat dalsi TRACE - // hlasky (napr. v DllMain reakce na DLL_THREAD_ATTACH), pokud bysme neopustili - // CriticalSection, nastal by deadlock; - // v DllMain se nesmi pouzivat TRACE_C, jinak dojde k deadlocku: - // - pokud se da do DLL_THREAD_ATTACH: chce si otevrit novy thread pro msgbox - // a to je z DllMainu blokovane - // - pokud se da do DLL_THREAD_DETACH: pri cekani na zavreni threadu s msgboxem - // predesleho TRACE_C zachytime TRACE_C z DLL_THREAD_DETACH a nechame ho - // cekat v nekonecnem cyklu, viz nize - // navic zavadime obranu proti mnozeni msgboxu pri vice TRACE_C zaroven, pusobilo - // by to jen zmatky, ted se otevre msgbox jen pro prvni a ten po uzavreni vyvola - // padacku, ostatni TRACE_C zustanou chyceny v nekonecne cekaji smycce, viz nize + // only if crash==TRUE: + // make a copy of the data, because starting the msgbox thread can trigger more TRACE + // messages (for example, DllMain reacting to DLL_THREAD_ATTACH); if we did not leave + // the CriticalSection, a deadlock would occur; + // TRACE_C must not be used in DllMain, otherwise a deadlock occurs: + // - if TRACE_C is used in DLL_THREAD_ATTACH: it tries to open a new thread for the msgbox + // and DllMain blocks that + // - if TRACE_C is used in DLL_THREAD_DETACH: while waiting for the msgbox thread of the + // previous TRACE_C to close, we catch TRACE_C from DLL_THREAD_DETACH and leave it + // waiting in an infinite loop, see below + // in addition, we guard against multiple msgboxes when several TRACE_C occur at once; + // that would only cause confusion, so now a msgbox is opened only for the first one and it + // triggers a crash after it closes; the other TRACE_C remain stuck in an infinite waiting loop, see below static BOOL msgBoxOpened = FALSE; C__TraceMsgBoxThreadData threadData; C__TraceMsgBoxThreadDataW threadDataW; - if (crash) // break/padacka po vypisu TRACE error hlasky (TRACE_C a TRACE_MC) + if (crash) // break/crash after displaying the TRACE error message (TRACE_C and TRACE_MC) { if (!msgBoxOpened) { @@ -1120,36 +1121,36 @@ C__Trace::SendMessageToServer(C__MessageType type, BOOL crash) } } if (unicode) - TraceStringBufW.erase(); // priprava pro dalsi trace + TraceStringBufW.erase(); // prepare for the next trace else TraceStringBuf.erase(); LeaveCriticalSection(&CriticalSection); if (crash) { - if (unicode && threadDataW.Msg != NULL || // break/padacka po vypisu TRACE error hlasky (TRACE_C a TRACE_MC) + if (unicode && threadDataW.Msg != NULL || // break/crash after displaying the TRACE error message (TRACE_C and TRACE_MC) !unicode && threadData.Msg != NULL) { - // vypiseme hlasku v jinem threadu, aby nepumpovala zpravy aktualniho threadu + // show the message in another thread so the current thread does not pump messages DWORD id; HANDLE msgBoxThread = CreateThread(NULL, 0, unicode ? __TraceMsgBoxThreadW : __TraceMsgBoxThread, unicode ? (void*)&threadDataW : (void*)&threadData, 0, &id); if (msgBoxThread != NULL) { - WaitForSingleObject(msgBoxThread, INFINITE); // pokud se da TRACE_C do DllMain do DLL_THREAD_ATTACH, dojde k deadlocku - silne nepravdepodobne, neresime + WaitForSingleObject(msgBoxThread, INFINITE); // if TRACE_C is used in DllMain during DLL_THREAD_ATTACH, a deadlock occurs - very unlikely, we do not handle it CloseHandle(msgBoxThread); } msgBoxOpened = FALSE; GlobalFree(unicode ? (HGLOBAL)threadDataW.Msg : (HGLOBAL)threadData.Msg); - // pad softu vyvolame primo v kodu, kde je umisteny TRACE_C/TRACE_MC, aby - // bylo v bug reportu videt presne kde makra lezi; padacka tedy nasleduje - // po dokonceni teto metody + // we trigger the crash directly in the code where TRACE_C/TRACE_MC is placed, so + // it is clear in the bug report exactly where the macros are; the crash therefore follows + // after this method finishes } - else // ostatni thready s TRACE_C zablokujeme, az se zavre msgbox otevreny pro - { // prvni TRACE_C, tak to tam i spadne, at v tom neni bordel + else // block other threads with TRACE_C until the message box opened by the first TRACE_C closes + { // the first TRACE_C closes; then the first TRACE_C crashes there too, to avoid confusion if (msgBoxOpened) { while (1) - Sleep(1000); // blokace vede na deadlock napr. kdyz je (a nema byt) TRACE_C v DLL_THREAD_DETACH + Sleep(1000); // Blocking causes a deadlock, for example if TRACE_C is used in DLL_THREAD_DETACH, where it must not be. } } } @@ -1158,15 +1159,14 @@ C__Trace::SendMessageToServer(C__MessageType type, BOOL crash) #endif // TRACE_ENABLE -// pasticka na vlastni definici techto "zakazanych" operatoru (aby fungovala kontrola -// zakazanych kombinaci stringu WCHAR / char v jednom TRACE nebo MESSAGE makru, -// nesmi byt nasledujici operatory definovany v jinych modulech - jinak by linker -// neohlasil chybu - idea: v DEBUG verzi chytame chyby linkeru, v RELEASE verzi chytame -// chyby vlastni definice operatoru; aby se otestovaly obe veci, musi byt povolene -// TRACE_ENABLE v DEBUG i RELEASE verzi, coz napr. u Salamandera splnuje SDK build; -// nejbeznejsi model je v DEBUG verzi mit povolene TRACE_ENABLE a v RELEASE ne, v tomto -// pripade se provede jen prvni test, ktery je dulezitejsi (zakazane kombinace stringu -// WCHAR / char)) +// trap for custom definitions of these "forbidden" operators (for the check +// for forbidden WCHAR/char string combinations in a single TRACE or MESSAGE macro +// to work, the following operators must not be defined in other modules - otherwise the linker +// would not report an error - the idea is: in the DEBUG build we catch linker errors, in the RELEASE build we catch +// errors from custom operator definitions; to test both, TRACE_ENABLE must be enabled +// in both DEBUG and RELEASE builds, which the Salamander SDK build, for example, satisfies; +// the most common setup is to have TRACE_ENABLE enabled in DEBUG and disabled in RELEASE, in that +// case only the first test runs, which is the more important one (forbidden WCHAR/char string combinations)) #ifndef _DEBUG #include diff --git a/src/common/trace.h b/src/common/trace.h index 4205bad02..bd9c4551c 100644 --- a/src/common/trace.h +++ b/src/common/trace.h @@ -1,45 +1,46 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once -// makro TRACE_ENABLE - zapoji vypis hlasek na server -// makro MULTITHREADED_TRACE_ENABLE - zapoji premapovavani TID na UTID -// makro TRACE_TO_FILE - zapoji vypis hlasek do souboru v TEMPu (vyzaduje definici TRACE_ENABLE) -// makro TRACE_IGNORE_AUTOCLEAR - zakaze Trace Serveru pri pripojeni tohoto procesu smazat vsechny zpravy, -// i kdyz to ma zaple v nastaveni (hodi se pro utilitky spoustene za behu -// hlavniho programu, u kterych je mazani zprav nezadouci) -// makro __TRACESERVER - includeno z trace-serveru +// macro TRACE_ENABLE - enables sending messages to the server +// macro MULTITHREADED_TRACE_ENABLE - enables remapping TID to UTID +// macro TRACE_TO_FILE - enables writing messages to a file in TEMP (requires TRACE_ENABLE to be defined) +// macro TRACE_IGNORE_AUTOCLEAR - prevents Trace Server from clearing all messages when this process connects, +// even if that is enabled in the settings (useful for utilities started while the main +// program is running, where clearing messages is undesirable) +// macro __TRACESERVER - included from trace-server -// modul TRACE je pripraven na multi-threadove aplikace +// TRACE module is ready for multi-threaded applications -// POZOR: TRACE_C se nesmi pouzivat v DllMain knihoven, ani v zadnem kodu, ktery -// se z DllMainu vola, jinak dojde k deadlocku, vice viz implementace -// C__Trace::SendMessageToServer +// WARNING: TRACE_C must not be used in a library's DllMain, or in any code that +// is called from DllMain, otherwise a deadlock will occur; see the +// implementation of C__Trace::SendMessageToServer #if defined(__TRACESERVER) || defined(TRACE_ENABLE) enum C__MessageType { - // druh message + // message type __mtInformation, __mtError, - // nastaveni nazvu procesu / threadu + // setting the process / thread name __mtSetProcessName, __mtSetThreadName, - // druh message - unicodove varianty zprav + // message type - Unicode message variants __mtInformationW, __mtErrorW, - // nastaveni nazvu procesu / threadu - unicodove varianty zprav + // setting the process / thread name - Unicode message variants __mtSetProcessNameW, __mtSetThreadNameW, - // zakazeme Trace Serveru pri pripojeni tohoto procesu smazat vsechny zpravy, i kdyz to ma - // zaple v nastaveni (hodi se pro utilitky spoustene za behu hlavniho programu, u kterych je - // mazani zprav nezadouci) + // prevents Trace Server from clearing all messages when this process connects, even if that is + // enabled in the settings (useful for utilities started while the main program is running, where + // clearing messages is undesirable) __mtIgnoreAutoClear, }; @@ -357,14 +358,14 @@ extern const TCHAR* __OPEN_CONNECTION_MUTEX; extern const TCHAR* __CONNECT_DATA_READY_EVENT_NAME; extern const TCHAR* __CONNECT_DATA_ACCEPTED_EVENT_NAME; -#define __PIPE_SIZE 100 // maximum dat v pipe (v kB) +#define __PIPE_SIZE 100 // maximum data in the pipe (in kB) #define __COMMUNICATION_WAIT_TIMEOUT 5000 //**************************************************************************** // // CClientServerInitData // -// tato struktura se pri zahajeni komunikace predava od clienta do serveru +// This structure is passed from the client to the server when communication starts. struct C__ClientServerInitData { @@ -380,45 +381,45 @@ struct C__ClientServerInitData // // CPipeDataHeader // -// pomoci teto struktury komunikuje client se serverem pres pipu +// This structure is used by the client and server to communicate through the pipe -// Pro Type == __mtInformation || Type == __mtError -// maji promenne tyto vyznamy: +// For Type == __mtInformation || Type == __mtError +// the variables have the following meanings: struct C__PipeDataHeader { - int Type; // typ zpravy (C__MessageType) - DWORD ThreadID; // pro upresneni jeste ID threadu - DWORD UniqueThreadID; // unikatni cislo threadu (systemove ID se opakuji) - SYSTEMTIME Time; // cas vzniku message - DWORD MessageSize; // delka bufferu potrebneho pro prijem textu - DWORD MessageTextOffset; // offset textu ve spolecnem bufferu s filem - DWORD Line; // cislo radky - double Counter; // presne pocitadlo v ms + int Type; // message type (C__MessageType) + DWORD ThreadID; // thread ID for additional identification + DWORD UniqueThreadID; // unique thread number (system IDs are reused) + SYSTEMTIME Time; // message creation time + DWORD MessageSize; // length of the buffer needed to receive the text + DWORD MessageTextOffset; // offset of the text in the buffer shared with the file name + DWORD Line; // line number + double Counter; // high-resolution counter in ms }; #define __SIZEOF_PIPEDATAHEADER 48 -// Pro Type == __mtSetProcessName -// C__MessageType Type; // typ zpravy -// DWORD MessageSize // delka bufferu potrebneho pro prijem nazvu +// For Type == __mtSetProcessName +// C__MessageType Type; // message type +// DWORD MessageSize // length of the buffer needed to receive the name // Pro Type == __mtSetThreadName -// C__MessageType Type; // typ zpravy +// C__MessageType Type; // message type // DWORD UniqueThreadID; // Unique Thread ID -// DWORD MessageSize // delka bufferu potrebneho pro prijem nazvu +// DWORD MessageSize // length of the buffer needed to receive the name // Pro Type == __mtIgnoreAutoClear -// C__MessageType Type; // typ zpravy +// C__MessageType Type; // message type // DWORD ThreadID; // 0 = neignorovat, 1 = ignorovat auto-clear na Trace Serveru -// aktualni verze clientu (porovnava se s verzi serveru) +// current client version (compared with the server version) #define TRACE_CLIENT_VERSION 7 #endif // defined(__TRACESERVER) || defined(TRACE_ENABLE) #ifndef TRACE_ENABLE -// aby nedochazelo k problemum se stredniky v nize nadefinovanych makrech +// to avoid problems with semicolons in the macros defined below inline void __TraceEmptyFunction() {} #define TRACE_MI(file, line, str) __TraceEmptyFunction() @@ -431,14 +432,14 @@ inline void __TraceEmptyFunction() {} #define TRACE_MEW(file, line, str) __TraceEmptyFunction() #define TRACE_E(str) __TraceEmptyFunction() #define TRACE_EW(str) __TraceEmptyFunction() -// pri crashi softu pres DebugBreak() nejde vystopovat, kde lezi volani -// TRACE_C/TRACE_MC, protoze adresa exceptiony je kdesi v ntdll.dll -// a sekce Stack Back Trace bug reportu muze obsahovat nesmysly, pokud -// funkce volajici TRACE_C/TRACE_MC nepouziva stary jednoduchy model -// ukladani a prace s EBP/ESP, ovsem i v tom pripade je zde jen adresa -// odkud byla tato funkce volana (ne primo adresa TRACE_C/TRACE_MC), -// proto aspon prozatim pouzivame stary primitivni zpusob crashe -// zapisem na NULL +// when the program crashes through DebugBreak(), it is impossible to trace where +// TRACE_C/TRACE_MC was called, because the exception address ends up somewhere in ntdll.dll, +// and the Stack Back Trace section of the bug report may contain nonsense if +// the function calling TRACE_C/TRACE_MC does not use the old simple model for +// saving and using EBP/ESP; even then, only the address from which +// that function was called is available (not the TRACE_C/TRACE_MC address itself), +// so at least for now we use the old primitive way of crashing +// by writing to NULL //#define TRACE_MC(file, line, str) DebugBreak() //#define TRACE_MCW(file, line, str) DebugBreak() //#define TRACE_C(str) DebugBreak() @@ -479,7 +480,7 @@ uintptr_t __TRACE_beginthreadex(void* security, unsigned stack_size, #endif // MULTITHREADED_TRACE_ENABLE -// info-trace, manualne zadana pozice v souboru +// info-trace, manually specified file position #define TRACE_MI(file, line, str) \ (::EnterCriticalSection(&__Trace.CriticalSection), __Trace.StoreLastError(), \ __Trace.OStream() << str, __Trace) \ @@ -502,7 +503,7 @@ uintptr_t __TRACE_beginthreadex(void* security, unsigned stack_size, #define TRACE_W(str) TRACE_I(str) #define TRACE_WW(str) TRACE_IW(str) -// error-trace, manualne zadana pozice v souboru +// error-trace, manually specified file position #define TRACE_ME(file, line, str) \ (::EnterCriticalSection(&__Trace.CriticalSection), __Trace.StoreLastError(), \ __Trace.OStream() << str, __Trace) \ @@ -521,15 +522,15 @@ uintptr_t __TRACE_beginthreadex(void* security, unsigned stack_size, #define TRACE_E(str) TRACE_ME(__FILE__, __LINE__, str) #define TRACE_EW(str) TRACE_MEW(__WFILE__, __LINE__, str) -// fatal-error-trace (CRASHING TRACE), manualne zadana pozice v souboru; -// zastavime soft v debuggeru, pro snadne odladeni problemu, ktery prave vznikl, -// release verze spadne a problem snad bude jasny z call-stacku v bug-reportu; -// nepouzivame DebugBreak(), protoze pri crashi softu nejde vystopovat, kde -// lezi volani DebugBreak(), protoze adresa exceptiony je kdesi v ntdll.dll -// a sekce Stack Back Trace bug reportu muze obsahovat nesmysly, pokud -// funkce, ze ktere volame TRACE_C/MC, nepouziva stary jednoduchy model ukladani -// a prace s EBP/ESP (to zalezi na kompileru a zaplych optimalizacich), proto -// aspon prozatim pouzivame stary primitivni zpusob crashe zapisem na NULL +// fatal-error-trace (CRASHING TRACE), manually specified file location; +// stop the program in the debugger to make the problem that just occurred easier to debug; +// the release build crashes, and the problem will hopefully be clear from the call stack in the bug report; +// we do not use DebugBreak(), because when the program crashes through DebugBreak(), it is impossible to trace where +// TRACE_C/MC was called: the exception address ends up somewhere in ntdll.dll, +// and the Stack Back Trace section of the bug report may contain nonsense if +// the function that calls TRACE_C/MC does not use the old simple model for +// saving and using EBP/ESP (this depends on the compiler and enabled optimizations), so +// at least for now we use the old primitive way of crashing by writing to NULL #define TRACE_MC(file, line, str) \ ((::EnterCriticalSection(&__Trace.CriticalSection), __Trace.StoreLastError(), \ __Trace.OStream() << str, __Trace) \ @@ -587,7 +588,7 @@ class C__TraceThreadCache int UniqueThreadID; DWORD CacheTID[__TRACE_CACHE_SIZE]; - DWORD CacheUID[__TRACE_CACHE_SIZE]; // hodnota -1 -> invalidni zaznam + DWORD CacheUID[__TRACE_CACHE_SIZE]; // value -1 -> invalid record public: C__TraceThreadCache(); @@ -613,29 +614,29 @@ class C__Trace #endif // MULTITHREADED_TRACE_ENABLE protected: - HANDLE HWritePipe; // zapisovy konec pipe - HANDLE HPipeSemaphore; // slouzi pro alokaci mista v pipe (1x wait = 1kB) - DWORD BytesAllocatedForWriteToPipe; // kolik mista pro zapis je prave naalokovano v pipe + HANDLE HWritePipe; // write end of the pipe + HANDLE HPipeSemaphore; // used to allocate space in the pipe (1x wait = 1 kB) + DWORD BytesAllocatedForWriteToPipe; // amount of write space currently allocated in the pipe #ifdef TRACE_TO_FILE - HANDLE HTraceFile; // soubor otevreny pro zapis v TEMPu, ukladaji se do nej vsechny message + HANDLE HTraceFile; // file opened for writing in TEMP; all messages are stored there #ifdef __TRACESERVER - WCHAR TraceFileName[MAX_PATH]; // jmeno souboru HTraceFile -#endif // __TRACESERVER + WCHAR TraceFileName[MAX_PATH]; // HTraceFile file name +#endif // TRACE_TO_FILE #endif // TRACE_TO_FILE - LARGE_INTEGER StartPerformanceCounter; // pro presny counter - uvodni hodnota - LARGE_INTEGER PerformanceFrequency; // pro presny counter + LARGE_INTEGER StartPerformanceCounter; // initial value of the high-resolution counter + LARGE_INTEGER PerformanceFrequency; // high-resolution counter frequency BOOL SupportPerformanceFrequency; - const char* File; // pomocne promenne pro predani jmena souboru (ANSI) - const WCHAR* FileW; // pomocne promenne pro predani jmena souboru (unicode) - int Line; // a cisla radku, odkud se vola TRACE_X() - C__StringStreamBuf TraceStringBuf; // string buffer drzici data trace streamu (ANSI) - C__StringStreamBufW TraceStringBufW; // string buffer drzici data trace streamu (unicode) - C__TraceStream TraceStrStream; // vlastni trace stream (ANSI) - C__TraceStreamW TraceStrStreamW; // vlastni trace stream (unicode) - DWORD StoredLastError; // GetLastError() pred TRACE_? makrem + const char* File; // helper variables for passing the file name (ANSI) + const WCHAR* FileW; // helper variables for passing the file name (Unicode) + int Line; // and the line number from which TRACE_X() is called + C__StringStreamBuf TraceStringBuf; // string buffer holding trace stream data (ANSI) + C__StringStreamBufW TraceStringBufW; // string buffer holding trace stream data (Unicode) + C__TraceStream TraceStrStream; // trace stream object (ANSI) + C__TraceStreamW TraceStrStreamW; // trace stream object (Unicode) + DWORD StoredLastError; // GetLastError() value before the TRACE_? macro public: C__Trace(); diff --git a/src/common/winlib.cpp b/src/common/winlib.cpp index aeceb3471..74d7f336b 100644 --- a/src/common/winlib.cpp +++ b/src/common/winlib.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -8,7 +9,7 @@ #include #include #include -#include // potrebuju LPCOLORMAP +#include // need LPCOLORMAP #include #if defined(_DEBUG) && defined(_MSC_VER) // without passing file+line to 'new' operator, list of memory leaks shows only 'crtdbg.h(552)' @@ -25,23 +26,23 @@ #include "winlib.h" -// opatreni proti runtime check failure v debug verzi: puvodni verze makra pretypovava rgb na WORD, -// takze hlasi ztratu dat (RED slozky) +// precaution against a runtime check failure in the debug build: the original macro casts rgb to WORD, +// so it reports data loss in the RED component #undef GetGValue #define GetGValue(rgb) ((BYTE)(((rgb) >> 8) & 0xFF)) const TCHAR* CWINDOW_CLASSNAME = _T("WinLib Universal Window"); -const TCHAR* CWINDOW_CLASSNAME2 = _T("WinLib Universal Window2"); // nema CS_VREDRAW | CS_HREDRAW +const TCHAR* CWINDOW_CLASSNAME2 = _T("WinLib Universal Window2"); // does not have CS_VREDRAW | CS_HREDRAW #ifndef _UNICODE const WCHAR* CWINDOW_CLASSNAMEW = L"WinLib Universal Window Unicode"; -const WCHAR* CWINDOW_CLASSNAME2W = L"WinLib Universal Window Unicode2"; // nema CS_VREDRAW | CS_HREDRAW +const WCHAR* CWINDOW_CLASSNAME2W = L"WinLib Universal Window Unicode2"; // does not have CS_VREDRAW | CS_HREDRAW #endif // _UNICODE CWinLibHelp* WinLibHelp = NULL; CWindowsManager WindowsManager; HINSTANCE HInstance = NULL; -BOOL WinLibReleased = FALSE; // TRUE = uz se volalo ReleaseWinLib() +BOOL WinLibReleased = FALSE; // TRUE = ReleaseWinLib() has already been called TCHAR WinLibStrings[WLS_COUNT][101] = { _T("Invalid number!"), @@ -71,7 +72,7 @@ BOOL InitializeWinLib() void ReleaseWinLib() { - // musime odpojit otevrena okna od WinLibu, protoze WinLib konci ... + // we must detach open windows from WinLib because WinLib is shutting down ... int c = WindowsManager.GetCount(); if (c > 0) TRACE_ET(_T("ReleaseWinLib(): WindowsManager still contains opened windows: ") << c); @@ -85,7 +86,7 @@ BOOL SetupWinLibHelp(CWinLibHelp* winLibHelp) } // **************************************************************************** -// WinLibIsWindowsVersionOrGreater (kopie SalIsWindowsVersionOrGreater) +// WinLibIsWindowsVersionOrGreater (copy of SalIsWindowsVersionOrGreater) // // Based on SDK 8.1 VersionHelpers.h // Indicates if the current OS version matches, or is greater than, the provided @@ -102,7 +103,7 @@ BOOL WinLibIsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WOR VER_MINORVERSION, VER_GREATER_EQUAL), VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); - SecureZeroMemory(&osvi, sizeof(osvi)); // nahrada za memset (nevyzaduje RTLko) + SecureZeroMemory(&osvi, sizeof(osvi)); // replacement for memset (does not require the RTL) osvi.dwOSVersionInfoSize = sizeof(osvi); osvi.dwMajorVersion = wMajorVersion; osvi.dwMinorVersion = wMinorVersion; @@ -110,12 +111,11 @@ BOOL WinLibIsWindowsVersionOrGreater(WORD wMajorVersion, WORD wMinorVersion, WOR return VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask) != FALSE; } -// // **************************************************************************** // CWindow // -// lpvParam - v pripade, ze se pri CreateWindow zavola CWindow::CWindowProc -// (je v tride okna), musi obsahovat adresu objektu vytvareneho okna +// lpvParam - if CWindow::CWindowProc is called during CreateWindow +// (it is in the window class), it must contain the address of the window object being created HWND CWindow::CreateEx(DWORD dwExStyle, // extended window style LPCTSTR lpszClassName, // address of registered class name @@ -128,7 +128,7 @@ HWND CWindow::CreateEx(DWORD dwExStyle, // extended window style HWND hwndParent, // handle of parent or owner window HMENU hmenu, // handle of menu or child-window identifier HINSTANCE hinst, // handle of application instance - LPVOID lpvParam) // ukazatel na objekt vytvareneho okna + LPVOID lpvParam) // pointer to the created window object { HWND hWnd = CreateWindowEx(dwExStyle, lpszClassName, @@ -144,8 +144,8 @@ HWND CWindow::CreateEx(DWORD dwExStyle, // extended window style lpvParam); if (hWnd != 0) { - if (WindowsManager.GetWindowPtr(hWnd) == NULL) // pokud se jeste neni ve WindowsManageru - AttachToWindow(hWnd); // tak ho pridame -> subclassing + if (WindowsManager.GetWindowPtr(hWnd) == NULL) // if it is not in WindowsManager yet + AttachToWindow(hWnd); // then add it -> subclassing } return hWnd; } @@ -160,7 +160,7 @@ HWND CWindow::Create(LPCTSTR lpszClassName, // address of registered class name HWND hwndParent, // handle of parent or owner window HMENU hmenu, // handle of menu or child-window identifier HINSTANCE hinst, // handle of application instance - LPVOID lpvParam) // ukazatel na objekt vytvareneho okna + LPVOID lpvParam) // pointer to the created window object { return CreateEx(0, lpszClassName, @@ -189,7 +189,7 @@ HWND CWindow::CreateExW(DWORD dwExStyle, // extended window style HWND hwndParent, // handle of parent or owner window HMENU hmenu, // handle of menu or child-window identifier HINSTANCE hinst, // handle of application instance - LPVOID lpvParam) // ukazatel na objekt vytvareneho okna + LPVOID lpvParam) // pointer to the created window object { HWND hWnd = CreateWindowExW(dwExStyle, lpszClassName, @@ -205,8 +205,8 @@ HWND CWindow::CreateExW(DWORD dwExStyle, // extended window style lpvParam); if (hWnd != 0) { - if (WindowsManager.GetWindowPtr(hWnd) == NULL) // pokud se jeste neni ve WindowsManageru - AttachToWindow(hWnd); // tak ho pridame -> subclassing + if (WindowsManager.GetWindowPtr(hWnd) == NULL) // if it is not in WindowsManager yet + AttachToWindow(hWnd); // then add it -> subclassing } return hWnd; } @@ -221,7 +221,7 @@ HWND CWindow::CreateW(LPCWSTR lpszClassName, // address of registered class nam HWND hwndParent, // handle of parent or owner window HMENU hmenu, // handle of menu or child-window identifier HINSTANCE hinst, // handle of application instance - LPVOID lpvParam) // ukazatel na objekt vytvareneho okna + LPVOID lpvParam) // pointer to the created window object { return CreateExW(0, lpszClassName, @@ -275,7 +275,7 @@ void CWindow::AttachToWindow(HWND hWnd) #ifndef _UNICODE || DefWndProc == CWindow::CWindowProcW #endif // _UNICODE - ) // to by byla rekurze + ) // that would be recursion { TRACE_CT(_T("This should never happen.")); DefWndProc = GetDefWindowProc(); @@ -328,8 +328,8 @@ CWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) return TRUE; } if (GetWindowLongPtr(HWindow, GWL_STYLE) & WS_CHILD) - break; // pokud F1 nezpracujeme a pokud je to child okno, nechame F1 propadnout do parenta - return TRUE; // pokud to neni child, ukoncime zpracovani F1 + break; // if we do not handle F1 and this is a child window, let F1 fall through to the parent + return TRUE; // if this is not a child window, stop processing F1 } } #ifndef _UNICODE @@ -363,11 +363,11 @@ CWindow::CWindowProcInt(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL CWindow* wnd; switch (uMsg) { - case WM_CREATE: // prvni zprava - pripojeni objektu k oknu + case WM_CREATE: // first message - attach the object to the window { - // osetrim MDI_CHILD_WINDOW - if (((CREATESTRUCT*)lParam)->dwExStyle & WS_EX_MDICHILD) // CREATESTRUCTA a CREATESTRUCTW se pro dwExStyle ani lpCreateParams nelisi - wnd = (CWindow*)((MDICREATESTRUCT*)((CREATESTRUCT*)lParam)->lpCreateParams)->lParam; // MDICREATESTRUCTA a MDICREATESTRUCTW se pro lParam nelisi + // handle MDI_CHILD_WINDOW + if (((CREATESTRUCT*)lParam)->dwExStyle & WS_EX_MDICHILD) // CREATESTRUCTA and CREATESTRUCTW do not differ in dwExStyle or lpCreateParams + wnd = (CWindow*)((MDICREATESTRUCT*)((CREATESTRUCT*)lParam)->lpCreateParams)->lParam; // MDICREATESTRUCTA and MDICREATESTRUCTW do not differ in lParam else wnd = (CWindow*)((CREATESTRUCT*)lParam)->lpCreateParams; if (wnd == NULL) @@ -382,8 +382,8 @@ CWindow::CWindowProcInt(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL if (wnd->UnicodeWnd != unicode) TRACE_C("Incompatible windows procedure."); #endif // _UNICODE - //--- zarazeni okna podle hwnd do seznamu oken - if (!WindowsManager.AddWindow(hwnd, wnd)) // chyba + //--- insert the window into the window list by hwnd + if (!WindowsManager.AddWindow(hwnd, wnd)) // error { TRACE_ET(_T("Unable to create window.")); return FALSE; @@ -392,7 +392,7 @@ CWindow::CWindowProcInt(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL break; } - case WM_DESTROY: // posledni zprava - odpojeni objektu od okna + case WM_DESTROY: // last message - detach the object from the window { wnd = (CWindow*)WindowsManager.GetWindowPtr(hwnd); #ifndef _UNICODE @@ -401,23 +401,23 @@ CWindow::CWindowProcInt(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL #endif // _UNICODE if (wnd != NULL && wnd->Is(otWindow)) { - // Petr: posunul jsem dolu pod wnd->WindowProc(), aby behem WM_DESTROY - // jeste dochazely zpravy (potreboval Lukas) + // Petr: moved this below wnd->WindowProc() so messages are still delivered during WM_DESTROY + // (Lukas needed this) // WindowsManager.DetachWindow(hwnd); LRESULT res = wnd->WindowProc(uMsg, wParam, lParam); - // ted uz zase do stare procedury (kvuli subclassingu) + // now back to the old procedure again (because of subclassing) WindowsManager.DetachWindow(hwnd); - // pokud aktualni WndProc je jina nez nase, nebudeme ji menit, - // protoze nekdo v rade subclasseni uz vratil puvodni WndProc + // if the current WndProc is different from ours, do not change it, + // because someone else in the subclass chain has already restored the original WndProc #ifdef _UNICODE WNDPROC currentWndProc = (WNDPROC)GetWindowLongPtr(wnd->HWindow, GWLP_WNDPROC); if (currentWndProc == CWindow::CWindowProc) SetWindowLongPtr(wnd->HWindow, GWLP_WNDPROC, (LONG_PTR)wnd->DefWndProc); #else // _UNICODE - if (wnd->UnicodeWnd) // je-li nase window procedura unicodova, musime pouzit "W" varianty API funkci + if (wnd->UnicodeWnd) // if our window procedure is Unicode, we must use the "W" API variants { WNDPROC currentWndProc = (WNDPROC)GetWindowLongPtrW(wnd->HWindow, GWLP_WNDPROC); if (currentWndProc == CWindow::CWindowProcW || currentWndProc == CWindow::CWindowProc) @@ -434,9 +434,9 @@ CWindow::CWindowProcInt(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL if (wnd->IsAllocated()) delete wnd; else - wnd->HWindow = NULL; // uz neni pripojeny + wnd->HWindow = NULL; // no longer attached if (res == 0) - return 0; // aplikace ji zpracovala + return 0; // the application processed the message wnd = NULL; } break; @@ -458,11 +458,11 @@ CWindow::CWindowProcInt(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL #endif // _UNICODE } } - //--- zavolani metody WindowProc(...) prislusneho objektu okna + //--- call the WindowProc(...) method of the corresponding window object LRESULT lResult; if (wnd != NULL) lResult = wnd->WindowProc(uMsg, wParam, lParam); - else // chyba nebo message prisla pred WM_CREATE + else // an error occurred, or the message was received before WM_CREATE { #ifndef _UNICODE lResult = unicode ? DefWindowProcW(hwnd, uMsg, wParam, lParam) : DefWindowProcA(hwnd, uMsg, wParam, lParam); @@ -639,7 +639,7 @@ CDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_INITDIALOG: { TransferData(ttDataToWindow); - return TRUE; // chci focus od DefDlgProc + return TRUE; // let DefDlgProc set the focus } case WM_HELP: @@ -650,7 +650,7 @@ CDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) (GetKeyState(VK_CONTROL) & 0x8000) != 0, (GetKeyState(VK_SHIFT) & 0x8000) != 0); } - return TRUE; // F1 nenechame propadnout do parenta ani pokud nevolame WinLibHelp->OnHelp() + return TRUE; // do not let F1 fall through to the parent even if we do not call WinLibHelp->OnHelp() } case WM_CONTEXTMENU: @@ -672,7 +672,7 @@ CDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) memset(&hi, 0, sizeof(hi)); hi.cbSize = sizeof(hi); hi.iContextType = HELPINFO_WINDOW; - hi.dwContextId = ResID; // ve WM_HELP taky chodi ResID a ne HelpID, tak at je to konzistentni + hi.dwContextId = ResID; // WM_HELP also receives ResID rather than HelpID, so keep it consistent GetCursorPos(&hi.MousePos); WinLibHelp->OnHelp(HWindow, HelpID, &hi, FALSE, FALSE); } @@ -706,7 +706,7 @@ CDialog::CDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) CDialog* dlg; switch (uMsg) { - case WM_INITDIALOG: // prvni zprava - pripojeni objektu k dialogu + case WM_INITDIALOG: // first message - attach the object to the dialog { dlg = (CDialog*)lParam; if (dlg == NULL) @@ -717,25 +717,25 @@ CDialog::CDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) else { dlg->HWindow = hwndDlg; - //--- zarazeni okna podle hwndDlg do seznamu oken - if (!WindowsManager.AddWindow(hwndDlg, dlg)) // chyba + //--- register the window in the window list under hwndDlg + if (!WindowsManager.AddWindow(hwndDlg, dlg)) // error { TRACE_ET(_T("Unable to create dialog.")); return TRUE; } - dlg->NotifDlgJustCreated(); // zavedeno jako misto pro upravu layoutu dialogu + dlg->NotifDlgJustCreated(); // introduced as a place to adjust the dialog layout } break; } - case WM_DESTROY: // posledni zprava - odpojeni objektu od dialogu + case WM_DESTROY: // last message - detach the object from the dialog { dlg = (CDialog*)WindowsManager.GetWindowPtr(hwndDlg); - INT_PTR ret = FALSE; // pro pripad, ze ji nezpracuje + INT_PTR ret = FALSE; // in case the dialog does not handle it if (dlg != NULL && dlg->Is(otDialog)) { - // Petr: posunul jsem dolu pod dlg->DialogProc(), aby behem WM_DESTROY - // jeste dochazely zpravy (potreboval Lukas) + // Petr: moved this below dlg->DialogProc() so messages are still delivered during WM_DESTROY + // (Lukas needed this) // WindowsManager.DetachWindow(hwndDlg); ret = dlg->DialogProc(uMsg, wParam, lParam); @@ -744,7 +744,7 @@ CDialog::CDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) if (dlg->IsAllocated()) delete dlg; else - dlg->HWindow = NULL; // informace o odpojeni + dlg->HWindow = NULL; // detachment information } return ret; } @@ -761,12 +761,12 @@ CDialog::CDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) #endif } } - //--- zavolani metody DialogProc(...) prislusneho objektu dialogu + //--- call the DialogProc(...) method of the corresponding dialog object INT_PTR dlgRes; if (dlg != NULL) dlgRes = dlg->DialogProc(uMsg, wParam, lParam); else - dlgRes = FALSE; // chyba nebo message neprisla mezi WM_INITDIALOG a WM_DESTROY + dlgRes = FALSE; // error or the message did not arrive between WM_INITDIALOG and WM_DESTROY return dlgRes; } @@ -835,7 +835,7 @@ void CWindowsManager::DetachWindow(HWND hWnd) return; CS.Enter(); - if (LastHWnd[GetCacheIndex(hWnd)] == hWnd) // musime vycistit cache + if (LastHWnd[GetCacheIndex(hWnd)] == hWnd) // we must clear the cache { LastHWnd[GetCacheIndex(hWnd)] = NULL; LastWnd[GetCacheIndex(hWnd)] = NULL; @@ -849,7 +849,7 @@ void CWindowsManager::DetachWindow(HWND hWnd) { ResetState(); TRACE_ET(_T("Unable to detach window from WindowsManager. hwnd = ") << hWnd); - At(i).Wnd = NULL; // alespon takhle ... + At(i).Wnd = NULL; // at least this way... } } else @@ -877,7 +877,7 @@ CWindowsManager::GetWindowPtr(HWND hWnd) search++; #endif int i; - if (GetIndex(hWnd, i)) // nalezeno + if (GetIndex(hWnd, i)) // found { LastHWnd[GetCacheIndex(hWnd)] = hWnd; LastWnd[GetCacheIndex(hWnd)] = At(i).Wnd; @@ -888,7 +888,7 @@ CWindowsManager::GetWindowPtr(HWND hWnd) else { CS.Leave(); - return NULL; // nenalezeno + return NULL; // not found } } @@ -911,9 +911,9 @@ int CWindowsManager::GetCount() CWindowQueue::~CWindowQueue() { if (!Empty()) - TRACE_ET(_T("Some window is still opened in ") << QueueName << _T(" queue!")); // nemelo by nastat... - // tady uz multi-threadovost nehrozi (konci soft, thready jsou/byly ukonceny) - // dealokujeme aspon nejakou pamet + TRACE_ET(_T("Some window is still opened in ") << QueueName << _T(" queue!")); // should not happen... + // there is no multithreading risk here anymore (the app is shutting down, the threads are/were terminated) + // deallocate at least some memory CWindowQueueItem* last; CWindowQueueItem* item = Head; while (item != NULL) @@ -948,7 +948,7 @@ void CWindowQueue::Remove(HWND hWindow) CWindowQueueItem* item = Head; while (item != NULL) { - if (item->HWindow == hWindow) // nalezeno, odstranime + if (item->HWindow == hWindow) // found, remove it { if (last != NULL) last->Next = item->Next; @@ -1001,7 +1001,7 @@ void CWindowQueue::BroadcastMessage(DWORD uMsg, WPARAM wParam, LPARAM lParam) BOOL CTransferInfo::GetControl(HWND& ctrlHWnd, int ctrlID, BOOL ignoreIsGood) { if (!ignoreIsGood && !IsGood()) - return FALSE; // dalsi nema cenu zpracovavat + return FALSE; // no point in processing further ctrlHWnd = GetDlgItem(HDialog, ctrlID); if (ctrlHWnd == NULL) { @@ -1021,8 +1021,8 @@ void CTransferInfo::EnsureControlIsFocused(int ctrlID) HWND wnd = GetFocus(); while (wnd != NULL && wnd != ctrl) wnd = ::GetParent(wnd); - if (wnd == NULL) // fokusime jen pokud neni ctrl predek GetFocusu - { // jako napr. edit-line v combo-boxu + if (wnd == NULL) // Set focus only if ctrl is not an ancestor of the focused window. + { // This occurs, for example, with the edit box in a combo box. SendMessage(HDialog, WM_NEXTDLGCTL, (WPARAM)ctrl, TRUE); } } @@ -1107,8 +1107,8 @@ void CTransferInfo::EditLine(int ctrlID, double& value, TCHAR* format, BOOL sele BOOL decPoints = FALSE; BOOL expPart = FALSE; if (*s == _T('-') || *s == _T('+')) - s++; // preskok znamenka - while (*s != 0) // prevod carky na tecku + s++; // skip the digit + while (*s != 0) // convert comma to period { if (!expPart && !decPoints && (*s == _T(',') || *s == _T('.'))) { @@ -1121,7 +1121,7 @@ void CTransferInfo::EditLine(int ctrlID, double& value, TCHAR* format, BOOL sele { expPart = TRUE; if (*(s + 1) == _T('+') || *(s + 1) == _T('-')) - s++; // preskok +- za E + s++; // skip +/- after E } else { @@ -1139,10 +1139,10 @@ void CTransferInfo::EditLine(int ctrlID, double& value, TCHAR* format, BOOL sele if (*s == 0) { TCHAR* stopString; // dummy - value = _tcstod(buff, &stopString); // jen pokud je cislo + value = _tcstod(buff, &stopString); // only if the string is a number } else - value = 0; // pri chybe dame nulu + value = 0; // on error, set zero break; } } @@ -1173,8 +1173,8 @@ void CTransferInfo::EditLine(int ctrlID, int& value, BOOL select) TCHAR* s = buff; if (*s == _T('-') || *s == _T('+')) - s++; // preskok znamenka - while (*s != 0) // kontrola cisla + s++; // skip the digit + while (*s != 0) // validate the number { if (*s < _T('0') || *s > _T('9')) { @@ -1187,7 +1187,7 @@ void CTransferInfo::EditLine(int ctrlID, int& value, BOOL select) } TCHAR* endptr; - value = _tcstoul(buff, &endptr, 10); // nahrada za atoi / _ttoi, ktere misto 4000000000 vraci 2147483647 (protoze je to SIGNED INT) + value = _tcstoul(buff, &endptr, 10); // replacement for atoi / _ttoi, which returns 2147483647 instead of 4000000000 because it uses signed int break; } } @@ -1227,10 +1227,10 @@ void CTransferInfo::EditLine(int ctrlID, __int64& value, BOOL select, BOOL unsig TCHAR* s = buff; BOOL minus = !unsignedNum && *s == _T('-'); if (!unsignedNum && *s == _T('-') || *s == _T('+')) - s++; // preskok znamenka + s++; // skip the digit unsigned __int64 num = 0; BOOL overflow = FALSE; - while (*s != 0) // kontrola cisla + while (*s != 0) // validate the number { if ((*s < _T('0') || *s > _T('9')) && (!hexMode || *s < _T('A') || *s > _T('F'))) { @@ -1245,7 +1245,7 @@ void CTransferInfo::EditLine(int ctrlID, __int64& value, BOOL select, BOOL unsig else { if (hexMode && num > 0x0fffffffffffffffui64 || - !hexMode && num > 1844674407370955161ui64 || // max. je 18446744073709551615ui64 + !hexMode && num > 1844674407370955161ui64 || // max. is 18446744073709551615ui64 !hexMode && num == 1844674407370955161ui64 && *s > _T('5')) { overflow = TRUE; // unsigned overflow @@ -1257,11 +1257,11 @@ void CTransferInfo::EditLine(int ctrlID, __int64& value, BOOL select, BOOL unsig } if (*s != 0) { - value = 0; // pri chybe dame nulu + value = 0; // on error, set zero break; } - // pri preteceni davame mezni hodnoty (inspirace: value = _ttoi64(buff)) + // on overflow, use the limit values (inspired by value = _ttoi64(buff)) if (unsignedNum) { if (overflow) @@ -1294,7 +1294,7 @@ void CTransferInfo::EditLine(int ctrlID, __int64& value, BOOL select, BOOL unsig } if (overflow) { - if (ignoreOverflow) // ohlasime overflow jen pres TRACE_E + if (ignoreOverflow) // report overflow only via TRACE_E { TRACE_ET(_T("CTransferInfo::EditLine(") << ctrlID << _T("): ") << (unsignedNum ? _T("unsigned ") : _T("")) << _T("int64 overflow has occured!")); } diff --git a/src/common/winlib.h b/src/common/winlib.h index fd7266822..19a97b242 100644 --- a/src/common/winlib.h +++ b/src/common/winlib.h @@ -1,11 +1,12 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once -// makro __DEBUG_WINLIB zapina nekolik testu zaludnych chyb WinLibu +// __DEBUG_WINLIB enables several checks for tricky WinLib bugs -// konstanty pro stringy WinLibu (jen interni pouziti ve WinLibu) +// WinLib string constants (for internal WinLib use only) enum CWLS { WLS_INVALID_NUMBER, @@ -14,26 +15,26 @@ enum CWLS WLS_COUNT }; -// nastaveni vlastnich textu do WinLibu -void SetWinLibStrings(const TCHAR* invalidNumber, // "neni cislo" (u transferbufferu cisel) - const TCHAR* error); // titulek "chyba" (u transferbufferu cisel) +// set custom WinLib strings +void SetWinLibStrings(const TCHAR* invalidNumber, // "not a number" (for numeric transfer buffers) + const TCHAR* error); // title "error" (for numeric transfer buffers) extern HINSTANCE HInstance; -extern const TCHAR* CWINDOW_CLASSNAME; // jmeno tridy universalniho okna -extern const TCHAR* CWINDOW_CLASSNAME2; // jmeno tridy universalniho okna - nema CS_VREDRAW | CS_HREDRAW +extern const TCHAR* CWINDOW_CLASSNAME; // universal window class name +extern const TCHAR* CWINDOW_CLASSNAME2; // universal window class name - no CS_VREDRAW | CS_HREDRAW #ifndef _UNICODE -extern const WCHAR* CWINDOW_CLASSNAMEW; // jmeno tridy unicodoveho universalniho okna -extern const WCHAR* CWINDOW_CLASSNAME2W; // jmeno tridy unicodoveho universalniho okna - nema CS_VREDRAW | CS_HREDRAW +extern const WCHAR* CWINDOW_CLASSNAMEW; // Unicode universal window class name +extern const WCHAR* CWINDOW_CLASSNAME2W; // Unicode universal window class name - no CS_VREDRAW | CS_HREDRAW #endif // _UNICODE class CWinLibHelp; -// je potreba zavolat pred pouzitim WinLibu +// must be called before using WinLib BOOL InitializeWinLib(); -// je potreba zavolat po pouziti WinLibu +// must be called after using WinLib void ReleaseWinLib(); -// je treba zavolat pred pouzivanim helpu +// must be called before using help BOOL SetupWinLibHelp(CWinLibHelp* winLibHelp); class CWinLibHelp @@ -46,16 +47,16 @@ class CWinLibHelp // **************************************************************************** -enum CObjectOrigin // pouzito pri destrukci oken a dialogu +enum CObjectOrigin // used when destroying windows and dialogs { - ooAllocated, // pri WM_DESTROY se bude dealokovat - ooStatic, // pri WM_DESTROY se HWindow nastavi na NULL - ooStandard // pro modalni dlg =ooStatic, pro nemodalni dlg =ooAllocated + ooAllocated, // deallocated on WM_DESTROY + ooStatic, // HWindow is set to NULL on WM_DESTROY + ooStandard // for modal dialogs = ooStatic, for modeless dialogs = ooAllocated }; // **************************************************************************** -enum CObjectType // pro rozpoznani typu objektu +enum CObjectType // for object type identification { otBase, otWindow, @@ -66,7 +67,7 @@ enum CObjectType // pro rozpoznani typu objektu // **************************************************************************** -class CWindowsObject // predek vsech MS-Windows objektu +class CWindowsObject // base class for all Windows objects { public: HWND HWindow; @@ -102,9 +103,9 @@ class CWindowsObject // predek vsech MS-Windows objektu SetHelpID(helpID); } - virtual ~CWindowsObject() {} // aby se u potomku volal jejich destruktor + virtual ~CWindowsObject() {} // so derived destructors are called - virtual BOOL Is(int) { return FALSE; } // identifikace objektu + virtual BOOL Is(int) { return FALSE; } // object type identification virtual int GetObjectType() { return otBase; } virtual BOOL IsAllocated() { return ObjectOrigin == ooAllocated; } @@ -121,8 +122,8 @@ class CWindowsObject // predek vsech MS-Windows objektu protected: CObjectOrigin ObjectOrigin; #ifndef _UNICODE - // okna: create: TRUE = okno je unicodove, jinak je ANSI; attach: TRUE = nase window procedura - // je unicodova, jinak je ANSI; dialogy: TRUE = dialog je unicodovy, jinak je ANSI + // for windows: on create, TRUE = the window is Unicode, otherwise ANSI; on attach, TRUE = our window procedure + // is Unicode, otherwise ANSI; for dialogs: TRUE = the dialog is Unicode, otherwise ANSI BOOL UnicodeWnd; #endif // _UNICODE }; @@ -201,7 +202,7 @@ class CWindow : public CWindowsObject HWND hwndParent, // handle of parent or owner window HMENU hmenu, // handle of menu or child-window identifier HINSTANCE hinst, // handle of application instance - LPVOID lpvParam); // ukazatel na objekt vytvareneho okna + LPVOID lpvParam); // pointer to the window object being created HWND CreateEx(DWORD dwExStyle, // extended window style LPCTSTR lpszClassName, // address of registered class name @@ -214,7 +215,7 @@ class CWindow : public CWindowsObject HWND hwndParent, // handle of parent or owner window HMENU hmenu, // handle of menu or child-window identifier HINSTANCE hinst, // handle of application instance - LPVOID lpvParam); // ukazatel na objekt vytvareneho okna + LPVOID lpvParam); // pointer to the window object being created #ifndef _UNICODE HWND CreateW(LPCWSTR lpszClassName, // address of registered class name @@ -227,7 +228,7 @@ class CWindow : public CWindowsObject HWND hwndParent, // handle of parent or owner window HMENU hmenu, // handle of menu or child-window identifier HINSTANCE hinst, // handle of application instance - LPVOID lpvParam); // ukazatel na objekt vytvareneho okna + LPVOID lpvParam); // pointer to the window object being created HWND CreateExW(DWORD dwExStyle, // extended window style LPCWSTR lpszClassName, // address of registered class name @@ -240,7 +241,7 @@ class CWindow : public CWindowsObject HWND hwndParent, // handle of parent or owner window HMENU hmenu, // handle of menu or child-window identifier HINSTANCE hinst, // handle of application instance - LPVOID lpvParam); // ukazatel na objekt vytvareneho okna + LPVOID lpvParam); // pointer to the window object being created #endif // _UNICODE void AttachToWindow(HWND hWnd); @@ -277,8 +278,8 @@ class CWindow : public CWindowsObject enum CTransferType { - ttDataToWindow, // data jdou do okna - ttDataFromWindow // data jdou z okna + ttDataToWindow, // data to the window + ttDataFromWindow // data from the window }; // **************************************************************************** @@ -286,7 +287,7 @@ enum CTransferType class CTransferInfo { public: - int FailCtrlID; // INT_MAX - vse v poradku, jinak ID controlu s chybou + int FailCtrlID; // INT_MAX = no error, otherwise the ID of the failing control CTransferType Type; CTransferInfo(HWND hDialog, CTransferType type) @@ -302,7 +303,7 @@ class CTransferInfo void EnsureControlIsFocused(int ctrlID); void EditLine(int ctrlID, TCHAR* buffer, DWORD bufferSizeInChars, BOOL select = TRUE); - void EditLine(int ctrlID, double& value, TCHAR* format, BOOL select = TRUE); // format napr. _T("%.2lf") + void EditLine(int ctrlID, double& value, TCHAR* format, BOOL select = TRUE); // format, e.g. _T("%.2lf") void EditLine(int ctrlID, int& value, BOOL select = TRUE); void EditLine(int ctrlID, __int64& value, BOOL select = TRUE, BOOL unsignedNum = FALSE /* signed number */, BOOL hexMode = FALSE /* decimal mode */, BOOL ignoreOverflow = FALSE, BOOL quiet = FALSE); @@ -315,7 +316,7 @@ class CTransferInfo #endif // _UNICODE protected: - HWND HDialog; // handle dialogu, pro ktery se provadi transfer + HWND HDialog; // handle of the dialog for which the transfer is performed }; // **************************************************************************** @@ -323,8 +324,8 @@ class CTransferInfo class CDialog : public CWindowsObject { public: - CWindowsObject::SetObjectOrigin; // kvuli zkompilovatelnosti CPropSheetPage - CWindowsObject::HWindow; // kvuli zkompilovatelnosti CPropSheetPage + CWindowsObject::SetObjectOrigin; // needed so CPropSheetPage compiles + CWindowsObject::HWindow; // needed so CPropSheetPage compiles #ifdef _UNICODE CDialog(HINSTANCE modul, int resID, HWND parent, CObjectOrigin origin = ooStandard) : CWindowsObject(origin) @@ -366,8 +367,8 @@ class CDialog : public CWindowsObject void SetParent(HWND parent) { Parent = parent; } HWND GetParent() { return Parent; } - INT_PTR Execute(); // modalni dialog - HWND Create(); // nemodalni dialog + INT_PTR Execute(); // modal dialog + HWND Create(); // modeless dialog static INT_PTR CALLBACK CDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); @@ -377,7 +378,7 @@ class CDialog : public CWindowsObject virtual void NotifDlgJustCreated() {} - BOOL Modal; // kvuli zpusobu destrukce dialogu + BOOL Modal; // because of the way the dialog is destroyed HINSTANCE Modul; int ResID; HWND Parent; @@ -388,14 +389,14 @@ class CDialog : public CWindowsObject struct CWindowData { - // pokud jsou objekty oken (Wnd) umistene na stacku (typicky modalni dialogy, napr. SalMessageBox()) - // a dojde k terminovani threadu, stack se zneplatni a tim jiz objekty oken nejsou pristupne, - // resime tak, ze na objekty (Wnd) sahame jen dokud jsou platne handly oken (HWnd) + // if window objects (Wnd) are allocated on the stack (typically modal dialogs, e.g. SalMessageBox()) + // and the thread terminates, the stack becomes invalid and the window objects are no longer accessible, + // so we only access the objects (Wnd) while the window handles (HWnd) are still valid HWND HWnd; CWindowsObject* Wnd; }; -#define WNDMGR_CACHE_SIZE 256 // (2kB cache) musi byt v souladu s GetCacheIndex +#define WNDMGR_CACHE_SIZE 256 // (2kB cache) must be consistent with GetCacheIndex inline int GetCacheIndex(HWND hWnd) { @@ -420,7 +421,7 @@ class CWindowsManager : protected TDirectArray int search, cache, maxWndCount; #endif - CWinLibCS CS; // je public, aby slo lokalne zamezit zmenam ve Windows Manageru + CWinLibCS CS; // public so Windows Manager changes can be prevented locally public: CWindowsManager(); @@ -431,7 +432,7 @@ class CWindowsManager : protected TDirectArray int GetCount(); private: - HWND LastHWnd[WNDMGR_CACHE_SIZE]; // posledni pozadavek - cache + HWND LastHWnd[WNDMGR_CACHE_SIZE]; // last-request cache CWindowsObject* LastWnd[WNDMGR_CACHE_SIZE]; inline BOOL GetIndex(HWND hWnd, int& index); @@ -456,7 +457,7 @@ BOOL CWindowsManager::GetIndex(HWND hWnd, int& index) { m = (l + r) / 2; HWND hw = At(m).HWnd; - if (hw == hWnd) // nalezeno + if (hw == hWnd) // found { index = m; CS.Leave(); @@ -464,9 +465,9 @@ BOOL CWindowsManager::GetIndex(HWND hWnd, int& index) } else if (hw > hWnd) { - if (l == r || l > m - 1) // nenalezeno + if (l == r || l > m - 1) // not found { - index = m; // mel by byt na teto pozici + index = m; // should be at this position CS.Leave(); return FALSE; } @@ -474,9 +475,9 @@ BOOL CWindowsManager::GetIndex(HWND hWnd, int& index) } else { - if (l == r) // nenalezeno + if (l == r) // not found { - index = m + 1; // mel by byt az za touto pozici + index = m + 1; // should be after this position CS.Leave(); return FALSE; } @@ -502,13 +503,13 @@ struct CWindowQueueItem class CWindowQueue { protected: - const TCHAR* QueueName; // jmeno fronty (jen pro debugovaci ucely) + const TCHAR* QueueName; // queue name (for debugging only) CWindowQueueItem* Head; int Count; - CWinLibCS CS; // pristup z vice threadu -> nutna synchronizace + CWinLibCS CS; // access from multiple threads -> synchronization required public: - CWindowQueue(const TCHAR* queueName /* napr. "Find Dialogs" */) + CWindowQueue(const TCHAR* queueName /* e.g. "Find Dialogs" */) { QueueName = queueName; Head = NULL; @@ -516,12 +517,12 @@ class CWindowQueue } ~CWindowQueue(); - BOOL Add(CWindowQueueItem* item); // prida polozku do fronty, vraci uspech - void Remove(HWND hWindow); // odstrani polozku z fronty - BOOL Empty(); // vraci TRUE pokud je fronta prazdna - int GetWindowCount(); // vraci pocet oken ve fronte + BOOL Add(CWindowQueueItem* item); // adds an item to the queue, returns success status + void Remove(HWND hWindow); // removes an item from the queue + BOOL Empty(); // returns TRUE if the queue is empty + int GetWindowCount(); // returns the number of windows in the queue - // posle (PostMessage - okna muzou byt v ruznych threadech) vsem oknum zpravu + // posts the message to all windows (PostMessage - windows may be in different threads) void BroadcastMessage(DWORD uMsg, WPARAM wParam, LPARAM lParam); }; diff --git a/src/consts.h b/src/consts.h index 1f7e5c63b..f16056c83 100644 --- a/src/consts.h +++ b/src/consts.h @@ -1,64 +1,64 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once -// aktualni verze konfigurace (popis viz. mainwnd2.cpp) +// current configuration version (see mainwnd2.cpp for details) extern const DWORD THIS_CONFIG_VERSION; -// Expirace verze: pro beta a PB verze odkomentovat, pro ostre verze zakomentovat: +// Version expiration: uncomment for beta and PB builds, comment out for release builds: //#define USE_BETA_EXPIRATION_DATE -// pro PB (EAP) verze odkomentovat, pro ostatni verze zakomentovat: +// For PB (EAP) builds uncomment, for other builds comment out: //#define THIS_IS_EAP_VERSION #ifdef USE_BETA_EXPIRATION_DATE -// urcuje prvni den, kdy uz tato beta verze nepobezi +// specifies the first day when this beta build will no longer run extern SYSTEMTIME BETA_EXPIRATION_DATE; #endif // USE_BETA_EXPIRATION_DATE -// jen pro DEBUG verzi Salama: umozni debugovat tvorbu bugreportu (defaultne se nedela, -// exceptiona se jen preda MSVC debuggeru) +// DEBUG build only: allows debugging bug report creation (normally no report is built, +// the exception is simply passed to the MSVC debugger) //#define ENABLE_BUGREPORT_DEBUGGING 1 -// slouzi pro detekci, zda wheel message prisla pres hook nebo primo -extern BOOL MouseWheelMSGThroughHook; // TRUE: zprava sla skrz hook v case MouseWheelMSGTime; FALSE: zprava sla skrz panel v case MouseWheelMSGTime -extern DWORD MouseWheelMSGTime; // casove razitko pri posledni zprave -#define MOUSEWHEELMSG_VALID 100 // [ms] pocet milisekund, po ktere je validni jeden kanal (hook vs okno) +// used to detect whether a wheel message came through the hook or directly +extern BOOL MouseWheelMSGThroughHook; // TRUE: the message went through the hook at the time stored in MouseWheelMSGTime; FALSE: the message went through the panel at the time stored in MouseWheelMSGTime +extern DWORD MouseWheelMSGTime; // timestamp of the last wheel message +#define MOUSEWHEELMSG_VALID 100 // [ms] number of milliseconds for which one channel (hook vs. window) remains valid enum { otViewerWindow = 10, }; -// podpora pro horizontalni scroll (funguje jiz na W2K/XP s Intellipoint ovladacema, oficialne podporeno od Visty) +// horizontal scroll support (works on W2K/XP with Intellipoint drivers, officially supported since Vista) #define WM_MOUSEHWHEEL 0x020E BOOL PostMouseWheelMessage(MSG* pMSG); -// zjisti jestli je velka sance (jiste se to urcit neda), ze Salamander v pristich par -// okamzicich nebude "busy" (nebude otevreny zadny modalni dialog a nebude se zpracovavat -// zadna zprava) - v tomto pripade vraci TRUE (jinak FALSE); neni-li 'lastIdleTime' NULL, -// vraci se v nem GetTickCount() z okamziku posledniho prechodu z "idle" do "busy" stavu -// je mozne volat z libovolneho threadu +// checks if it is very likely (though not guaranteed) that Salamander will not be "busy" in the next +// few moments (no modal dialog open and no message being processed). Returns TRUE in that case, otherwise FALSE. +// If 'lastIdleTime' is not NULL, it receives GetTickCount() from the last idle->busy transition. +// Can be called from any thread. BOOL SalamanderIsNotBusy(DWORD* lastIdleTime); -// otevre HTML help Salamandera nebo pluginu, jazyk helpu (adresar s .chm soubory) vybira takto: -// -adresar ziskany z aktualniho .slg souboru Salamandera (viz SLGHelpDir v shared\versinfo.rc) -// -HELP\ENGLISH\*.chm -// -prvni nalezeny podadresar v podadresari HELP -// 'helpFileName' je jmeno .chm souboru, se kterym se ma pracovat (jmeno je bez cesty), je-li NULL, -// jde o "salamand.chm"; 'parent' je parent messageboxu s chybou; 'command' je prikaz HTML helpu, -// viz HHCDisplayXXX; 'dwData' je parametr prikazu HTML helpu, viz HHCDisplayXXX -// je mozne volat z libovolneho threadu -// Pokud je 'quiet' TRUE, nezobrazi se chybova hlaska. -// Vraci TRUE, pokud se help podarilo otevrite, jinak vraci FALSE; +// Opens Salamander or plugin HTML Help. The help language (the directory with .chm files) is selected as follows: +// - directory from the current Salamander .slg file (see SLGHelpDir in shared\versinfo.rc) +// - HELP\ENGLISH\*.chm +// - first subdirectory found in HELP +// 'helpFileName' is the .chm file name to use (without a path); if NULL, "salamand.chm" is used. +// 'parent' is the parent window for the error message box; 'command' is the HTML Help command, +// see HHCDisplayXXX; 'dwData' is the HTML Help command parameter, see HHCDisplayXXX +// Can be called from any thread. +// If 'quiet' is TRUE, no error message is shown. +// Returns TRUE if the help was opened successfully; otherwise returns FALSE. BOOL OpenHtmlHelp(char* helpFileName, HWND parent, CHtmlHelpCommand command, DWORD_PTR dwData, BOOL quiet); -extern CRITICAL_SECTION OpenHtmlHelpCS; // kriticka sekce pro OpenHtmlHelp() +extern CRITICAL_SECTION OpenHtmlHelpCS; // critical section used by OpenHtmlHelp() -/* jednoduche zajisteni behu v kriticke sekci, priklad pouziti: +/* simple way to run inside a critical section, example usage: static CCriticalSection cs; CEnterCriticalSection enterCS(cs); */ @@ -93,610 +93,619 @@ class CEnterCriticalSection } }; -// protoze windowsova GetTempFileName nefunguje, napsali jsme si vlastniho klona: -// vytvori soubor/adresar (podle 'file') na ceste 'path' (NULL -> Window TEMP dir), -// s prefixem 'prefix', vraci jmeno vytvoreneho souboru v 'tmpName' (min. velikost MAX_PATH), -// vraci "uspech?" (pri neuspechu vraci pres SetLastError kod Windows chyby - pro kompatib.) +// Because Windows GetTempFileName does not work correctly, this function is our own clone: +// creates a file/directory (depending on 'file') at 'path' (NULL -> Windows TEMP dir), +// with prefix 'prefix', returns the created name in 'tmpName' (minimum buffer size MAX_PATH), +// and returns success status; on failure, SetLastError contains the Windows error code for compatibility. BOOL SalGetTempFileName(const char* path, const char* prefix, char* tmpName, BOOL file); -// protoze windowsova verze MoveFile nezvlada prejmenovani souboru s read-only atributem na Novellu, -// napsali jsme si vlastni (nastane-li chyba pri MoveFile, zkusi shodit read-only, provest operaci, -// a pak ho zase nahodit) +// Windows MoveFile cannot rename a file with the read-only attribute on Novell volumes, +// so we have our own version (on failure we drop the read-only flag, perform the operation, +// then restore it) BOOL SalMoveFile(const char* srcName, const char* destName); -// varianta k windowsove verzi GetFileSize (ma jednodussi osetreni chyb); 'file' je otevreny -// soubor pro volani GetFileSize(); v 'size' vraci ziskanou velikost souboru; vraci uspech, -// pri FALSE (chyba) je v 'err' windowsovy kod chyby a v 'size' nula +// replacement for Windows GetFileSize with simpler error handling; 'file' is an open +// handle for GetFileSize(); the result is stored in 'size'. Returns success, otherwise +// 'err' receives the Windows error code and 'size' is zero BOOL SalGetFileSize(HANDLE file, CQuadWord& size, DWORD& err); -BOOL SalGetFileSize2(const char* fileName, CQuadWord& size, DWORD* err); // 'err' muze byt NULL pokud nas nezajima +BOOL SalGetFileSize2(const char* fileName, CQuadWord& size, DWORD* err); // 'err' may be NULL if the error code is not needed struct COperation; -// zjisti velikost souboru, na ktery vede symlink 'fileName'; je-li 'op' ruzne od NULL, -// pri cancelu se vnitrek 'op' uvolni; je-li 'fileName' NULL, bere se 'op->SourceName'; -// velikost vraci v 'size'; 'ignoreAll' je in + out, je-li TRUE vsechny chyby se ignoruji -// (pred akci je treba priradit FALSE, jinak se okno s chybou vubec nezobrazi, pak uz -// nemenit); pri chybe zobrazi standardni okno s dotazem Retry / Ignore / Ignore All / Cancel -// s parentem 'parent'; pokud velikost uspesne zjisti, vraci TRUE; pri chybe a stisku -// tlacitka Ignore / Igore All v okne s chybou, vraci FALSE a v 'cancel' vraci FALSE; -// je-li 'ignoreAll' TRUE, okno se neukaze, na tlacitko se neceka, chova se jako by -// uzivatel stiskl Ignore; pri chybe a stisku Cancel v okne s chybou vraci FALSE a -// v 'cancel' vraci TRUE +// Determines the size of the file pointed to by the symlink 'fileName'. If 'op' is not +// NULL, the contents of 'op' are released on Cancel. If 'fileName' is NULL, +// 'op->SourceName' is used. The size is returned in 'size'. 'ignoreAll' is both input +// and output; if it is TRUE, all errors are ignored. Set it to FALSE before the +// operation, otherwise the error dialog is not shown at all, and do not change it +// afterwards. On error, the standard Retry / Ignore / Ignore All / Cancel dialog with +// parent 'parent' is shown. Returns TRUE if the size is determined successfully. On +// error, if Ignore or Ignore All is chosen, returns FALSE and stores FALSE in 'cancel'. +// If 'ignoreAll' is TRUE, the dialog is not shown and the function behaves as if the +// user had pressed Ignore. On error, if Cancel is chosen, returns FALSE and stores TRUE +// in 'cancel'. BOOL GetLinkTgtFileSize(HWND parent, const char* fileName, COperation* op, CQuadWord* size, BOOL* cancel, BOOL* ignoreAll); -// protoze windowsova verze GetFileAttributes neumi pracovat se jmeny koncicimi mezerou/teckou, -// napsali jsme si vlastni (u techto jmen pridava backslash na konec, cimz uz pak -// GetFileAttributes funguje spravne, ovsem jen pro adresare, pro soubory s mezerou/teckou na -// konci reseni nemame, ale aspon se to nezjistuje od jineho souboru - windowsova verze -// orizne mezery/tecky a pracuje tak s jinym souborem/adresarem) +// Windows GetFileAttributes cannot handle names ending with a space or dot, so we created +// our own version. For such names it appends a backslash which fixes GetFileAttributes for directories; +// files with trailing spaces/dots remain problematic, but at least we avoid reading attributes of another file +// because the Windows version trims spaces/dots and operates on a different name. DWORD SalGetFileAttributes(const char* fileName); -// pokud ma soubor/adresar 'name' read-only atribut, pokusime se ho vypnout -// (duvod: napr. aby sel smazat pres DeleteFile); pokud uz mame atributy 'name' -// nactene, predame je v 'attr', je-li 'attr' -1, ctou se atributy 'name' z disku; -// vraci TRUE pokud se provede pokus o zmenu atributu (uspech se nekontroluje) -// POZNAMKA: vypina jen read-only atribut, aby v pripade vice hardlinku nedoslo -// k zbytecne velke zmene atributu na zbyvajicich hardlinkach souboru (atributy -// vsechny hardlinky sdili) +// If the file or directory 'name' has the read-only attribute we try to clear it +// (so DeleteFile can succeed). If the attributes have already been read we pass them in 'attr'; +// when 'attr' is -1 the attributes are read from disk. Returns TRUE if the change was attempted +// (the success is not checked). NOTE: only the read-only attribute is cleared to avoid unnecessary +// attribute changes on other hard links which all share the same attributes. BOOL ClearReadOnlyAttr(const char* name, DWORD attr = -1); -// smaze link na adresar (junction point, symbolic link, mount point); pri uspechu -// vraci TRUE; pri chybe vraci FALSE a neni-li 'err' NULL, vraci kod chyby v 'err' +// Deletes a directory link (junction point, symbolic link, mount point). Returns TRUE on success; +// on failure returns FALSE and if 'err' is not NULL, the error code is stored there. BOOL DeleteDirLink(const char* name, DWORD* err); -// vraci TRUE, pokud je cesta 'path' na NOVELLskem svazku (slouzi k detekci toho, -// jestli lze pouzit fast-directory-move) +// Returns TRUE if 'path' resides on a NOVELL volume (used to detect whether fast-directory-move can be used) BOOL IsNOVELLDrive(const char* path); -// vraci TRUE, pokud je cesta 'path' na LANTASTICskem svazku (slouzi k detekci toho, -// jestli je nutne po kopirovani kontrolovat velikost souboru); pro optimalizacni -// ucely se vyuzivaji 'lastLantasticCheckRoot' (pro prvni volani "", pak nemenit) -// a 'lastIsLantasticPath' (vysledek pro 'lastLantasticCheckRoot') +// Returns TRUE if 'path' is located on a LANTASTIC volume (used to decide +// whether the file size must be verified after copying). For performance the +// parameters 'lastLantasticCheckRoot' (empty for the first call, then unchanged) +// and 'lastIsLantasticPath' (result for 'lastLantasticCheckRoot') are used BOOL IsLantasticDrive(const char* path, char* lastLantasticCheckRoot, BOOL& lastIsLantasticPath); -// vraci TRUE pro sitove cesty +// returns TRUE for network paths BOOL IsNetworkPath(const char* path); -// vraci TRUE pokud 'path' lezi na svazku, ktery podporuje ADS (nebo nastala chyba pri -// zjistovani o jaky file-system jde) a jsme pod NT/W2K/XP; neni-li 'isFAT32' NULL, -// vraci v nem TRUE pokud 'path' vede na FAT32 svazek; vraci FALSE jen pokud je -// jiste, ze FS nepodporuje ADS +// returns TRUE if 'path' lies on a volume supporting ADS (or an error occurred while +// detecting the file system) and we are on NT/W2K/XP; if 'isFAT32' is not NULL, +// it receives TRUE if 'path' points to a FAT32 volume; returns FALSE only when it is +// certain the FS does not support ADS BOOL IsPathOnVolumeSupADS(const char* path, BOOL* isFAT32); -// test jestli jde o Sambu (Linuxova podpora sdileni disku s Windows) +// test whether this is a Samba share (Linux sharing with Windows) BOOL IsSambaDrivePath(const char* path); -// test jestli jde o UNC cestu (detekuje oba formaty: \\server\share i \\?\UNC\server\share) +// test whether the path is UNC (detects both \\server\share and \\?\UNC\server\share formats) BOOL IsUNCPath(const char* path); -// test jestli jde o UNC root (detekuje jen format: \\server\share) +// test whether the path is UNC root (only detects the \\server\share format) BOOL IsUNCRootPath(const char* path); -// vytvoreni souboru se jmenem 'fileName' pres klasicke volani Win32 API -// CreateFile (lpSecurityAttributes==NULL, dwCreationDisposition==CREATE_NEW, -// hTemplateFile==NULL); tato metoda resi kolizi 'fileName' s dosovym nazvem -// jiz existujiciho souboru/adresare (jen pokud nejde i o kolizi s dlouhym -// jmenem souboru/adresare) - zajisti zmenu dosoveho jmena tak, aby se soubor se -// jmenem 'fileName' mohl vytvorit (zpusob: docasne prejmenuje konfliktni -// soubor/adresar na jine jmeno a po vytvoreni 'fileName' ho prejmenuje zpet); -// vraci handle souboru nebo pri chybe INVALID_HANDLE_VALUE (chyba je v GetLastError()); -// neni-li 'encryptionNotSupported' NULL a soubor nejde otevrit s Encrypted -// atributem, zkusi ho otevrit jeste bez Encrypted atributu, pokud se to povede, -// soubor je smazan a do 'encryptionNotSupported' se zapise TRUE - navratova hodnota -// funkce a GetLastError() obsahuji "puvodni" chybu (otevirani s Encrypted atributem) +// creates a file named 'fileName' using the standard Win32 API CreateFile +// (lpSecurityAttributes==NULL, dwCreationDisposition==CREATE_NEW, hTemplateFile==NULL). +// This method handles collisions between 'fileName' and an existing DOS name +// (only when it is not also a long-name collision) by temporarily renaming the +// conflicting file/directory and renaming it back after creating 'fileName'. +// Returns a file handle or INVALID_HANDLE_VALUE on error (GetLastError()). +// If 'encryptionNotSupported' is not NULL and the file cannot be opened with the +// Encrypted attribute, it tries again without encryption support, +// the file is deleted and 'encryptionNotSupported' is set to TRUE - the function's +// return value and GetLastError() contain the original error from opening with the Encrypted attribute HANDLE SalCreateFileEx(const char* fileName, DWORD desiredAccess, DWORD shareMode, DWORD flagsAndAttributes, BOOL* encryptionNotSupported); -// zkontroluje posledni komponentu jmena v ceste 'path', pokud obsahuje na -// zacatku nebo na konci mezeru nebo na konci tecku, vraci TRUE, jinak FALSE +// Checks the last component of the name in 'path'. If it starts or ends with a +// space or ends with a dot the function returns TRUE; otherwise FALSE BOOL FileNameInvalidForManualCreate(const char* path); -// oriznuti mezer na zacatku a na konci jmena (CutWS nebo StripWS nebo CutWhiteSpace nebo StripWhiteSpace) -// vraci TRUE pokud doslo k orezu +// Trims spaces from the beginning and end of the path (CutWS or StripWS or CutWhiteSpace or StripWhiteSpace) +// Returns TRUE if any trimming occurred BOOL CutSpacesFromBothSides(char* path); -// oriznuti mezer na zacatku a mezer a tecek na konci jmena, dela to tak Explorer -// a lidi tlacili, ze to tak taky chteji, viz https://forum.altap.cz/viewtopic.php?f=16&t=5891 -// a https://forum.altap.cz/viewtopic.php?f=2&t=4210 -// vraci TRUE pokud se zmeni obsah 'path' +// Trims leading spaces and trailing spaces or dots in the same way Explorer does +// because users requested this behavior, see https://forum.altap.cz/viewtopic.php?f=16&t=5891 +// and https://forum.altap.cz/viewtopic.php?f=2&t=4210. Returns TRUE if 'path' was modified BOOL MakeValidFileName(char* path); -// pokud 'name' konci na mezeru/tecku, udela se kopie 'name' do 'nameCopy' a doplni -// se na konec '\\', pak se 'name' nasmeruje do 'nameCopy'; bezne API funkce -// orezavaji tise mezery/tecky z konce cesty a pracuji pak s jinymi soubory/adresari -// nez chceme, pridany '\\' na konci to resi +// If 'name' ends with a space or dot a copy of 'name' is made to 'nameCopy' and +// a '\\' is appended. 'name' is then redirected to 'nameCopy'. Standard API +// functions silently trim trailing spaces or dots and operate on other +// files/directories than intended; adding '\\' at the end fixes that void MakeCopyWithBackslashIfNeeded(const char*& name, char (&nameCopy)[3 * MAX_PATH]); -// vraci TRUE pokud jmeno konci na backslash ('\\' pridany na konci resi invalidni jmena) +// Returns TRUE if the name ends with a backslash (the added '\\' fixes invalid names) BOOL NameEndsWithBackslash(const char* name); -// pokud 'name' konci na mezeru/tecku nebo obsahuje ':' (kolize s ADS), vraci TRUE, jinak FALSE, -// je-li 'ignInvalidName' TRUE, vraci TRUE jen pokud 'name' obsahuje ':' (kolize s ADS) +// Returns TRUE if 'name' ends with a space/dot or contains ':' (ADS conflict), otherwise FALSE. +// When 'ignInvalidName' is TRUE, returns TRUE only if 'name' contains ':' (ADS conflict) BOOL FileNameIsInvalid(const char* name, BOOL isFullName, BOOL ignInvalidName = FALSE); -// vraci FALSE, pokud obsazene komponenty cesty konci na mezeru/tecku -// a je-li 'cutPath' TRUE, zaroven cestu zkrati k prvni invalidni komponente -// (pro chybove hlaseni), jinak vraci TRUE +// Returns FALSE if any component of the path ends with a space or dot. When +// 'cutPath' is TRUE the path is shortened to the first invalid component (for an +// error message). Otherwise returns TRUE BOOL PathContainsValidComponents(char* path, BOOL cutPath); -// vytvoreni adresare se jmenem 'name' pres klasicke volani Win32 API -// CreateDirectory(lpSecurityAttributes==NULL); tato metoda resi kolizi 'name' -// s dosovym nazvem jiz existujiciho souboru/adresare (jen pokud nejde i o -// kolizi s dlouhym jmenem souboru/adresare) - zajisti zmenu dosoveho jmena -// tak, aby se adresar se jmenem 'name' mohl vytvorit (zpusob: docasne prejmenuje -// konfliktni soubor/adresar na jine jmeno a po vytvoreni 'name' ho -// prejmenuje zpet); dale resi jmena koncici na mezery (umi je vytvorit, narozdil -// od CreateDirectory, ktera mezery bez varovani orizne a vytvori tak vlastne -// jiny adresar); vraci TRUE pri uspechu, pri chybe FALSE (vraci v 'err' -// (neni-li NULL) kod Windows chyby) +// creates a directory called 'name' using the standard CreateDirectory API +// (lpSecurityAttributes==NULL). The function resolves collisions with an +// existing DOS name (provided the long name itself does not collide) by +// temporarily renaming the conflicting item so the directory can be created and +// then restoring the original name. It also supports names ending with spaces, +// which CreateDirectory would otherwise trim. Returns TRUE on success or FALSE +// on failure. If 'err' is not NULL it receives the Windows error code. BOOL SalCreateDirectoryEx(const char* name, DWORD* err); -void InitLocales(); // nutne volat pres pouzitim NumberToStr a PrintDiskSize -char* NumberToStr(char* buffer, const CQuadWord& number); // prevod int -> prehlednejsi string, !char buffer[50]! -int NumberToStr2(char* buffer, const CQuadWord& number); // prevod int -> prehlednejsi string, !char buffer[50]!, vraci pocet znaku nakopirovanych do bufferu -char* GetErrorText(DWORD error); // prevadi cislo chyby na string -WCHAR* GetErrorTextW(DWORD error); // prevadi cislo chyby na string -BOOL IsDirError(DWORD err); // tyka se chyba prace s adresari ? +void InitLocales(); // must be called before NumberToStr and PrintDiskSize +char* NumberToStr(char* buffer, const CQuadWord& number); // converts integer to a more readable string, !char buffer[50]! +int NumberToStr2(char* buffer, const CQuadWord& number); // converts an integer to a more readable string, !char buffer[50]!, returns the number of characters written to the buffer +char* GetErrorText(DWORD error); // converts error code to a string +WCHAR* GetErrorTextW(DWORD error); // converts error code to a wide string +BOOL IsDirError(DWORD err); // does the error relate to directories? -// normal i UNC cesty: maji stejny root? +// regular and UNC paths: do they share the same root? BOOL HasTheSameRootPath(const char* path1, const char* path2); -// zjisti, jestli maji obe cesty stejny root a jsou z jednoho svazku (resi -// cesty obsahujici reparse pointy a substy) -// POZOR: jde o dost POMALOU funkci (az 200ms) +// checks whether both paths have the same root and lie on the same volume +// (handles paths containing reparse points and SUBST drives) +// WARNING: this function can be quite slow (up to 200 ms) BOOL HasTheSameRootPathAndVolume(const char* p1, const char* p2); -// vraci TRUE, pokud jsou cesty 'path1' a 'path2' ze stejneho svazku; v 'resIsOnlyEstimation' -// (neni-li NULL) vraci TRUE, pokud neni vysledek jisty (jisty je jen v pripade, ze se -// podarilo ziskat "volume name" (GUID) u obou cest, coz pripada v uvahu jen pro lokalni -// cesty pod W2K nebo novejsimi z rady NT) -// POZOR: jde o dost POMALOU funkci (az 200ms) +// returns TRUE if 'path1' and 'path2' are on the same volume; if 'resIsOnlyEstimation' +// is not NULL it is set to TRUE when the result is only an estimation (certain only +// when the "volume name" GUID could be obtained for both paths, which is possible +// only for local paths under Windows 2000 or newer) +// WARNING: this function can be quite slow (up to 200 ms) BOOL PathsAreOnTheSameVolume(const char* path1, const char* path2, BOOL* resIsOnlyEstimation); -// porovna dve cesty: ignore-case, ignoruje take jeden backslash na zacatku a konci cest +// compares two paths: case-insensitive and ignoring a single backslash at the start and end BOOL IsTheSamePath(const char* path1, const char* path2); -// zjisti, jestli je cesta typu plugin FS, 'path' je zjistovana cesta, 'fsName' je -// buffer MAX_PATH znaku pro jmeno FS (nebo NULL), vraci 'userPart' (je-li != NULL) - ukazatel -// do 'path' na prvni znak pluginem definovane cesty (za prvni ':') +// Determines whether 'path' is a plugin FS path; 'path' is the path to check, +// 'fsName' is a MAX_PATH buffer for the FS name (or NULL); returns in 'userPart' +// (if not NULL) a pointer into 'path' to the first character of the plugin-defined path (after the first ':') BOOL IsPluginFSPath(const char* path, char* fsName = NULL, const char** userPart = NULL); BOOL IsPluginFSPath(char* path, char* fsName = NULL, char** userPart = NULL); -// test, jestli jde o cestu s URL, napr. "file:///c|/WINDOWS/clock.avi" = "c:\\WINDOWS\\clock.avi" +// test whether the path is a URL, e.g. "file:///c|/WINDOWS/clock.avi" becomes "c:\\WINDOWS\\clock.avi" BOOL IsFileURLPath(const char* path); -// zjisti podle pripony souboru, jestli jde o link (.lnk, .pif nebo .url); je-li, vraci 1, -// jinak vraci 0 +// determines from a file extension whether it is a shortcut (.lnk, .pif or .url); +// returns 1 for shortcuts or 0 otherwise int IsFileLink(const char* fileExtension); -// ziska UNC i normalni root cestu z 'path', v 'root' vraci cestu ve formatu 'C:\' nebo '\\SERVER\SHARE\', -// vraci pocet znaku root cesty (bez null-terminatoru); 'root' je buffer aspon MAX_PATH znaku, pri delsi -// UNC root ceste dojde k orezu na MAX_PATH-2 znaku a doplneni backslashe (stejne to na 100% neni root cesta) +// obtains the UNC or drive root from 'path'; 'root' receives it in the form +// "C:\\" or "\\SERVER\\SHARE\\". The function returns the number of characters +// in the root (without the null terminator). If the UNC root is longer it is +// truncated to MAX_PATH-2 characters and a trailing backslash is added because +// such a string cannot be a real root int GetRootPath(char* root, const char* path); -// vraci ukazatel za root (presneji na backslash hned za rootem) UNC i normalni cesty 'path' +// returns a pointer just after the root (specifically to the backslash) of a +// UNC or standard path const char* SkipRoot(const char* path); -// vraci TRUE pokud se podari 'path' (UNC i normal cesta) zkratit o posledni adresar -// (zariznuti na poslednim backslashi - v oriznute ceste zustava na konci backslash jen u 'c:\'), -// v 'cutDir' se vraci ukazatel na posledni adresar (odriznutou cast) -// nahrazka za PathRemoveFileSpec +// returns TRUE if `path` (UNC or regular path) can be shortened by removing the last +// directory (cut at the last backslash; the shortened path retains a trailing backslash +// only for paths like "c:\"), `cutDir` returns a pointer to the last directory +// (the removed part) +// replacement for PathRemoveFileSpec BOOL CutDirectory(char* path, char** cutDir = NULL); -// spoji 'path' a 'name' do 'path', zajisti spojeni backslashem, 'path' je buffer alespon 'pathSize' znaku -// vraci TRUE pokud se 'name' veslo za 'path'; je-li 'path' nebo 'name' prazdne, -// spojovaci (pocatecni/ukoncovaci) backslash nebude (napr. "c:\" + "" -> "c:") +// concatenates 'name' to 'path' ensuring a single backslash separator. 'path' +// must hold at least 'pathSize' characters. Returns TRUE if 'name' fits; if +// either parameter is empty no separator is added (e.g. "c:\" + "" -> "c:") BOOL SalPathAppend(char* path, const char* name, int pathSize); -// pokud jeste 'path' nekonci na backslash, prida ho na konec 'path'; 'path' je buffer alespon 'pathSize' -// znaku; vraci TRUE pokud se backslash vesel za 'path'; je-li 'path' prazdne, backslash se neprida +// if 'path' does not already end with a backslash, appends one to the end of 'path'; 'path' is a buffer of at least 'pathSize' +// characters; returns TRUE if the backslash fits after 'path'; if 'path' is empty, no backslash is added BOOL SalPathAddBackslash(char* path, int pathSize); -// pokud je v 'path' na konci backslash, odstrani ho +// removes a trailing backslash from 'path' if present void SalPathRemoveBackslash(char* path); -// prevede vsechny '/' na '\\' a zaroven pokud jsou za sebou dva nebo vice '\\', -// necha jen jeden (krome dvou '\\' na zacatku stringu, coz oznacuje UNC cestu) +// converts all '/' characters to '\\' and collapses repeated '\\' to a single one +// except for the two leading characters that denote a UNC path void SlashesToBackslashesAndRemoveDups(char* path); -// z plneho jmena udela jmeno ("c:\path\file" -> "file") +// extracts the file name from a full path ("c:\\path\\file" -> "file") void SalPathStripPath(char* path); -// pokud je ve jmene pripona, odstrani ji +// removes the file extension if one is present void SalPathRemoveExtension(char* path); -// pokud ve jmenu 'path' jeste neni pripona, prida priponu 'extension' (napr. ".txt"), 'path' je buffer -// alespon 'pathSize' znaku, vraci FALSE pokud buffer 'path' nestaci pro vyslednou cestu +// if 'path' has no extension yet, append 'extension' (for example ".txt"). +// 'path' must hold at least 'pathSize' characters; returns FALSE when the buffer +// is not large enough for the resulting string BOOL SalPathAddExtension(char* path, const char* extension, int pathSize); -// zmeni/prida priponu 'extension' (napr. ".txt") ve jmenu 'path', 'path' je buffer -// alespon 'pathSize' znaku, vraci FALSE pokud buffer 'path' nestaci pro vyslednou cestu +// changes or adds the extension 'extension' (for example ".txt") in 'path'. +// 'path' must hold at least 'pathSize' characters; returns FALSE if the buffer +// is not large enough for the resulting string BOOL SalPathRenameExtension(char* path, const char* extension, int pathSize); -// vraci ukazatel do 'path' na jmeno souboru/adresare (backslash na konci 'path' ignoruje), -// pokud jmeno neobsahuje jine backslashe nez na konci retezce, vraci 'path' +// returns a pointer into 'path' pointing to the file or directory name. A +// trailing backslash is ignored. If there are no other backslashes the function +// simply returns 'path' const char* SalPathFindFileName(const char* path); -// Pracuje pro normalni i UNC cesty. -// Vrati pocet znaku spolecne cesty. Na normalni ceste musi byt root ukonceny zpetnym -// lomitkem, jinak funkce vrati 0. ("C:\"+"C:"->0, "C:\A\B"+"C:\"->3, "C:\A\B\"+"C:\A"->4, -// "C:\AA\BB"+"C:\AA\CC"->5) +// Works for both regular and UNC paths. +// Returns the number of characters common to both paths. For a regular path the +// root must end with a backslash, otherwise the function returns 0. Examples: +// "C:\"+"C:"->0, "C:\A\B"+"C:\"->3, "C:\A\B\"+"C:\A"->4, +// "C:\AA\BB"+"C:\AA\CC"->5 int CommonPrefixLength(const char* path1, const char* path2); -// Vraci TRUE, pokud je cesta 'prefix' zakladem cesty 'path'. Jinak vraci FALSE. +// Returns TRUE if the path 'prefix' is a prefix of the path 'path'. Otherwise returns FALSE. // "C:\aa","C:\Aa\BB"->TRUE // "C:\aa","C:\aaa"->FALSE // "C:\aa\","C:\Aa"->TRUE // "\\server\share","\\server\share\aaa"->TRUE -// Pracuje pro normalni i UNC cesty. +// Works with both regular and UNC paths. BOOL SalPathIsPrefix(const char* prefix, const char* path); -// odstrani ".." (vynecha ".." spolu s jednim podadresarem vlevo) a "." (vynecha jen ".") -// z cesty; podminkou je backslash jako oddelovac podadresaru; 'afterRoot' ukazuje za root -// zpracovavane cesty (zmeny cesty se deji jen za 'afterRoot'); vraci TRUE pokud se upravy -// podarily, FALSE pokud se nedaji odstranit ".." (vlevo uz je root) +// Removes ".." (together with one directory to the left) and "." (only the "." itself) +// from a path; backslashes must be used as directory separators; 'afterRoot' points past the +// root of the processed path (the path is modified only after 'afterRoot'); returns TRUE if the +// adjustments succeed, or FALSE if ".." cannot be removed because the root has already been reached BOOL SalRemovePointsFromPath(char* afterRoot); BOOL SalRemovePointsFromPath(WCHAR* afterRoot); -// upravuje relativni nebo absolutni cestu na absolutni bez '.', '..' a koncoveho backslashe (krom -// "X:\"); je-li 'curDir' NULL, relativni cesty typu "\path" a "path" vraci chybu (neurcitelne), jinak je -// 'curDir' platna upravena aktualni cesta (UNC i normal); aktualni cesty ostatnich disku (mimo -// 'curDir'; jen normal, ne UNC) jsou v DefaultDir (pred pouzitim je dobre zavolat -// CMainWindow::UpdateDefaultDir); 'name' - in/out buffer alespon MAX_PATH znaku (jeho velikost je v 'nameBufSize'); -// neni-li 'nextFocus' NULL a zadana relativni cesta neobsahuje backslash - strcpy(nextFocus, name) -// vraci TRUE - jmeno 'name' je pripraveno k pouziti, jinak neni-li 'errTextID' NULL obsahuje -// chybu (konstanty pro LoadStr - IDS_SERVERNAMEMISSING, IDS_SHARENAMEMISSING, IDS_TOOLONGPATH, -// IDS_INVALIDDRIVE, IDS_INCOMLETEFILENAME, IDS_EMPTYNAMENOTALLOWED a IDS_PATHISINVALID); -// v 'callNethood' (neni-li NULL) se vraci TRUE ma-li se volat Nethood plugin pri chybach -// IDS_SERVERNAMEMISSING a IDS_SHARENAMEMISSING, je-li 'allowRelPathWithSpaces' TRUE, neoreze -// mezery ze zacatku relativni cesty (bezne dela, aby si lidi nevytvareli omylem nazvy s mezerami -// na zacatku, mezery a tecky na konci orezou wokna) -// vraci TRUE pokud v ceste neni chyba, jinak se vraci FALSE (napr. "\\\" nebo "\\server\\") +// Converts a relative or absolute path to an absolute path without '.', '..', or a trailing +// backslash (except for "X:\"); if 'curDir' is NULL, relative paths such as "\\path" and "path" +// return an error (they cannot be resolved); otherwise, 'curDir' must be a valid normalized +// current path (UNC or regular); current paths of other drives (except 'curDir'; regular only, +// not UNC) are in DefaultDir (it is advisable to call CMainWindow::UpdateDefaultDir before use); +// 'name' is an in/out buffer of at least MAX_PATH characters (its size is in 'nameBufSize'); +// if 'nextFocus' is not NULL and the specified relative path contains no backslash, +// strcpy(nextFocus, name) is called +// Returns TRUE: the name in 'name' is ready for use; otherwise, if 'errTextID' is not NULL, it +// contains the error (constants for LoadStr: IDS_SERVERNAMEMISSING, IDS_SHARENAMEMISSING, +// IDS_TOOLONGPATH, IDS_INVALIDDRIVE, IDS_INCOMLETEFILENAME, IDS_EMPTYNAMENOTALLOWED, and +// IDS_PATHISINVALID); TRUE is returned in 'callNethood' (if not NULL) if the Nethood plugin should +// be called for IDS_SERVERNAMEMISSING and IDS_SHARENAMEMISSING; if 'allowRelPathWithSpaces' is +// TRUE, leading spaces are not trimmed from a relative path (normally they are, to prevent users +// from accidentally creating names with leading spaces; Windows trims trailing spaces and dots) +// Returns TRUE if the path contains no error, otherwise FALSE (e.g. "\\\" or "\\server\\") BOOL SalGetFullName(char* name, int* errTextID = NULL, const char* curDir = NULL, char* nextFocus = NULL, BOOL* callNethood = NULL, int nameBufSize = MAX_PATH, BOOL allowRelPathWithSpaces = FALSE); -// zkusi pristup na cestu 'path' (normal nebo UNC), probiha ve vedlejsim threadu, takze -// umoznuje prerusit zkousku klavesou ESC (po jiste dobe vybali okenko s hlasenim o ESC) -// 'echo' TRUE znamena povoleny vypis chybove hlasky (pokud cesta nebude pristupna); -// 'err' ruzne od ERROR_SUCCESS v kombinaci s 'echo' TRUE pouze zobrazi chybu (na cestu -// se jiz nepristupuje); 'postRefresh' je parametr do volani EndStopRefresh (normalne TRUE); -// 'parent' je parent messageboxu; vraci ERROR_SUCCESS v pripade, ze je cesta v poradku, -// jinak vraci standardni Windowsovy kod chyby nebo ERROR_USER_TERMINATED v pripade, ze -// user pouzil klavesu ESC k preruseni testu +// tries to access the 'path' (regular or UNC) in a worker thread so +// the attempt can be interrupted with the ESC key (after a while a +// message about the pressed ESC is shown) +// When 'echo' is TRUE an error message is displayed if the path is not +// accessible. If 'err' differs from ERROR_SUCCESS together with 'echo' TRUE, the +// error is shown and no additional check is performed. 'postRefresh' is passed +// to EndStopRefresh (normally TRUE). 'parent' is the parent message box. The +// function returns ERROR_SUCCESS when the path is valid or a standard Windows +// error code (or ERROR_USER_TERMINATED when ESC was pressed) otherwise. DWORD SalCheckPath(BOOL echo, const char* path, DWORD err, BOOL postRefresh, HWND parent); -// zkusi jestli je cesta 'path' pristupna, prip. obnovi sitova spojeni pomoci funkci -// CheckAndRestoreNetworkConnection a CheckAndConnectUNCNetworkPath; vraci TRUE pokud -// je cesta pristupna; 'parent' je parent messageboxu; 'tryNet' je TRUE pokud ma smysl -// zkouset obnovit sitova spojeni +// Tries to access 'path' and optionally restores network connections via +// CheckAndRestoreNetworkConnection and CheckAndConnectUNCNetworkPath. +// Returns TRUE when the path is accessible. 'parent' is the parent message box; +// 'tryNet' specifies whether attempting to restore the connection makes sense. BOOL SalCheckAndRestorePath(HWND parent, const char* path, BOOL tryNet); -// zkusi jestli je cesta 'path' pristupna, prip. ji zkrati; je-li 'tryNet' TRUE, prip. obnovi -// sitova spojeni pomoci funkci CheckAndRestoreNetworkConnection a CheckAndConnectUNCNetworkPath -// (je-li 'donotReconnect' TRUE, zjisti se pouze chyba, obnova spojeni uz se neprovede) a nastavi -// 'tryNet' na FALSE; vraci 'err' (kod chyby aktualni cesty), 'lastErr' (kod chyby vedouci ke -// zkraceni cesty), 'pathInvalid' (TRUE pokud se zkusila obnova sit. spojeni bez uspechu), -// 'cut' (TRUE pokud je vysledna cesta zkracena); 'parent' je parent messageboxu; vraci TRUE -// pokud je vysledna cesta 'path' pristupna +// Checks if 'path' is accessible and optionally shortens it. When 'tryNet' is +// TRUE, network connections can be restored using +// CheckAndRestoreNetworkConnection and CheckAndConnectUNCNetworkPath (unless +// 'donotReconnect' is TRUE, in which case the error is only reported). The +// function updates 'tryNet' to FALSE and returns 'err' (current path error), +// 'lastErr' (error that caused path shortening), 'pathInvalid' (TRUE when a +// network reconnection failed), and 'cut' (TRUE when the final path is shorter). +// 'parent' is the parent window. Returns TRUE if the resulting path is +// accessible. BOOL SalCheckAndRestorePathWithCut(HWND parent, char* path, BOOL& tryNet, DWORD& err, DWORD& lastErr, BOOL& pathInvalid, BOOL& cut, BOOL donotReconnect); -// rozpozna o jaky typ cesty (FS/windowsova/archiv) jde a postara se o rozdeleni na -// jeji casti (u FS jde o fs-name a fs-user-part, u archivu jde o path-to-archive a -// path-in-archive, u windowsovych cest jde o existujici cast a zbytek cesty), u FS cest -// se nic nekontroluje, u windowsovych (normal + UNC) cest se kontroluje kam az cesta existuje -// (prip. obnovi sitove spojeni), u archivu se kontroluje existence souboru archivu -// (rozliseni archivu dle pripony); pouziva SalGetFullName, proto je dobre napred zavolat -// CMainWindow::UpdateDefaultDir) -// 'path' je plna nebo relativni cesta (buffer min. 'pathBufSize' znaku; u relativnich cest se -// uvazuje aktualni cesta 'curPath' (neni-li NULL) jako zaklad pro vyhodnoceni plne cesty; -// 'curPathIsDiskOrArchive' je TRUE pokud je 'curPath' windowsova nebo archivova cesta; -// pokud je aktualni cesta archivova, obsahuje 'curArchivePath' jmeno archivu, jinak je NULL), -// do 'path' se ulozi vysledna plna cesta (musi byt min. 'pathBufSize' znaku); vraci TRUE pri -// uspesnem rozpoznani, pak 'type' je typ cesty (viz PATH_TYPE_XXX) a 'secondPart' je nastavene: -// - do 'path' na pozici za existujici cestu (za '\\' nebo na konci retezce; existuje-li -// v ceste soubor, ukazuje za cestu k tomuto souboru) (typ cesty windows), POZOR: neresi -// se delka vracene casti cesty (cela cesta muze byt delsi nez MAX_PATH) -// - za soubor archivu (typ cesty archiv), POZOR: neresi se delka cesty v archivu (muze byt -// delsi nez MAX_PATH) -// - za ':' za nazvem file-systemu - user-part cesty file-systemu (typ cesty FS), POZOR: neresi -// se delka user-part cesty (muze byt delsi nez MAX_PATH); -// pokud vraci TRUE je jeste 'isDir' nastavena na: -// - TRUE pokud existujici cast cesty je adresar, FALSE == soubor (typ cesty windows) -// - FALSE pro cesty typu archiv a FS; -// pokud vrati FALSE, userovi byla vypsana chyba (az na jednu vyjimku - viz popis SPP_INCOMLETEPATH), -// ktera pri rozpoznavani nastala (neni-li 'error' NULL, vraci se v nem jedna z konstant SPP_XXX); -// 'errorTitle' je titulek messageboxu s chybou; pokud je 'nextFocus' != NULL a windowsova/archivova -// cesta neobsahuje '\\' nebo na '\\' jen konci, nakopiruje se cesta do 'nextFocus' (viz SalGetFullName) +// Detects the path type (FS/Windows/archive) and splits it into parts. +// For FS paths, this means the file-system name and user part; for archive +// paths, the path to the archive file and the path inside the archive; for +// Windows paths, the existing part and the remainder of the path. FS paths are +// not checked; Windows paths (normal and UNC) are checked for how far the path +// exists, and the network connection is restored if needed. For archive paths, +// the existence of the archive file is checked (archives are distinguished by +// extension). This function uses SalGetFullName, so it is advisable to call +// CMainWindow::UpdateDefaultDir first. +// 'path' is a full or relative path (buffer of at least 'pathBufSize' chars; for +// relative paths, the current path 'curPath' is used as the base for resolving +// the full path, if it is not NULL; 'curPathIsDiskOrArchive' is TRUE if +// 'curPath' is a Windows or archive path; if the current path is an archive +// path, 'curArchivePath' contains the archive file name, otherwise it is NULL). +// The resulting full path is stored in 'path' (which must be at least +// 'pathBufSize' chars long). Returns TRUE on successful recognition; then +// 'type' is the path type (see PATH_TYPE_XXX) and 'secondPart' is set to: +// - in 'path', at the position after the existing path (after '\\' or at the +// end of the string; if the path contains a file, it points past the path to +// that file) (Windows path type); WARNING: the length of the returned part of +// the path is not handled (the whole path may be longer than MAX_PATH) +// - after the archive file (archive path type); WARNING: the length of the path +// inside the archive is not handled (it may be longer than MAX_PATH) +// - after ':' following the file-system name, i.e. to the user part of the +// file-system path (FS path type); WARNING: the length of the user part is +// not handled (it may be longer than MAX_PATH); +// if TRUE is returned, 'isDir' is also set to: +// - TRUE if the existing part of the path is a directory, FALSE if it is a file +// (Windows path type) +// - FALSE for archive and FS paths; +// if FALSE is returned, an error that occurred during recognition has already +// been shown to the user (with one exception; see the description of +// SPP_INCOMLETEPATH); if 'error' is not NULL, one of the SPP_XXX constants is +// returned in it. 'errorTitle' is the title of the error message box; if +// 'nextFocus' != NULL and the Windows/archive path does not contain '\\' or +// only ends with '\\', the path is copied to 'nextFocus' (see +// SalGetFullName). BOOL SalParsePath(HWND parent, char* path, int& type, BOOL& isDir, char*& secondPart, const char* errorTitle, char* nextFocus, BOOL curPathIsDiskOrArchive, const char* curPath, const char* curArchivePath, int* error, int pathBufSize); -// ziska z windowsove cilove cesty existujici cast a operacni masku; pripadnou neexistujici cast -// umozni vytvorit; pri uspechu vraci TRUE a existujici windowsovou cilovou cestu (v 'path') -// a nalezenou operacni masku (v 'mask' - ukazuje do bufferu 'path', ale cesta a maska jsou oddelene -// nulou; pokud v ceste neni maska, automaticky vytvori masku "*.*"); 'parent' - parent pripadnych -// messageboxu; 'title' + 'errorTitle' jsou titulky messageboxu s informaci + chybou; 'selCount' je -// pocet oznacenych souboru a adresaru; 'path' je na vstupu cilova cesta ke zpracovani, na vystupu -// (alespon 2 * MAX_PATH znaku) existujici cilova cesta; 'secondPart' ukazuje do 'path' na pozici -// za existujici cestu (za '\\' nebo na konec retezce; existuje-li v ceste soubor, ukazuje za cestu -// k tomuto souboru); 'pathIsDir' je TRUE/FALSE pokud existujici cast cesty je adresar/soubor; -// 'backslashAtEnd' je TRUE pokud byl pred provedenim "parse" na konci 'path' backslash (napr. -// SalParsePath takovy backslash rusi); 'dirName' + 'curDiskPath' nejsou NULL pokud je oznaceny -// max. jeden soubor/adresar (jeho jmeno bez cesty je v 'dirName'; pokud neni nic oznacene, bere -// se focus) a aktualni cesta je windowsova (cesta je v 'curDiskPath'); 'mask' je na vystupu -// ukazatel na operacni masku do bufferu 'path'; pokud je v ceste chyba, vraci metoda FALSE, -// problem uz byl uzivateli ohlasen +// obtains the existing part and operation mask from a Windows target path; allows any non-existent part +// to be created; on success returns TRUE, the existing Windows target path (in 'path') +// and the found operation mask (in 'mask' - it points into the 'path' buffer, but the path and mask are separated +// by a null character; if the path contains no mask, it automatically creates the mask "*.*"); 'parent' is the parent of any +// message boxes; 'title' + 'errorTitle' are the captions of the information + error message boxes; 'selCount' is +// the number of selected files and directories; 'path' is the input target path to process, on output +// (at least 2 * MAX_PATH characters) the existing target path; 'secondPart' points into 'path' to the position +// after the existing path (after '\\' or at the end of the string; if the path contains a file, it points after the path +// to that file); 'pathIsDir' is TRUE/FALSE if the existing part of the path is a directory/file; +// 'backslashAtEnd' is TRUE if there was a backslash at the end of 'path' before "parse" was performed (for example, +// SalParsePath removes such a backslash); 'dirName' + 'curDiskPath' are not NULL if at most one file/directory is selected +// (its name without the path is in 'dirName'; if nothing is selected, the focused item is used) +// and the current path is a Windows path (the path is in 'curDiskPath'); 'mask' is on output +// a pointer to the operation mask in the 'path' buffer; if the path contains an error, the method returns FALSE, +// the problem has already been reported to the user BOOL SalSplitWindowsPath(HWND parent, const char* title, const char* errorTitle, int selCount, char* path, char* secondPart, BOOL pathIsDir, BOOL backslashAtEnd, const char* dirName, const char* curDiskPath, char*& mask); -// ziska z cilove cesty existujici cast a operacni masku; pripadnou neexistujici cast rozpozna; pri -// uspechu vraci TRUE, relativni cestu k vytvoreni (v 'newDirs'), existujici cilovou cestu (v 'path'; -// existujici jen za predpokladu vytvoreni relativni cesty 'newDirs') a nalezenou operacni masku -// (v 'mask' - ukazuje do bufferu 'path', ale cesta a maska jsou oddelene nulou; pokud v ceste neni -// maska, automaticky vytvori masku "*.*"); 'parent' - parent pripadnych messageboxu; -// 'title' + 'errorTitle' jsou titulky messageboxu s informaci + chybou; 'selCount' je pocet oznacenych -// souboru a adresaru; 'path' je na vstupu cilova cesta ke zpracovani, na vystupu (alespon 2 * MAX_PATH -// znaku) existujici cilova cesta (vzdy konci backslashem); 'afterRoot' ukazuje do 'path' za root cesty -// (za '\\' nebo na konec retezce); 'secondPart' ukazuje do 'path' na pozici za existujici cestu (za -// '\\' nebo na konec retezce; existuje-li v ceste soubor, ukazuje za cestu k tomuto souboru); -// 'pathIsDir' je TRUE/FALSE pokud existujici cast cesty je adresar/soubor; 'backslashAtEnd' je -// TRUE pokud byl pred provedenim "parse" na konci 'path' backslash (napr. SalParsePath takovy -// backslash rusi); 'dirName' + 'curPath' nejsou NULL pokud je oznaceny max. jeden soubor/adresar -// (jeho jmeno bez cesty je v 'dirName'; jeho cesta je v 'curPath'; pokud neni nic oznacene, bere -// se focus); 'mask' je na vystupu ukazatel na operacni masku do bufferu 'path'; neni-li 'newDirs' NULL, -// pak jde o buffer (o velikosti alespon MAX_PATH) pro relativni cestu (vzhledem k existujici ceste -// v 'path'), kterou je nutne vytvorit (uzivatel s vytvorenim souhlasi, byl pouzit stejny dotaz jako -// u kopirovani z disku na disk; prazdny retezec = nic nevytvaret); je-li 'newDirs' NULL a je-li -// potreba vytvorit nejakou relativni cestu, je jen vypsana chyba; 'isTheSamePathF' je funkce pro -// porovnani dvou cest (potrebna jen pokud 'curPath' neni NULL), je-li NULL pouzije se IsTheSamePath; -// pokud je v ceste chyba, vraci metoda FALSE, problem uz byl uzivateli ohlasen +// Retrieves the existing part of the target path and the operation mask; also recognizes any non-existent part. On +// success, returns TRUE, the relative path to create (in 'newDirs'), the existing target path (in 'path'; valid only +// if the relative path 'newDirs' is created), and the found operation mask (in 'mask', which points into the 'path' +// buffer, with the path and mask separated by a zero; if the path contains no mask, the mask "*.*" is created +// automatically). 'parent' is the parent of any message boxes; 'title' and 'errorTitle' are the captions of the +// information and error message boxes; 'selCount' is the number of selected files and directories; 'path' is the +// target path to process on input and, on output (at least 2 * MAX_PATH characters), the existing target path (always +// ending with a backslash); 'afterRoot' points into 'path' past the path root (past '\\' or to the end of the +// string); 'secondPart' points into 'path' to the position after the existing path (past '\\' or to the end of the +// string; if the path contains a file, it points past the path to that file); 'pathIsDir' is TRUE/FALSE if the +// existing part of the path is a directory/file; 'backslashAtEnd' is TRUE if 'path' ended with a backslash before +// parsing (for example, SalParsePath removes such a backslash); 'dirName' and 'curPath' are non-NULL if at most one +// file/directory is selected (its name without the path is in 'dirName'; its path is in 'curPath'; if nothing is +// selected, the focused item is used); 'mask' receives a pointer to the operation mask in the 'path' buffer; if +// 'newDirs' is not NULL, it is a buffer (of size at least MAX_PATH) for the relative path (with respect to the +// existing path in 'path') that must be created (the user agrees to create it; the same prompt is used as when copying +// from disk to disk; an empty string means create nothing); if 'newDirs' is NULL and some relative path needs to be +// created, only an error is reported; 'isTheSamePathF' is a function for comparing two paths (needed only if 'curPath' +// is not NULL); if it is NULL, IsTheSamePath is used; if the path contains an error, the method returns FALSE and the +// problem has already been reported to the user BOOL SalSplitGeneralPath(HWND parent, const char* title, const char* errorTitle, int selCount, char* path, char* afterRoot, char* secondPart, BOOL pathIsDir, BOOL backslashAtEnd, const char* dirName, const char* curPath, char*& mask, char* newDirs, SGP_IsTheSamePathF isTheSamePathF); -// zjisti jestli je mozne retezec 'fileNameComponent' pouzit jako komponentu -// jmena na Windows filesystemu (resi retezce delsi nez MAX_PATH-4 (4 = "C:\" -// + null-terminator), prazdny retezec, retezce znaku '.', retezce white-spaces, -// znaky "*?\\/<>|\":" a jednoducha jmena typu "prn" a "prn .txt") +// tests whether the string 'fileNameComponent' can be used as a name component +// on a Windows filesystem (handles strings longer than MAX_PATH-4 (4 = "C:\\" +// + null terminator), an empty string, strings of '.' characters, strings of white-space, +// the characters "*?\\/<>|\":" and simple names such as "prn" and "prn .txt") BOOL SalIsValidFileNameComponent(const char* fileNameComponent); -// pretvori retezec 'fileNameComponent' tak, aby mohl byt pouzity jako komponenta -// jmena na Windows filesystemu (resi retezce delsi nez MAX_PATH-4 (4 = "C:\" -// + null-terminator), resi prazdny retezec, retezce znaku '.', retezce -// white-spaces, znaky "*?\\/<>|\":" nahradi '_' + jednoducha jmena typu "prn" -// a "prn .txt" doplni o '_' na konci nazvu); 'fileNameComponent' musi jit -// rozsirit alespon o jeden znak (maximalne se vsak z 'fileNameComponent' -// pouzije MAX_PATH bytu) +// transforms 'fileNameComponent' so it can be used as a Windows file name +// component (handles strings longer than MAX_PATH-4 (4 = "C:\\" + null terminator), +// empty strings, strings of '.', whitespace-only strings; characters "*?\\/<>|\":" +// are replaced with '_'; simple names like "prn" and "prn .txt" get an '_' +// appended at the end of the name); 'fileNameComponent' must be extendable by at +// least one character (but at most MAX_PATH bytes of 'fileNameComponent' are used) void SalMakeValidFileNameComponent(char* fileNameComponent); -// tisk velikosti mista na disku, mode==0 "1.23 MB", mode==1 "1 230 000 bytes, 1.23 MB", -// mode==2 "1 230 000 bytes", mode==3 (vzdy v celych KB), mode==4 (jako mode==0, ale vzdy -// aspon 3 platne cislice, napr. "2.00 MB") +// prints disk space size; mode==0 "1.23 MB", mode==1 "1 230 000 bytes, 1.23 MB", +// mode==2 "1 230 000 bytes", mode==3 (always whole KBs), mode==4 (like mode==0 but +// always at least 3 significant digits, e.g. "2.00 MB") char* PrintDiskSize(char* buf, const CQuadWord& size, int mode); -// prevadi pocet sekund na retezec ("5 sec", "1 hr 34 min", atp.); 'buf' je -// buffer pro vysledny text, musi byt velky aspon 100 znaku; 'secs' je pocet sekund; -// vraci 'buf' +// converts the number of seconds to a string ("5 sec", "1 hr 34 min", etc.); +// 'buf' is the output buffer (at least 100 chars); 'secs' is the number of seconds. +// returns 'buf' char* PrintTimeLeft(char* buf, CQuadWord const& secs); -// zdvojuje '&' - hodi se pro cesty zobrazovane v menu ('&&' se zobrazi jako '&'); -// 'buffer' je vstupne/vystupni retezec, 'bufferSize' je velikost 'buffer' v bytech; -// vraci TRUE pokud zdvojenim nedoslo ke ztrate znaku z konce retezce (buffer byl dost -// veliky) +// duplicates '&' - useful for paths shown in menus ('&&' displays as '&'); +// 'buffer' is an in/out string, 'bufferSize' its size in bytes. +// returns TRUE if doubling did not truncate the string (buffer was large enough) BOOL DuplicateAmpersands(char* buffer, int bufferSize, BOOL skipFirstAmpersand = FALSE); -// likviduje '&' - hodi se pro prikazy z menu, ktere potrebujeme zobrazit ocistene -// od horkych klaves; najde-li dvojici "&&", nahradi ji jednim znakem '&' -// 'text' je vstupne/vystupni retezec +// Removes '&' characters. Useful for menu commands that should be displayed +// without hot-key markers; if a double "&&" is found it is replaced with a +// single '&'. 'text' is an input/output string. void RemoveAmpersands(char* text); -// zdvojuje '\\' - hodi se pro texty, ktere posilame do LookForSubTexts, ktera '\\\\' -// zase zredukuje na '\\'; 'buffer' je vstupne/vystupni retezec, 'bufferSize' je velikost -// 'buffer' v bytech; vraci TRUE pokud zdvojenim nedoslo ke ztrate znaku z konce retezce -// (buffer byl dost veliky) +// Duplicates '\\'. Useful for strings passed to LookForSubTexts, which reduces +// "\\\\" back to "\\". 'buffer' is both input and output; 'bufferSize' is its +// size in bytes. Returns TRUE if doubling did not truncate the string (buffer +// was large enough). BOOL DuplicateBackslashes(char* buffer, int bufferSize); -// zdvojuje '$' - slouzi pro import starych cest (hotpaths), ktere mohou obsahovat $(SalDir) -// a nove na nich podporuje Sal/Env promenne jako napriklad $(SalDir) nebo $(WinDir) -// behem zavadeni jsem narazil na to, ze 2.5RC1, kde jsme podporili tyto promenne pro editory, -// viewery, archivery se tato expanze nedelala; dodatecne to neresim, zavedu konverzi pouze -// pro HotPaths -// 'buffer' je vstupne/vystupni retezec, 'bufferSize' je velikost 'buffer' v bytech; -// vraci TRUE pokud zdvojenim nedoslo ke ztrate znaku z konce retezce (buffer byl dost -// veliky) +// Duplicates '$'. Used when importing old paths (HotPaths), which may +// contain $(SalDir) and now support Sal/Env variables such as $(SalDir) or +// $(WinDir). In 2.5RC1 this expansion was not done for editors, viewers, or +// archivers; this conversion is added only for HotPaths. +// 'buffer' is the input/output string, 'bufferSize' is the size of 'buffer' in +// bytes. Returns TRUE if doubling did not truncate the string (the buffer was +// large enough). BOOL DuplicateDollars(char* buffer, int bufferSize); -// najde si v 'buf' jmeno (preskoci mezery na zacatku i konci) a pokud existuje ('buf' -// neobsahuje jen mezery), neni v uvozovkach a obsahuje aspon jednu mezeru, da ho do -// uvozovek; vraci FALSE pokud neni dost mista na pridani uvozovek ('bufSize' je -// velikost 'buf') +// Searches 'buf' for a name (trimming spaces at both ends). If the name exists, +// is not quoted and contains at least one space, it is wrapped in quotes. The +// function returns FALSE when there is not enough room to add the quotes +// ('bufSize' specifies the buffer size). BOOL AddDoubleQuotesIfNeeded(char* buf, int bufSize); -// oriznuti '"' na zacatku a na konci 'path' (CutDoubleQuotes nebo StripDoubleQuotes nebo CutQuotes nebo StripQuotes) -// vraci TRUE pokud doslo k orezu +// trims '"' at the beginning and end of 'path' (CutDoubleQuotes or StripDoubleQuotes or +// CutQuotes or StripQuotes). Returns TRUE if trimming occurred BOOL CutDoubleQuotesFromBothSides(char* path); -// do 1/5 sekundy pockame na pusteni ESC (aby se po ESC v dialogu hned neprerusilo -// napr. cteni listingu v panelu) +// wait up to 1/5 second for ESC to be released so that the dialog does not +// immediately abort operations such as reading a panel listing void WaitForESCRelease(); -// zkontroluje jestli je root-parent okna 'parent' foreground window, pokud ne, -// udela se FlashWindow(root-parent, TRUE) a vrati se root-parent, jinak se vraci NULL +// checks whether the root parent of 'parent' is the foreground window; if not +// FlashWindow(root-parent, TRUE) is called and root-parent is returned, +// otherwise NULL is returned HWND GetWndToFlash(HWND parent); -// projde v threadu 'tid' (0=aktualni) vsechna okna (EnumThreadWindows) a vsem enablovanym a -// viditelnym dialogum (class name "#32770") vlastnenym oknem 'parent' postne WM_CLOSE; -// pouziva se pri critical shutdown k odblokovani okna/dialogu, nad kterym jsou otevrene -// modalni dialogy, hrozi-li vice vrstev, je nutne volat opakovane +// walks through all windows of thread 'tid' (0 means current) with +// EnumThreadWindows and posts WM_CLOSE to every enabled visible dialog +// (class name "#32770") owned by 'parent'. Used during critical shutdown to +// unblock windows when multiple layers of modal dialogs are open; call +// repeatedly if more layers appear void CloseAllOwnedEnabledDialogs(HWND parent, DWORD tid = 0); -// vraci zobrazitelnou podobu atributu souboru/adresare; 'text' je buffer aspon 10 znaku; -// 'attrs' jsou atributy souboru/adresare +// returns a displayable form of file or directory attributes; 'text' must be a +// buffer of at least 10 characters; 'attrs' are the attributes to format void GetAttrsString(char* text, DWORD attrs); -// nakopiruje retezec 'srcStr' za retezec 'dstStr' (za jeho koncovou nulu); -// 'dstStr' je buffer o velikosti 'dstBufSize' (musi byt nejmene rovno 2); -// pokud se do bufferu oba retezce nevejdou, jsou zkraceny (vzdy tak, aby se -// veslo co nejvice znaku z obou retezu) +// Copies 'srcStr' after the terminating zero of 'dstStr'. +// 'dstStr' is a buffer of size 'dstBufSize' (must be at least 2). +// If both strings do not fit, they are truncated so that as many characters as +// possible from both strings are kept. void AddStrToStr(char* dstStr, int dstBufSize, const char* srcStr); -// vytvori plne jmeno souboru (alokovane); pokud neni 'dosName' NULL a 'path'+'name' je prilis -// dlouhe jmeno, zkusi se spojit 'path'+'dosName'; pokud 'skip', 'skipAll' a 'sourcePath' nejsou -// NULL a dojde k chybe "prilis dlouhe jmeno", umozni uzivateli toto jmeno preskocit (v tomto pripade -// vraci NULL a ve 'skip' TRUE), pokud user da "Skip All", nastavi 'skipAll' na TRUE -// 'sourcePath' je pouzita pro Focus tlacitko (v panelu zobrazime prilis dlouhou komponentu ve zdrojove -// ceste, ktera by v cilove ceste zpusobila problem). +// Creates and returns an allocated full file name. If 'dosName' is not NULL and +// 'path'+'name' is too long, it tries 'path'+'dosName'. If 'skip', 'skipAll', +// and 'sourcePath' are not NULL and a "name too long" error occurs, the user +// can skip this name (the function then returns NULL and sets 'skip' to TRUE). +// If the user selects "Skip All", 'skipAll' is set to TRUE. 'sourcePath' is +// used for the Focus button (the panel shows the too-long component in the +// source path that would cause the problem in the target path). char* BuildName(char* path, char* name, char* dosName = NULL, BOOL* skip = NULL, BOOL* skipAll = NULL, const char* sourcePath = NULL); -// vraci z panelu datum+cas pro soubor/adresar 'f' (resi i datumy+casy dodavane pluginy - nemusi -// byt platne) +// retrieves the date and time for file/directory 'f' from the panel (also handles +// values supplied by plugins-they may be invalid) void GetFileDateAndTimeFromPanel(DWORD validFileData, CPluginDataInterfaceEncapsulation* pluginData, const CFileData* f, BOOL isDir, SYSTEMTIME* st, BOOL* validDate, BOOL* validTime); -// vraci z panelu velikost pro soubor/adresar 'f' (resi i velikosti dodavane pluginy - nemusi -// byt platne) +// retrieves the size for file/directory 'f' from the panel (also handles sizes +// supplied by plugins-they may be invalid) void GetFileSizeFromPanel(DWORD validFileData, CPluginDataInterfaceEncapsulation* pluginData, const CFileData* f, BOOL isDir, CQuadWord* size, BOOL* validSize); void DrawSplitLine(HWND HWindow, int newDragSplitX, int oldDragSplitX, RECT client); -BOOL InitializeCheckThread(); // inicializace threadu pro CFilesWindow::CheckPath() -void ReleaseCheckThreads(); // uvolneni threadu pro CFilesWindow::CheckPath() -void InitDefaultDir(); // inicializace pole DefaultDir (posledni navstivene cesty na vsech drivech) - -// zobrazi/schova zpravu ve vlastnim threadu (neodcerpa message-queue), zobrazi najednou jen -// jednu zpravu, opakovane volani ohlasi chybu do TRACE (neni fatalni), 'delay' je zpozdeni -// pred otevrenim okenka (od okamziku volani CreateSafeWaitWindow) -// 'message' muze byt vicerakova; jednotlive radky se oddeluji znakem '\n' -// 'caption' muze byt NULL: pouzije se pak "Open Salamander" -// 'showCloseButton' udava, zda bude okenko obsahovat tlacitko Close -// 'hForegroundWnd' urcuje okno, ktere musi byt aktivni, aby bylo okenko zobrazeno -// a zaroven urcuje okno, ktere bude aktivovana pri kliknuti do wait okenka +BOOL InitializeCheckThread(); // initializes the thread used by CFilesWindow::CheckPath() +void ReleaseCheckThreads(); // releases the thread used by CFilesWindow::CheckPath() +void InitDefaultDir(); // initializes the DefaultDir array (last visited paths for all drives) + +// shows or hides a message in its own thread without draining the message +// queue; only one message can be displayed at a time. Repeated calls report +// an error to TRACE (non-fatal). 'delay' is the delay before the window is +// opened (counted from the call to CreateSafeWaitWindow). +// 'message' may span multiple lines; individual lines are separated by '\n'. +// 'caption' may be NULL; in that case, the caption "Open Salamander" is used. +// 'showCloseButton' specifies whether the window contains a Close button. +// 'hForegroundWnd' specifies the window that must be active for the wait window +// to be shown and the window that will be activated when the wait window is clicked. void CreateSafeWaitWindow(const char* message, const char* caption, int delay, BOOL showCloseButton, HWND hForegroundWnd); void DestroySafeWaitWindow(BOOL killThread = FALSE); -// zhasne 'show'==FALSE a pak zobrazi 'show'==TRUE vytvorene okenko -// volat jako reakci na WM_ACTIVATE z okna hForegroundWnd: +// hides the created window when 'show'==FALSE and shows it when 'show'==TRUE. +// Call in response to WM_ACTIVATE from the hForegroundWnd window: // case WM_ACTIVATE: // { // ShowSafeWaitWindow(LOWORD(wParam) != WA_INACTIVE); // break; // } -// Pokud je thread (ze ktereho bylo okenko vytvoreno) zamestnan, nedochazi -// k distribuci zprav, takze nedojde ani k doruceni WM_ACTIVATE pri kliknuti -// na jinou aplikaci. Zpravy se doruci az ve chvili zobrazeni messageboxu, -// coz presne potrebujeme: docasne se nechame schovat a pozdeji (po zavreni -// messageboxu a aktivaci okna hForegroundWnd) zase zobrazit. +// If the thread that created the window is busy, messages are not dispatched, +// so WM_ACTIVATE is not delivered when the user clicks another application. The +// messages are delivered only when the message box is shown, which is what we +// need: hide temporarily and show again later (after the message box is closed +// and the hForegroundWnd window is activated). void ShowSafeWaitWindow(BOOL show); -// po zavolani CreateSafeWaitWindow nebo ShowSafeWaitWindow vraci funkce FALSE az do doby, -// kdy user kliknul mysi na Close tlacitko (pokud je zobrazeno); pak vraci TRUE +// after calling CreateSafeWaitWindow or ShowSafeWaitWindow the function returns +// FALSE until the user clicks the Close button (if shown); then it returns TRUE BOOL GetSafeWaitWindowClosePressed(); -// vraci TRUE pokud uzivatel macka ESC nebo kliknul mysi na Close tlacitko +// returns TRUE if the user is pressing ESC or clicked the Close button BOOL UserWantsToCancelSafeWaitWindow(); -// slouzi pro dodatecnou zmenu textu v okenku -// POZOR: nedochazi k novemu layoutovani okna a pokud dojde k vetsimu natazeni -// textu, bude orezan; pouzivat napriklad pro countdown: 60s, 55s, 50s, ... +// Used to change the message text later. NOTE: the window layout is not +// recomputed; if the text grows it will be truncated. Useful for countdowns +// like 60s, 55s, 50s, ... void SetSafeWaitWindowText(const char* message); -// vraci TRUE pokud je Salamander aktivni (foreground window PID == current PID) +// returns TRUE when Salamander is active (foreground window PID == current PID) BOOL SalamanderActive(); -// odstraneni adresare vcetne jeho obsahu (SHFileOperation je priserne pomaly) +// removes a directory along with its contents (SHFileOperation is terribly slow) void RemoveTemporaryDir(const char* dir); -// pomocna funkce pro pridani jmena do seznamu jmen (oddelenych mezerou), vraci uspech +// helper for adding a name to a space-separated list; returns success BOOL AddToListOfNames(char** list, char* listEnd, const char* name, int nameLen); -// pokud adresar neexistuje, umozni jej vytvorit, -// pokud adresar existuje nebo je uspesne vytvoren vraci TRUE -// parent je parent messageboxu s chybami, NULL = hlavni okno Salamandera -// quiet = TRUE - neptat se jestli chce vytvaret, ale pozor, chyby ukazuje pokud errBuf == NULL -// pokud errBuf != NULL, je errBufSize velikost bufferu pro popis chyby, -// pokud newDir != NULL, je v newDir vracen prvni vytvoreny podadresar (plnou cestou), -// pokud cesta komplet existuje, je newDir=="", newDir ukazuje na buffer o velikosti MAX_PATH -// noRetryButton = TRUE - chybove dialogy nemaji obsahovat Retry/Cancel buttony, ale jen OK button -// manualCrDir = TRUE - nedovolime vytvorit adresar s mezerou na zacatku (pri rucnim vytvareni -// adresare, jinak Windowsum mezery na zacatku nevadi) +// if the directory does not exist, the user can create it; +// returns TRUE if the directory exists or is created successfully +// 'parent' is the parent window for error message boxes; NULL = Salamander's main window +// quiet = TRUE - do not ask whether to create it, but note that errors are shown if errBuf == NULL +// if errBuf != NULL, errBufSize is the size of the error-description buffer +// if newDir != NULL, the first created subdirectory (full path) is returned in 'newDir' +// if the full path already exists, newDir==""; newDir points to a buffer of size MAX_PATH +// noRetryButton = TRUE - error dialogs contain only an OK button, not Retry/Cancel +// manualCrDir = TRUE - do not allow creating a directory with a leading space (during manual +// directory creation; otherwise Windows allows leading spaces) BOOL CheckAndCreateDirectory(const char* dir, HWND parent = NULL, BOOL quiet = FALSE, char* errBuf = NULL, int errBufSize = 0, char* newDir = NULL, BOOL noRetryButton = FALSE, BOOL manualCrDir = FALSE); -// smaze z disku prazdne podadresare v 'dir' a je-li 'dir' po vymazu podadresaru prazdny, -// je smazan take +// removes empty subdirectories under 'dir' and deletes 'dir' itself when it becomes empty void RemoveEmptyDirs(const char* dir); -// vykona rutina pro otevirani vieweru - pouziva se v CFilesWindow::ViewFile a -// CSalamanderForViewFileOnFS::OpenViewer; dalsi vyuziti se neocekava, proto nejsou -// popsany parametry a navratove hodnoty +// routine used to open the viewer-used in CFilesWindow::ViewFile and +// CSalamanderForViewFileOnFS::OpenViewer; no other use is expected, therefore +// parameters and return values are not documented BOOL ViewFileInt(HWND parent, const char* name, BOOL altView, DWORD handlerID, BOOL returnLock, HANDLE& lock, BOOL& lockOwner, BOOL addToHistory, int enumFileNamesSourceUID, int enumFileNamesLastFileIndex); -// prevede string ('str' o delce 'len') na unsigned __int64 (muze predchazet -// znamenko '+'; ignoruje white-spaces na zacatku a konci retezce); -// neni-li 'isNum' NULL, vraci se v nem TRUE, pokud cely retezec -// 'str' reprezentuje cislo +// converts the string ('str' of length 'len') to unsigned __int64 (a leading +// '+' sign is allowed; leading and trailing white-space is ignored); +// if 'isNum' is not NULL it receives TRUE when the entire string represents +// a number unsigned __int64 StrToUInt64(const char* str, int len, BOOL* isNum = NULL); -// spousti handler exceptiony "in-page-error" a "access violation - read/write on XXX" (testuje se -// jestli se exceptiona vztahuje k souboru - 'fileMem' je pocatecni adresa, 'fileMemSize' je velikost -// aktualniho view mapovaneho souboru), pouzito pri mapovani souboru do pameti (chyba -// cteni/zapisu vyvola tuto exceptionu) +// handles the "in-page-error" and "access violation - read/write on XXX" exceptions +// (checks whether the exception is related to the file: 'fileMem' is the base address, +// 'fileMemSize' is the size of the current mapped file view); used when mapping files +// into memory (a read/write error raises one of these exceptions) int HandleFileException(EXCEPTION_POINTERS* e, char* fileMem, DWORD fileMemSize); struct CSalamanderVarStrEntry; -// ValidateVarString a ExpandVarString: -// metody pro overovani a expanzi retezcu s promennymi ve tvaru "$(var_name)", "$(var_name:num)" -// (num je sirka promenne, jde o ciselnou hodnotu od 1 do 9999), "$(var_name:max)" ("max" je -// symbol, ktery oznacuje, ze sirka promenne se ridi hodnotou v poli 'maxVarWidths', podrobnosti -// u ExpandVarString) a "$[env_var]" (expanduje hodnotu promenne prostredi); pouziva se pokud si -// uzivatel muze zadat format retezce (jako napr. v info-line) priklad retezce s promennymi: -// "$(files) files and $(dirs) directories" - promenne 'files' a 'dirs' - -// kontroluje syntaxi 'varText' (retezce s promennymi), vraci FALSE pokud najde chybu, jeji -// pozici umisti do 'errorPos1' (offset zacatku chybne casti) a 'errorPos2' (offset konce chybne -// casti); 'variables' je pole struktur CSalamanderVarStrEntry, ktere je ukonceno strukturou s -// Name==NULL; 'msgParent' je parent message-boxu s chybami, je-li NULL, chyby se nevypisuji +// ValidateVarString and ExpandVarString: +// methods for validating and expanding strings with variables like "$(var_name)", +// "$(var_name:num)" (num is the field width, numeric 1..9999), "$(var_name:max)" +// ("max" means the width follows the value in 'maxVarWidths'; details with +// ExpandVarString) and "$[env_var]" for environment variables. +// Used where the user can define a format string (e.g. in the info line). Example +// string with variables: "$(files) files and $(dirs) directories" where +// the variables are 'files' and 'dirs'. + +// checks the syntax of 'varText' (string with variables); returns FALSE on error and +// provides the error position in 'errorPos1' (start offset) and 'errorPos2' (end offset). +// 'variables' is an array of CSalamanderVarStrEntry terminated with Name==NULL. +// 'msgParent' is the parent of error message boxes; if NULL, errors are not displayed BOOL ValidateVarString(HWND msgParent, const char* varText, int& errorPos1, int& errorPos2, const CSalamanderVarStrEntry* variables); -// naplni 'buffer' vysledkem expanze 'varText' (retezce s promennymi), vraci FALSE pokud je -// 'buffer' maly (predpoklada overeni retezce s promennymi pres ValidateVarString, jinak -// vraci FALSE i pri chybe syntaxe) nebo uzivatel kliknul na Cancel pri chybe environment-variable -// (nenalezena nebo prilis velka); 'bufferLen' je velikost bufferu 'buffer'; -// 'variables' je pole struktur CSalamanderVarStrEntry, ktere je ukonceno strukturou -// s Name==NULL; 'param' je ukazatel, ktery se predava do CSalamanderVarStrEntry::Execute -// pri expanzi nalezene promenne; 'msgParent' je parent message-boxu s chybami, je-li NULL, -// chyby se nevypisuji; je-li 'ignoreEnvVarNotFoundOrTooLong' TRUE, ignoruji se chyby -// environment-variable (nenalezena nebo prilis velka), je-li FALSE, zobrazi se messagebox -// s chybou; neni-li 'varPlacements' NULL, ukazuje na pole DWORDu o '*varPlacementsCount' polozkach, -// ktere bude naplneno DWORDy slozenymi vzdy z pozice promenne ve vystupnim bufferu (spodni WORD) -// a poctu znaku promenne (horni WORD); neni-li 'varPlacementsCount' NULL, vraci se v nem pocet -// naplnenych polozek v poli 'varPlacements' (jde vlastne o pocet promennych ve vstupnim -// retezci); -// pokud se tato metoda pouziva jen k expanzi retezce pro jednu hodnotu 'param', meli by -// byt nastaveny 'detectMaxVarWidths' na FALSE, 'maxVarWidths' na NULL a 'maxVarWidthsCount' -// na 0; pokud se ovsem pouziva tato metoda pro expanzi retezce opakovane pro urcitou -// mnozinu hodnot 'param' (napr. u Make File List je to expanze radky postupne pro vsechny -// oznacene soubory a adresare), ma smysl pouzivat i promenne ve tvaru "$(varname:max)", -// u techto promennych se sirka urci jako nejvetsi sirka expandovane promenne v ramci cele -// mnoziny hodnot; omereni nejvetsi sirky expandovane promenne se provadi v prvnim cyklu -// (pro vsechny hodnoty mnoziny) volani ExpandVarString, v prvnim cyklu ma parametr -// 'detectMaxVarWidths' hodnotu TRUE a pole 'maxVarWidths' o 'maxVarWidthsCount' polozkach -// je predem nulovane (slouzi pro ulozeni maxim mezi jednotlivymi volanimi ExpandVarString); -// samotna expanze pak probiha v druhem cyklu (pro vsechny hodnoty mnoziny) volani -// ExpandVarString, v druhem cyklu ma parametr 'detectMaxVarWidths' hodnotu FALSE a pole -// 'maxVarWidths' o 'maxVarWidthsCount' polozkach obsahuje predpocitane nejvetsi sirky -// (z prvniho cyklu) +// fills 'buffer' with the result of expanding 'varText'; returns FALSE if the +// buffer is too small (the variable string should be validated first via +// ValidateVarString, otherwise FALSE is also returned for syntax errors) or when +// the user clicked Cancel for an environment-variable error (not found or too +// long). 'bufferLen' is the size of 'buffer'. 'variables' is an array of +// CSalamanderVarStrEntry structures terminated by Name==NULL. 'param' is passed +// to CSalamanderVarStrEntry::Execute when expanding a variable. 'msgParent' is +// the parent for error message boxes; if NULL, errors are not shown. When +// 'ignoreEnvVarNotFoundOrTooLong' is TRUE, environment-variable errors are +// ignored; otherwise a message box is shown. If 'varPlacements' is not NULL it +// points to an array of DWORDs of '*varPlacementsCount' items that receives the +// variable positions in the output buffer (low WORD) and their lengths (high +// WORD). If 'varPlacementsCount' is not NULL it receives the number of filled +// entries. +// When this method is used just once for a single 'param', set +// 'detectMaxVarWidths' to FALSE, 'maxVarWidths' to NULL and 'maxVarWidthsCount' +// to 0. When expanding repeatedly for a set of values (e.g. Make File List), it +// makes sense to use variables like "$(varname:max)"; their width is measured as +// the maximum width of the expanded variable across the whole set. Measuring is +// done during the first cycle (for all values) with 'detectMaxVarWidths' TRUE +// and 'maxVarWidths' zeroed. The actual expansion then happens in the second +// cycle with 'detectMaxVarWidths' FALSE and 'maxVarWidths' containing the +// precomputed widths from the first cycle. BOOL ExpandVarString(HWND msgParent, const char* varText, char* buffer, int bufferLen, const CSalamanderVarStrEntry* variables, void* param, BOOL ignoreEnvVarNotFoundOrTooLong = FALSE, @@ -704,40 +713,40 @@ BOOL ExpandVarString(HWND msgParent, const char* varText, char* buffer, int buff BOOL detectMaxVarWidths = FALSE, int* maxVarWidths = NULL, int maxVarWidthsCount = 0); -// ulozi na clipboard Unicode verzi textu str o delce len znaku -// vraci ERROR_SUCCESS nebo GetLastError +// stores the Unicode version of 'str' of length 'len' on the clipboard +// returns ERROR_SUCCESS or GetLastError DWORD AddUnicodeToClipboard(const char* str, int len); -// vrzne text na clipboard; pokud showEcho, zobrazi message box, ze jako OK -// pokud je textLen==-1, napocita si delku sam +// puts text on the clipboard; if showEcho is TRUE a message box confirming success is shown +// when textLen==-1 the length is calculated automatically BOOL CopyTextToClipboard(const char* text, int textLen = -1, BOOL showEcho = FALSE, HWND hEchoParent = NULL); BOOL CopyTextToClipboardW(const wchar_t* text, int textLen = -1, BOOL showEcho = FALSE, HWND hEchoParent = NULL); BOOL CopyHTextToClipboard(HGLOBAL hGlobalText, int textLen = -1, BOOL showEcho = FALSE, HWND hEchoParent = NULL); -// zjisti z bufferu 'pattern' o delce 'patternLen' jestli jde o text (existuje kodova stranka, -// ve ktere obsahuje jen povolene znaky - zobrazitelne a ridici) a pokud jde o text, zjisti take -// jeho kodovou stranku (nejpravdepodobnejsi); 'parent' je parent messageboxu; je-li 'forceText' -// TRUE, neprovadi se kontrola na nepovolene znaky (pouziva se, pokud 'pattern' obsahuje text); -// neni-li 'isText' NULL, vraci se v nem TRUE pokud jde o text; neni-li 'codePage' NULL, jde -// o buffer (min. 101 znaku) pro jmeno kodove stranky (nejpravdepodobnejsi) +// examines buffer 'pattern' of length 'patternLen' to determine whether it is text (that is, +// whether there is a code page in which it contains only allowed characters - printable and control). +// If it is text, it also determines its most probable code page. 'parent' is the parent of the +// message box. When 'forceText' is TRUE, forbidden characters are not checked (used when 'pattern' +// contains text). If 'isText' is not NULL it receives TRUE if the buffer is text. If 'codePage' +// is not NULL, it is a buffer (at least 101 chars) for the code page name void RecognizeFileType(HWND parent, const char* pattern, int patternLen, BOOL forceText, BOOL* isText, char* codePage); -// nastavi jmeno volajicimu threadu ve VC debuggeru +// sets the calling thread name in the VC debugger void SetThreadNameInVC(LPCSTR szThreadName); -// nastavi jmeno volajicimu threadu ve VC debuggeru a Trace Serveru +// sets the calling thread name in both the VC debugger and the Trace Server void SetThreadNameInVCAndTrace(const char* name); -// nacitani konfigurace +// configuration loading class CEditorMasks; class CViewerMasks; -// funkce spojene s drag&dropem a dalsimi shellovymi vecmi +// functions related to drag&drop and other shell tasks class CFilesWindow; -// operace shellu +// shell operations enum CShellAction { saLeftDragFiles, @@ -746,7 +755,7 @@ enum CShellAction saCopyToClipboard, saCutToClipboard, saProperties, - saPermissions, // stejne jako saProperties, jen se pokusi vybrat "security tab" + saPermissions, // same as saProperties but tries to activate the "security" tab }; class CCopyMoveData; @@ -767,7 +776,7 @@ BOOL MouseConfirmDrop(DWORD& effect, DWORD& defEffect, DWORD& grfKeyState); void DropEnd(BOOL drop, BOOL shortcuts, void* param, BOOL ownRutine, BOOL isFakeDataObject, int tgtType); void EnterLeaveDrop(BOOL enter, void* param); -// uklada na clipboard prefered drop effect a informaci o puvodu ze Salamandera +// stores the preferred drop effect on the clipboard and marks that it originated from Salamander void SetClipCutCopyInfo(HWND hwnd, BOOL copy, BOOL salObject); void ShellAction(CFilesWindow* panel, CShellAction action, BOOL useSelection = TRUE, @@ -776,194 +785,206 @@ void ExecuteAssociation(HWND hWindow, const char* path, const char* name); BOOL CanUseShellExecuteWndAsParent(const char* cmdName); -// zjisti jestli je soubor placeholder (online soubor ve OneDrive slozce), -// viz http://msdn.microsoft.com/en-us/library/windows/desktop/dn323738%28v=vs.85%29.aspx +// checks whether the file is a placeholder (an online file in a OneDrive folder), +// see http://msdn.microsoft.com/en-us/library/windows/desktop/dn323738%28v=vs.85%29.aspx BOOL IsFilePlaceholder(WIN32_FIND_DATA const* findData); -// pred otevrenim editoru nebo vieweru se placeholder prevadi na offline file, -// aby s nim umel viewer/editor pracovat +// before opening the editor or viewer, the placeholder is converted to an offline file +// so that the viewer/editor can work with it //BOOL MakeFileAvailOfflineIfOneDriveOnWin81(HWND parent, const char *name); -// nastavi prioritu threadu na normal a vyvola v try-except bloku menu->InvokeCommand() -// pred ukoncenim zase nastavi prioritu threadu na puvodni hodnotu +// sets the thread priority to normal and calls menu->InvokeCommand() in a try-except block; +// before exiting it restores the thread priority to its original value BOOL SafeInvokeCommand(IContextMenu2* menu, CMINVOKECOMMANDINFO& ici); -// pokud je 'hInstance' NULL, bude se cist z HLanguage; jinak z 'hInstance' -char* LoadStr(int resID, HINSTANCE hInstance = NULL); // taha string z resourcu -WCHAR* LoadStrW(int resID, HINSTANCE hInstance = NULL); // taha wide-string z resourcu +// if 'hInstance' is NULL strings are loaded from HLanguage; otherwise from 'hInstance' +char* LoadStr(int resID, HINSTANCE hInstance = NULL); // loads string from resources +WCHAR* LoadStrW(int resID, HINSTANCE hInstance = NULL); // loads wide-string from resources -// podpora pro tvorbu parametrizovanych textu (reseni jednotnych a mnoznych cisel -// v textech); 'lpFmt' je formatovaci retezec pro vysledny text - popis jeho formatu -// nasleduje; vysledny text se vraci v bufferu 'lpOut' o velikosti 'nOutMax' bytu; -// 'lpParArray' je pole parametru textu, 'nParCount' je pocet techto parametru; -// vraci delku vysledneho textu +// support for creating parameterized texts (handling singular and plural forms +// in text); 'lpFmt' is the format string for the resulting text - its format +// is described below; the resulting text is returned in the 'lpOut' buffer of +// size 'nOutMax' bytes; 'lpParArray' is the array of text parameters and +// 'nParCount' is the number of these parameters; returns the length of the +// resulting text // -// popis formatovaciho retezce: -// - na zacatku kazdeho formatovaciho retezce je signatura "{!}" -// - uznavaji se nasledujici escape sekvence pro potlaceni vyznamu specialnich -// znaku ve formatovacim retezci (znak backslashe v tomto popisu -// neni zdvojen): "\\" = "\", "\{" = "{", "\}" = "}", "\:" = ":" a "\|" = "|" -// - text, ktery neni ve slozenych zavorkach se do vysledneho retezce -// prenasi beze zmen (az na escape sekvence) -// - parametrizovany text je ve slozenych zavorkach -// - kazdy parametrizovany text pouziva jeden parametr z 'lpParArray' - jde -// o 64-bitovy unsigned int -// - parametrizovany text obsahuje ruzne vysledne texty pro ruzne intervaly -// hodnot parametru -// - jednotlive vysledne texty a meze intervalu se oddeluji znakem "|" -// - parametrizovany text "{}" se pouziva pro preskoceni jednoho parametru -// z pole 'lpParArray' (nevytvari zadny vystupni text) -// - pokud je na zacatku parametrizovaneho textu cislo nasledovane dvojteckou, -// jde o index parametru (od jedne az do poctu parametru), ktery se ma pouzit, -// pokud neni index uveden, prideli se automaticky (postupne od jedne az do -// poctu parametru) -// - pri zadani indexu parametru nedochazi ke zmene postupne prirazovaneho -// indexu, napr. v "{!}%d file{2:s|0||1|s} and %d director{y|1|ies}" se pro -// prvni parametrizovany text pouzije parametr s indexem 2 a pro druhy -// s indexem 1 -// - parametrizovanych textu se zadanym indexem je mozne pouzit libovolny pocet +// description of the format string: +// - every format string starts with the signature "{!}" +// - the following escape sequences are recognized to suppress the special +// meaning of characters in the format string (the backslash character in +// this description is not doubled): "\\" = "\", "\{" = "{", "\}" = "}", "\:" = ":" and "\|" = "|" +// - text outside curly braces is copied to the resulting string unchanged +// (except for escape sequences) +// - parameterized text is enclosed in curly braces +// - each parameterized text uses one parameter from 'lpParArray' - it is a +// 64-bit unsigned int +// - parameterized text contains different resulting texts for different +// parameter value ranges +// - individual resulting texts and range boundaries are separated by "|" +// - parameterized text "{}" is used to skip one parameter from 'lpParArray' +// (it produces no output text) +// - if a parameterized text starts with a number followed by a colon, it is +// the index of the parameter to use (from one up to the number of +// parameters); if no index is specified, it is assigned automatically +// (sequentially from one up to the number of parameters) +// - specifying a parameter index does not change the sequentially assigned +// index; for example, in "{!}%d file{2:s|0||1|s} and %d director{y|1|ies}" +// the first parameterized text uses parameter 2 and the second uses +// parameter 1 +// - any number of parameterized texts with an explicitly specified index may +// be used // -// priklady formatovacich retezcu: -// - "{!}director{y|1|ies}" pro hodnotu parametru od 0 do 1 (vcetne) bude -// "directory" a pro hodnotu od 2 do "nekonecna" (2^64-1) bude "directories" -// - "{!}soubo{rů|0|r|1|ry|4|rů}" pro hodnotu parametru 0 bude "souborů", -// pro 1 bude "soubor", pro 2 az 4 (vcetne) bude "soubory" a od 5 -// do "nekonecna" bude "souborů" +// examples of format strings: +// - "{!}director{y|1|ies}" for parameter values from 0 to 1 (inclusive) will +// be "directory", and for values from 2 to "infinity" (2^64-1) will be +// "directories" +// - keep the following Czech example unchanged: it documents the original +// plural grammar encoding and is intentionally not translated +// - "{!}soubo{rů|0|r|1|ry|4|rů}" for parameter value 0 will be "souborů", for +// 1 will be "soubor", for 2 to 4 (inclusive) will be "soubory", and from 5 +// to "infinity" will be "souborů" int ExpandPluralString(char* lpOut, int nOutMax, const char* lpFmt, int nParCount, const CQuadWord* lpParArray); // -// Do lpOut zapise retezec v zavislosti na promennych files a dirs: +// Writes the text to 'lpOut' depending on the 'files' and 'dirs' variables: // files > 0 && dirs == 0 -> XXX (selected/hidden) files // files == 0 && dirs > 0 -> YYY (selected/hidden) directories // files > 0 && dirs > 0 -> XXX (selected/hidden) files and YYY directories // -// kde XXX a YYY odpovidaji hodnotam promennych files a dirs. -// Promenna selectedForm ridi vlozeni slova selected +// where XXX and YYY correspond to the values of 'files' and 'dirs'. +// The variable 'selectedForm' controls insertion of the word "selected". // -// V forDlgCaption je TRUE/FALSE pokud text je/neni urceny pro titulek dialogu -// (v anglictine jsou nutna velka pocatecni pismena). +// 'forDlgCaption' is TRUE/FALSE if the text is meant for a dialog caption +// (capitalization is required in English). // -// Vrati pocet nakopirovanych znaku bez terminatoru. +// Returns the number of copied characters excluding the terminator. // -// popis konstant epfdmXXX viz spl_gen.h +// description of epfdmXXX constants is in spl_gen.h int ExpandPluralFilesDirs(char* lpOut, int nOutMax, int files, int dirs, int mode, BOOL forDlgCaption); int ExpandPluralBytesFilesDirs(char* lpOut, int nOutMax, const CQuadWord& selectedBytes, int files, int dirs, BOOL useSubTexts); -// V textu nalezne pary '<' '>', vyradi je z bufferu a prida odkazy na -// jejich obsah do 'varPlacements'. 'varPlacements' je pole DWORDu o '*varPlacementsCount' -// polozkach, DWORDy jsou slozene vzdy z pozice odkazu ve vystupnim bufferu (spodni WORD) -// a poctu znaku odkazu (horni WORD). Retezce "\<", "\>", "\\" jsou chapany -// jako escape sekvence a budou nahrazeny znaky '<', '>' a '\\'. -// Vraci TRUE v pripade uspechu, jinak FALSE; vzdy nastavi 'varPlacementsCount' na -// pocet zpracovanych promennych. +// Searches the text for '<' '>' pairs, removes them from the buffer, and stores +// references to their contents in 'varPlacements'. 'varPlacements' is an array of +// DWORDs with '*varPlacementsCount' items; each DWORD is composed of the position +// of the reference in the output buffer (low WORD) and the number of characters +// in the reference (high WORD). The strings "\<", "\>", "\\" are treated as +// escape sequences and are replaced with '<', '>' and '\\'. +// Returns TRUE on success, otherwise FALSE; always sets 'varPlacementsCount' to +// the number of processed variables. BOOL LookForSubTexts(char* text, DWORD* varPlacements, int* varPlacementsCount); -void MinimizeApp(HWND mainWnd); // minimalizace app. -void RestoreApp(HWND mainWnd, HWND dlgWnd); // obnova z minimized stavu app. - // meni format jmena (velikost pismen), filename musi byt vzdy terminovan znakem nula5 +void MinimizeApp(HWND mainWnd); // minimize the application +void RestoreApp(HWND mainWnd, HWND dlgWnd); // restore from minimized state + // adjusts the name format (letter case), filename must be null-terminated void AlterFileName(char* tgtName, char* filename, int filenameLen, int format, int change, BOOL dir); -// vraci string s velikosti a casy souboru; Ve 'fileTime' vraci cas, promenna muze byt NULL; -// neni-li 'getTimeFailed' NULL, zapise se do nej TRUE pri chybe ziskavani casu souboru +// returns a string with the file size and times; 'fileTime' receives the time (may be NULL); +// if 'getTimeFailed' is not NULL, it is set to TRUE on failure to obtain the file time void GetFileOverwriteInfo(char* buff, int buffLen, HANDLE file, const char* fileName, FILETIME* fileTime = NULL, BOOL* getTimeFailed = NULL); -void ColorsChanged(BOOL refresh, BOOL colorsOnly, BOOL reloadUMIcons); // volat po zmene barev -HICON GetDriveIcon(const char* root, UINT type, BOOL accessible, BOOL large = FALSE); // ikona drivu +void ColorsChanged(BOOL refresh, BOOL colorsOnly, BOOL reloadUMIcons); // call after color change +HICON GetDriveIcon(const char* root, UINT type, BOOL accessible, BOOL large = FALSE); // drive icon HICON SalLoadIcon(HINSTANCE hDLL, int id, int iconSize); -// SetCurrentDirectory(systemovy adresar) - odpojeni od adresare v panelu +// SetCurrentDirectory(system directory) - detach from panel directory void SetCurrentDirectoryToSystem(); -// nahradi substy v ceste 'resPath' jejich cilovymi cestami (prevod na cestu bez SUBST drive-letters); -// vraci FALSE pri chybe +// replaces SUBST drives in 'resPath' with their targets (converts to a path without SUBST drive letters); +// returns FALSE on error BOOL ResolveSubsts(char* resPath); -// Provede resolve substu a reparse pointu pro cestu 'path', nasledne se pro mount-point cesty -// (pokud chybi tak pro root cesty) pokusi ziskat GUID path. Pri neuspechu vrati FALSE. Pri -// uspechu, vrati TRUE a nastavi 'mountPoint' a 'guidPath' (pokud jsou ruzne od NULL, musi -// odkazovat na buffery o velikosti minimalne MAX_PATH; retezce budou zakonceny zpetnym lomitkem). +// Resolves SUBSTs and reparse points for 'path' and then tries to obtain the GUID path for +// the mount point (or for the root if missing). On failure returns FALSE. On success returns +// TRUE and sets 'mountPoint' and 'guidPath' (if not NULL, they must be buffers at least +// MAX_PATH in size; strings will end with a backslash). BOOL GetResolvedPathMountPointAndGUID(const char* path, char* mountPoint, char* guidPath); -// pokus o vraceni korektnich hodnot (umi i reparse pointy - zadava se komplet cesta misto rootu) +// attempts to return correct values (handles reparse points - specify the full path instead of the root) CQuadWord MyGetDiskFreeSpace(const char* path, CQuadWord* total = NULL); -// POZOR: nepouzivat navratovky 'lpNumberOfFreeClusters' a 'lpTotalNumberOfClusters', protoze u vetsich -// disku jsou v nich nesmysly (DWORD nemusi stacit pro celkovy pocet clusteru), resit pres -// MyGetDiskFreeSpace(path, total), ktera vraci 64-bitova cisla +// NOTE: do not use the return values 'lpNumberOfFreeClusters' and 'lpTotalNumberOfClusters' +// for large disks they may overflow. Use MyGetDiskFreeSpace(path, total) which returns 64-bit numbers. BOOL MyGetDiskFreeSpace(const char* path, LPDWORD lpSectorsPerCluster, LPDWORD lpBytesPerSector, LPDWORD lpNumberOfFreeClusters, LPDWORD lpTotalNumberOfClusters); -// vylepsena GetVolumeInformation: pracuje s cestou (prochazi reparse pointy a substy); -// v 'rootOrCurReparsePoint' (neni-li NULL, musi byt aspon MAX_PATH znaku) vraci bud -// root nebo cestu k aktualnimu (poslednimu) lokalnimu reparse pointu na ceste 'path' -// (POZOR: nefunguje pokud neni medium v drivu, GetCurrentLocalReparsePoint() timto netrpi); -// v 'junctionOrSymlinkTgt' (neni-li NULL, musi byt aspon MAX_PATH znaku) vraci -// cil aktualniho reparse pointu nebo prazdny retezec (pokud zadny reparse point neexistuje nebo -// je neznameho typu nebo jde o volume mount point); v 'linkType' (neni-li NULL) vraci typ aktualniho -// reparse pointu: 0 (neznamy nebo neexistuje), 1 (MOUNT POINT), 2 (JUNCTION POINT), 3 (SYMBOLIC LINK) +// enhanced GetVolumeInformation: works with the path (walks reparse points and SUBST drives) +// 'rootOrCurReparsePoint' (if not NULL and at least MAX_PATH chars) receives the +// root or the path to the current (last) local reparse point on 'path' +// (WARNING: this does not work if no medium is present in the drive; GetCurrentLocalReparsePoint() is not affected by this) +// 'junctionOrSymlinkTgt' (if not NULL and at least MAX_PATH chars) receives the +// target of the current reparse point or an empty string when none exists or it +// is of unknown type or a volume mount point. 'linkType' (if not NULL) receives +// the type of the current reparse point: 0 (unknown or none), 1 (MOUNT POINT), +// 2 (JUNCTION POINT), 3 (SYMBOLIC LINK) BOOL MyGetVolumeInformation(const char* path, char* rootOrCurReparsePoint, char* junctionOrSymlinkTgt, int* linkType, LPTSTR lpVolumeNameBuffer, DWORD nVolumeNameSize, LPDWORD lpVolumeSerialNumber, LPDWORD lpMaximumComponentLength, LPDWORD lpFileSystemFlags, LPTSTR lpFileSystemNameBuffer, DWORD nFileSystemNameSize); -// vraci cilovou cestu reparse pointu 'repPointDir' v bufferu 'repPointDstBuf' (neni-li NULL) -// o velikosti 'repPointDstBufSize'; 'repPointDir' a 'repPointDstBuf' muzou ukazovat -// do jednoho bufferu (IN/OUT buffer); je-li 'makeRelPathAbs' TRUE a jde o relativni -// symbolicky link, prevede cilovou cestu linku na absolutni; -// vraci TRUE pri uspechu + v 'repPointType' (neni-li NULL) vraci typ reparse pointu: -// 1 (MOUNT POINT), 2 (JUNCTION POINT), 3 (SYMBOLIC LINK) +// returns the target path of the reparse point 'repPointDir' in 'repPointDstBuf' +// (if not NULL) of size 'repPointDstBufSize'. 'repPointDir' and 'repPointDstBuf' +// may point into the same buffer (IN/OUT). If 'makeRelPathAbs' is TRUE and it is a +// relative symbolic link, the target path is converted to an absolute path. +// Returns TRUE on success and when 'repPointType' is not NULL it receives the +// reparse point type: 1 (MOUNT POINT), 2 (JUNCTION POINT), 3 (SYMBOLIC LINK) BOOL GetReparsePointDestination(const char* repPointDir, char* repPointDstBuf, DWORD repPointDstBufSize, int* repPointType, BOOL makeRelPathAbs); -// v 'currentReparsePoint' (aspon MAX_PATH znaku) vraci aktualni (posledni) lokalni -// reparse point, pri neuspechu vraci klasicky root; pri neuspechu vraci FALSE; neni-li -// 'error' NULL, zapise se do nej pri chybe TRUE +// 'currentReparsePoint' (at least MAX_PATH chars) receives the current (last) +// local reparse point; on failure the standard root is returned and the result +// is FALSE. If 'error' is not NULL it is set to TRUE when an error occurs. BOOL GetCurrentLocalReparsePoint(const char* path, char* currentReparsePoint, BOOL* error = NULL); -// volat jen pro cesty 'path', jejichz root (po odstraneni substu) je DRIVE_FIXED (jinde nema smysl hledat -// reparse pointy); hledame cestu bez reparse pointu, vedouci na stejny svazek jako 'path'; pro cestu -// obsahujici symlink vedouci na sitovou cestu (UNC nebo mapovanou) vracime jen root teto sitove cesty -// (ani Vista neumi delat s reparse pointy na sitovych cestach, takze to je nejspis zbytecne drazdit); -// pokud takova cesta neexistuje z duvodu, ze aktualni (posledni) lokalni reparse point je volume mount -// point (nebo neznamy typ reparse pointu), vracime cestu k tomuto volume mount pointu (nebo reparse -// pointu neznameho typu); pokud cesta obsahuje vice nez 50 reparse pointu (nejspis nekonecny cyklus), -// vracime puvodni cestu; +// call only for paths whose root (after removing SUBSTs) is DRIVE_FIXED (there is +// no point searching for reparse points elsewhere); we look for a path without +// reparse points that leads to the same volume as 'path'; for a path containing +// a symlink that leads to a network path (UNC or mapped), we return only the +// root of that network path (even Vista cannot work with reparse points on +// network paths, so this is probably unnecessary); if no such path exists +// because the current (last) local reparse point is a volume mount point (or an +// unknown type of reparse point), we return the path to this volume mount point +// (or reparse point of an unknown type); if the path contains more than 50 +// reparse points (most likely an infinite loop), we return the original path; // -// 'resPath' je buffer pro vysledek o velikosti MAX_PATH; 'path' je puvodni cesta; v 'cutResPathIsPossible' -// (nesmi byt NULL) vracime FALSE pokud vysledna cesta v 'resPath' obsahuje na konci reparse point (volume -// mount point nebo neznamy typ reparse pointu) a tudiz ji nesmime zkracovat (dostali bysme se tim nejspis -// na jiny svazek); je-li 'rootOrCurReparsePointSet' neNULLove a obsahuje-li FALSE a na puvodni ceste je -// aspon jeden lokalni reparse point (reparse pointy na sitove casti cesty ignorujeme), vracime v teto -// promenne TRUE + v 'rootOrCurReparsePoint' (neni-li NULL) vracime plnou cestu k aktualnimu (poslednimu -// lokalnimu) reparse pointu (pozor, ne kam vede); cilovou cestu aktualniho reparse pointu (jen je-li to -// junction nebo symlink) vracime v 'junctionOrSymlinkTgt' (neni-li NULL) + typ vracime v 'linkType': -// 2 (JUNCTION POINT), 3 (SYMBOLIC LINK); v 'netPath' (neni-li NULL) vracime sitovou cestu, na kterou -// vede aktualni (posledni) lokalni symlink v ceste - v teto situaci se root sitove cesty vraci v 'resPath' +// 'resPath' is a MAX_PATH-sized output buffer; 'path' is the original path; in +// 'cutResPathIsPossible' (must not be NULL) we return FALSE if the resulting +// path in 'resPath' ends with a reparse point (volume mount point or an unknown +// type of reparse point) and therefore must not be shortened (that would most +// likely take us to a different volume); if 'rootOrCurReparsePointSet' is not +// NULL and contains FALSE, and the original path contains at least one local +// reparse point (reparse points on the network part of the path are ignored), +// we return TRUE in this variable and in 'rootOrCurReparsePoint' (if not NULL) +// we return the full path to the current (last local) reparse point (note: not +// where it leads); the target path of the current reparse point (only if it is +// a junction or symlink) is returned in 'junctionOrSymlinkTgt' (if not NULL) +// and its type is returned in 'linkType': 2 (JUNCTION POINT), 3 (SYMBOLIC +// LINK); in 'netPath' (if not NULL) we return the network path to which the +// current (last) local symlink in the path leads - in this situation, the root +// of the network path is returned in 'resPath' void ResolveLocalPathWithReparsePoints(char* resPath, const char* path, BOOL* cutResPathIsPossible, BOOL* rootOrCurReparsePointSet, char* rootOrCurReparsePoint, char* junctionOrSymlinkTgt, int* linkType, char* netPath); -// vylepsena GetDriveType: pracuje s cestou (prochazi reparse pointy a substy) +// improved GetDriveType: works with a path and resolves reparse points and SUBSTs UINT MyGetDriveType(const char* path); -// nase vlastni QueryDosDevice -// 'driveNum' je 0-based (0=A: 2=C: ...) +// our own QueryDosDevice +// 'driveNum' is 0-based (0=A: 2=C: ...) BOOL MyQueryDosDevice(BYTE driveNum, char* target, int maxTarget); -// detekuje zda 'driveNum' (0=A: 2=C: ...) je substed a pokud ano, kam je pripojeny -// pokud drive neni substed, vraci FALSE -// pokud je substed, vraci TRUE a do promenne 'path' (o maximalni delce 'pathMax') -// ulozi cestu, kam je subst pripojeny -// pokud je 'path' NULL, cesta nebude vracena -// muze vratit cestu v UNC tvaru +// detects whether 'driveNum' (0=A: 2=C: ...) is SUBSTed and if so where it is mounted +// returns FALSE when the drive is not SUBSTed +// when SUBSTed, returns TRUE and stores the target path into 'path' +// (up to 'pathMax' characters). If 'path' is NULL the path is not returned. +// The returned path may be in UNC form. BOOL GetSubstInformation(BYTE driveNum, char* path, int pathMax); -// nahradi v retezci posledni znak '.' decimalnim separatorem ziskanym ze systemu LOCALE_SDECIMAL -// delka retezce muze narust, protoze separator muze mit podle MSDN az 4 znaky -// vraci TRUE, pokud byl buffer dostatecne veliky a operaci se povedlo dokoncit, jinak vraci FALSE +// replaces the last '.' in the string with the decimal separator from LOCALE_SDECIMAL +// the string may grow because the separator can have up to 4 characters according to MSDN +// returns TRUE if the buffer was large enough and the operation succeeded, otherwise FALSE BOOL PointToLocalDecimalSeparator(char* buffer, int bufferSize); typedef WINBASEAPI LONG(WINAPI* MY_FMExtensionProc)(HWND hwnd, @@ -971,52 +992,53 @@ typedef WINBASEAPI LONG(WINAPI* MY_FMExtensionProc)(HWND hwnd, LONG lParam); void GetMessagePos(POINT& p); -// Vrati handle ikony ziskany pomoci SHGetFileInfo nebo NULL v pripade neuspechu. -// Volajici je zodpovedny za destrukci ikony. Ikona je prirazena do HANDLES. +// Returns an icon handle obtained via SHGetFileInfo or NULL on failure. +// The caller is responsible for destroying the icon. The icon is assigned to HANDLES. HICON GetFileOrPathIconAux(const char* path, BOOL large, BOOL isDir); -// pokud je root UNCPath nepristupny (pro listing), zkusi navazat sitove spojeni, -// o jmeno a heslo uzivatele si rekne samo, vraci TRUE pokud bylo spojeni navazano, -// vraci FALSE pokud UNCPath neni UNC cesta nebo je root UNCPath pristupny nebo -// pokud se spojeni nepodarilo navazat, v 'pathInvalid' vraci TRUE pokud user prerusil -// dialog zadani jmena+hesla nebo jsme neuspesne zkusili navazat spojeni (napr. -// "credentials conflict"); je-li 'donotReconnect' TRUE, nezkousi se navazat sitove -// spojeni, vrati se rovnou, ze to nevyslo +// If the UNC root of `UNCPath` is inaccessible (for listing), tries to establish a +// network connection and prompts the user for credentials if needed. Returns TRUE +// if the connection is established. Returns FALSE if `UNCPath` is not a UNC path, +// if the UNC root is accessible, or if the connection could not be established. In +// `pathInvalid`, returns TRUE if the user cancelled the credentials dialog or if +// establishing the connection failed (e.g. "credentials conflict"). If +// `donotReconnect` is TRUE, no network connection is attempted and FALSE is +// returned immediately. BOOL CheckAndConnectUNCNetworkPath(HWND parent, const char* UNCPath, BOOL& pathInvalid, BOOL donotReconnect); -// pokusi se obnovit sitove spojeni (existovalo-li) na 'drive:', parent - predek dialogu, -// vraci TRUE pokud se obnova spojeni podarila (sit. disk je jiz opet namapovan) -// v 'pathInvalid' vraci TRUE pokud user prerusil dialog zadani jmena+hesla nebo -// jsme neuspesne zkusili navazat spojeni (napr. "credentials conflict") +// Attempts to restore a network connection (if it previously existed) on +// 'drive:'. 'parent' is the parent dialog. Returns TRUE if the connection was +// restored successfully (the network drive is mapped again). +// 'pathInvalid' returns TRUE if the user cancelled the username/password dialog +// or an attempt to establish the connection failed (e.g. "credentials conflict") BOOL CheckAndRestoreNetworkConnection(HWND parent, const char drive, BOOL& pathInvalid); -// funkce pro spravu threadu, pri ukoncovani procesu se tyto thready maji uzavrit, -// pokud to neudelaji sami, musi se terminovat +// thread management helpers-these threads should exit when the process ends; if +// they do not, they must be terminated void AddAuxThread(HANDLE view, BOOL testIfFinished = FALSE); void TerminateAuxThreads(); -// vrati TRUE, pokud specifikovany soubor existuje; jinak vrati FALSE +// returns TRUE if the specified file exists; otherwise FALSE extern "C" BOOL FileExists(const char* fileName); -// vrati TRUE, pokud specifikovany adresar existuje; jinak vrati FALSE +// returns TRUE if the specified directory exists; otherwise FALSE BOOL DirExists(const char* dirName); // tool tip -void SetCurrentToolTip(HWND hNotifyWindow, DWORD id, int showDelay = 0); // popis v tooltip.h -void SuppressToolTipOnCurrentMousePos(); // popis v tooltip.h +void SetCurrentToolTip(HWND hNotifyWindow, DWORD id, int showDelay = 0); // see tooltip.h +void SuppressToolTipOnCurrentMousePos(); // see tooltip.h -// zajisti skoky kurzoru pri Ctrl+Left/Right po zpetnych lomitkach a mezerach -// k editline nebo comboboxu priradi EditWordBreakProc -// je mozne zavolat napriklad v WM_INITDIALOG -// neni nutne odinstalovavat +// Makes Ctrl+Left/Right skip over backslashes and spaces. Assigns +// EditWordBreakProc to an edit line or combo box. Can be called from +// WM_INITDIALOG. Uninstalling is not required. BOOL InstallWordBreakProc(HWND hWindow); -// vymaze vsechny polozky z dropdown listboxu od comboboxu -// pouzivame pri promazavani historii +// removes all items from a combo box drop-down list +// used when clearing history void ClearComboboxListbox(HWND hCombo); -// struktura pro WM_USER_VIEWFILE a WM_USER_VIEWFILEWITH +// structure for WM_USER_VIEWFILE and WM_USER_VIEWFILEWITH struct COpenViewerData { char* FileName; @@ -1031,88 +1053,87 @@ struct COpenViewerData #define WM_USER_S_REFRESH_DIR WM_APP + 101 // [BOOL setRefreshEvent, time] #define WM_USER_SETDIALOG WM_APP + 103 // [CProgressData *data, 0] \ - // nebo [0, 0] - setprogress + // or [0, 0] - setprogress #define WM_USER_DIALOG WM_APP + 104 // [int dlgID, void *data] -// icon reader prave nacetl ikonu, vlozil ji do iconcache a rika to panelu -// bezicimu v hlavnim threadu, aby se mohl prekreslit a ikonku zazalohovat do asociaci -// index je dohledana pozice polozky v CFilesWindow::Files/Dirs +// the icon reader has loaded an icon and stored it in the icon cache; it notifies +// the panel running in the main thread so it can repaint and back up the icon in the associations +// 'index' is the located position of the item in CFilesWindow::Files/Dirs #define WM_USER_REFRESHINDEX WM_APP + 105 // [int index, 0] -#define WM_USER_END_SUSPMODE WM_APP + 106 // [0, 0] - rychlejsi aktivace okna +#define WM_USER_END_SUSPMODE WM_APP + 106 // [0, 0] - faster window activation #define WM_USER_DRIVES_CHANGE WM_APP + 107 // [0, 0] -#define WM_USER_ICON_NOTIFY WM_APP + 108 // [0, 0] - mysak je nad ikonkou v taskbare -#define WM_USER_EDIT WM_APP + 110 // [begin, end] oznac tento interval -#define WM_USER_SM_END_NOTIFY WM_APP + 111 // [0, 0] za 200ms naplanuje WM_USER_SM_END_NOTIFY_DELAYED -#define WM_USER_DISPLAYPOPUP WM_APP + 112 // [0, commandID] je treba vybali popupmenu -//#define WM_USER_SETPATHS WM_APP + 113 // nepouzivat, stara zprava, kterou nam teoreticky mohou stare aplikace zasilat +#define WM_USER_ICON_NOTIFY WM_APP + 108 // [0, 0] - the mouse pointer is over the icon in the taskbar +#define WM_USER_EDIT WM_APP + 110 // [begin, end] select this interval +#define WM_USER_SM_END_NOTIFY WM_APP + 111 // [0, 0] schedules WM_USER_SM_END_NOTIFY_DELAYED after 200ms +#define WM_USER_DISPLAYPOPUP WM_APP + 112 // [0, commandID] a popup menu should be displayed +//#define WM_USER_SETPATHS WM_APP + 113 // do not use, legacy message that old applications may theoretically send us -#define WM_USER_CHAR WM_APP + 114 // notifikace z listview +#define WM_USER_CHAR WM_APP + 114 // notification from list view // [command, index] -// command = 0 pro normalni konfiguraci, -// command = 1 pro otevreni stranky Hot Paths; index pak vyjadruje polozku -// command = 2 pro otevreni stranky User Menu -// command = 3 pro otevreni stranky Internal Viewer -// command = 4 pro otevreni stranky Views, index vyjadruje pohled -// command = 5 pro otevreni stranky Panels +// command = 0 for normal configuration +// command = 1 to open the Hot Paths page; 'index' specifies the item +// command = 2 to open the User Menu page +// command = 3 to open the Internal Viewer page +// command = 4 to open the Views page; 'index' specifies the view +// command = 5 to open the Panels page #define WM_USER_CONFIGURATION WM_APP + 115 #define WM_USER_MOUSEWHEEL WM_APP + 116 // [wParam, lParam] z WM_MOUSEWHEEL #define WM_USER_SKIPONEREFRESH WM_APP + 117 // [0, 0] za 500 ms SkipOneActivateRefresh = FALSE -#define WM_USER_FLASHWINDOW WM_APP + 118 // [0, 0] zablika oknem -#define WM_USER_SHOWWINDOW WM_APP + 119 // [0, 0] vytahne dopopredi okno (restorne, je-li treba) +#define WM_USER_FLASHWINDOW WM_APP + 118 // [0, 0] flashes the window +#define WM_USER_SHOWWINDOW WM_APP + 119 // [0, 0] brings the window to the foreground (restores if needed) #define WM_USER_DROPCOPYMOVE WM_APP + 120 // [CTmpDropData *, 0] -#define WM_USER_CHANGEDIR WM_APP + 121 // [convertFSPathToInternal, newDir] - panel zmeni svou cestu (vola ChangeDir) -#define WM_USER_FOCUSFILE WM_APP + 122 // [fileName, newPath] - panel zmeni svou cestu a vybere prislusny soubor -#define WM_USER_CLOSEFIND WM_APP + 123 // [0, 0] - zavola DestroyWindow z threadu find okna -#define WM_USER_SELCHANGED WM_APP + 124 // [0, 0] - notifikaci o zmene selectu +#define WM_USER_CHANGEDIR WM_APP + 121 // [convertFSPathToInternal, newDir] - the panel changes its path (calls ChangeDir) +#define WM_USER_FOCUSFILE WM_APP + 122 // [fileName, newPath] - the panel changes its path and selects the given file +#define WM_USER_CLOSEFIND WM_APP + 123 // [0, 0] - calls DestroyWindow from the find window thread +#define WM_USER_SELCHANGED WM_APP + 124 // [0, 0] - notification about selection change #define WM_USER_MOUSEHWHEEL WM_APP + 126 // [wParam, lParam] z WM_MOUSEHWHEEL -#define WM_USER_CLOSEMENU WM_APP + 130 // [0, 0] - interni pro menu - je treba se zavrit +#define WM_USER_CLOSEMENU WM_APP + 130 // [0, 0] - internal for menus - they must close -#define WM_USER_REFRESH_PLUGINFS WM_APP + 133 // [0, 0] - volat u FS Event(FSE_ACTIVATEREFRESH) -#define WM_USER_REFRESH_SHARES WM_APP + 134 // [0, 0] - snooper.cpp hlasi zmenu sharu v registry -#define WM_USER_PROCESSDELETEMAN WM_APP + 135 // [0, 0] - cache.cpp: DeleteManager - spusteni zpracovani novych dat v hl. threadu +#define WM_USER_REFRESH_PLUGINFS WM_APP + 133 // [0, 0] - call for FS Event(FSE_ACTIVATEREFRESH) +#define WM_USER_REFRESH_SHARES WM_APP + 134 // [0, 0] - snooper.cpp reports a change in shares in the registry +#define WM_USER_PROCESSDELETEMAN WM_APP + 135 // [0, 0] - cache.cpp: DeleteManager - start processing new data in the main thread -#define WM_USER_CANCELPROGRDLG WM_APP + 136 // [0, 0] - CProgressDlgArray: po doruceni teto zpravy do CProgressDialog dojde k cancelu operace (bez dotazu; zavre se dialog operace) -#define WM_USER_FOCUSPROGRDLG WM_APP + 137 // [0, 0] - CProgressDlgArray: po doruceni teto zpravy do CProgressDialog dojde aktivaci dialogu (nebo jeho popupu) -#define WM_USER_ICONREADING_END WM_APP + 138 // [0, 0] - notifikace o ukonceni nacitani ikonek v panelu +#define WM_USER_CANCELPROGRDLG WM_APP + 136 // [0, 0] - CProgressDlgArray: when this message arrives the operation is canceled (no prompt; the dialog closes) +#define WM_USER_FOCUSPROGRDLG WM_APP + 137 // [0, 0] - CProgressDlgArray: activates the dialog (or its popup) when received +#define WM_USER_ICONREADING_END WM_APP + 138 // [0, 0] - notification that icon reading in the panel has finished -//presunuto do shexreg.h (konstanta se nesmi zmenit): #define WM_USER_SALSHEXT_PASTE WM_APP + 139 // [postMsgIndex, 0] - SalamExt zada o provedeni prikazu Paste +// moved to shexreg.h (constant must not change): #define WM_USER_SALSHEXT_PASTE WM_APP + 139 // [postMsgIndex, 0] - SalamExt requests execution of the Paste command -#define WM_USER_DROPUNPACK WM_APP + 140 // [allocatedTgtPath, operation] - drag&drop z archivu: cilova cesta + operace zjistena, nechame provest unpack -#define WM_USER_PROGRDLGEND WM_APP + 141 // [cmd, 0] - CProgressDialog: pod W2K+ asi zbytecne: bypass bugy (zavrene dialogy zustavaly v taskbare) - zpozdene zavreni dialogu -#define WM_USER_PROGRDLGSTART WM_APP + 142 // [0, 0] - CProgressDialog: pod W2K+ asi zbytecne: bypass bugy (na obrazovce zustaval bordel po dialogu) - zpozdeny start worker threadu +#define WM_USER_DROPUNPACK WM_APP + 140 // [allocatedTgtPath, operation] - drag&drop from archive: target path and operation determined, perform unpack +#define WM_USER_PROGRDLGEND WM_APP + 141 // [cmd, 0] - CProgressDialog: workaround for bugs on W2K+ (closed dialogs remained in the taskbar) - delayed close of the dialog +#define WM_USER_PROGRDLGSTART WM_APP + 142 // [0, 0] - CProgressDialog: workaround for bugs on W2K+ (garbage left on screen) - delayed start of the worker thread -//presunuto do shexreg.h (konstanta se nesmi zmenit): #define WM_USER_SALSHEXT_TRYRELDATA WM_APP + 143 // [0, 0] - SalamExt hlasi odblokovani paste-dat (viz CSalShExtSharedMem::BlockPasteDataRelease), nejsou-li data dale chranena, nechame je zrusit +// moved to shexreg.h (constant must not change): #define WM_USER_SALSHEXT_TRYRELDATA WM_APP + 143 // [0, 0] - SalamExt reports release of the paste data lock (see CSalShExtSharedMem::BlockPasteDataRelease); if the data is no longer protected, let it be released -#define WM_USER_DROPFROMFS WM_APP + 144 // [allocatedTgtPath, operation] - drag&drop z FS: cilova cesta + operace zjistena, nechame provest copy/move z FS +#define WM_USER_DROPFROMFS WM_APP + 144 // [allocatedTgtPath, operation] - drag&drop from FS: target path and operation determined, perform copy/move from FS #define WM_USER_DROPTOARCORFS WM_APP + 145 // [CTmpDragDropOperData *, 0] #define WM_USER_SHCHANGENOTIFY WM_APP + 146 // message for SHChangeNotifyRegister [pidlList, SHCNE_xxx (event that occured)] -#define WM_USER_REFRESH_DIR_EX WM_APP + 147 // [long_wait, time] - za (long_wait?5000:200) ms posle WM_USER_REFRESH_DIR_EX_DELAYED +#define WM_USER_REFRESH_DIR_EX WM_APP + 147 // [long_wait, time] - after (long_wait ? 5000 : 200) ms sends WM_USER_REFRESH_DIR_EX_DELAYED -#define WM_USER_SETPROGRESS WM_APP + 148 // [progress, text] slouzi pro prekroceni threadu +#define WM_USER_SETPROGRESS WM_APP + 148 // [progress, text] used to cross thread boundaries -// icon reader prave nacetl icon-overlay a rika to panelu bezicimu v hlavnim threadu, aby -// se mohl prekreslit -// index je pozice polozky v CFilesWindow::Files/Dirs +// icon reader has just loaded an icon overlay and informs the panel running in the main thread so it can repaint +// index is the position of the item in CFilesWindow::Files/Dirs #define WM_USER_REFRESHINDEX2 WM_APP + 149 // [int index, 0] -#define WM_USER_DONEXTFOCUS WM_APP + 150 // [0, 0] - notifikace o zmene NextFocusName -#define WM_USER_CREATEWAITWND WM_APP + 151 // [parent or NULL, delay] - zprava pro thread safe-wait-message: "create && show" -#define WM_USER_DESTROYWAITWND WM_APP + 152 // [killThread, 0] - zprava pro thread safe-wait-message: "hide && destery" -#define WM_USER_SHOWWAITWND WM_APP + 153 // [show, 0] - zprava pro thread safe-wait-message: "show || hide" -#define WM_USER_SETWAITMSG WM_APP + 154 // [0, 0] - zprava pro thread safe-wait-message: byl zmenen text--prekresli se -#define WM_USER_REPAINTALLICONS WM_APP + 155 // [0, 0] - refresh ikon v obou panelech -#define WM_USER_REPAINTSTATUSBARS WM_APP + 156 // [0, 0] - refresh throbberu (dirline) v obou panelech +#define WM_USER_DONEXTFOCUS WM_APP + 150 // [0, 0] - notification that NextFocusName changed +#define WM_USER_CREATEWAITWND WM_APP + 151 // [parent or NULL, delay] - message for the safe wait message thread: "create && show" +#define WM_USER_DESTROYWAITWND WM_APP + 152 // [killThread, 0] - message for the safe wait message thread: "hide && destroy" +#define WM_USER_SHOWWAITWND WM_APP + 153 // [show, 0] - message for the safe wait message thread: "show || hide" +#define WM_USER_SETWAITMSG WM_APP + 154 // [0, 0] - message for the safe wait message thread: text changed-repaint +#define WM_USER_REPAINTALLICONS WM_APP + 155 // [0, 0] - refresh icons in both panels +#define WM_USER_REPAINTSTATUSBARS WM_APP + 156 // [0, 0] - refresh the throbber (dirline) in both panels -#define WM_USER_VIEWERCONFIG WM_APP + 158 // [hWnd, 0] - hWnd urcuje viewer, ktery bude po dokonfigurovani zkusen vytahnout nahoru +#define WM_USER_VIEWERCONFIG WM_APP + 158 // [hWnd, 0] - hWnd indicates the viewer to bring to front after configuration -#define WM_USER_UPDATEPANEL WM_APP + 159 // [0, 0] - pokud je dorucena \ - // (doruci ji messageloopa pri otevreni messageboxu), \ - // bude invalidatnut panel a bude nastavena scrollbara \ - // (pouze pro interni pouziti !!!) +#define WM_USER_UPDATEPANEL WM_APP + 159 // [0, 0] - when delivered \ + // (the message loop sends it after opening a message box), \ + // the panel will be invalidated and the scrollbar updated \ + // (for internal use only) #define WM_USER_AUTOCONFIG WM_APP + 160 // KICKER - autoconfig #define WM_USER_ACFINDFINISHED WM_APP + 161 // KICKER - autoconfig @@ -1120,139 +1141,156 @@ struct COpenViewerData #define WM_USER_ACADDFILE WM_APP + 163 // KICKER - autoconfig #define WM_USER_ACERROR WM_APP + 164 // KICKER - autoconfig -#define WM_USER_QUERYCLOSEFIND WM_APP + 170 // [0, quiet] - zepta se v threadu find okna, jestli ho muzeme zavrit + na dotaz zastavi pripadne probihajici hledani -#define WM_USER_COLORCHANGEFIND WM_APP + 171 // [0, 0] - informuje find okna o zmene barev +#define WM_USER_QUERYCLOSEFIND WM_APP + 170 // [0, quiet] - ask the Find window thread whether it can be closed and stop any ongoing search if requested +#define WM_USER_COLORCHANGEFIND WM_APP + 171 // [0, 0] - notifies Find windows about color changes #define WM_USER_HELPHITTEST WM_APP + 172 // lResult = dwContext, lParam = MAKELONG(x,y) #define WM_USER_EXITHELPMODE WM_APP + 173 // [0, 0] -#define WM_USER_POSTCMDORUNLOADPLUGIN WM_APP + 180 // [plug-in iface, 0, 1 nebo salCmd+2 nebo menuCmd+502] - nastavi ShouldUnload nebo ShouldRebuildMenu nebo prida salCmd/menuCmd do dat plug-inu -#define WM_USER_POSTMENUEXTCMD WM_APP + 181 // [plug-in iface, cmdID] - post menu-ext-cmd z plug-inu +#define WM_USER_POSTCMDORUNLOADPLUGIN WM_APP + 180 // [plugin iface, 0, 1 or salCmd+2 or menuCmd+502] - sets ShouldUnload or ShouldRebuildMenu or adds salCmd/menuCmd to plugin data +#define WM_USER_POSTMENUEXTCMD WM_APP + 181 // [plugin iface, cmdID] - post a menu-ext command from a plugin -#define WM_USER_SHOWPLUGINMSGBOX WM_APP + 185 // [0, 0] - otevreni msg-boxu o plug-inu nad Bug Report dialogem +#define WM_USER_SHOWPLUGINMSGBOX WM_APP + 185 // [0, 0] - open the plugin message box above the Bug Report dialog -// prikazy pro hlavni thread (v jinem threadu je nelze spoustet) - vyuziva Find dialog (bezi ve svem threadu) -#define WM_USER_VIEWFILE WM_APP + 190 // [COpenViewerData *, altView] - otevreni souboru v (alternate) vieweru -#define WM_USER_EDITFILE WM_APP + 191 // [name, 0] - otevreni souboru v editoru -#define WM_USER_VIEWFILEWITH WM_APP + 192 // [COpenViewerData *, handlerID] - otevreni souboru ve vybranem vieweru -#define WM_USER_EDITFILEWITH WM_APP + 193 // [name, handlerID] - otevreni souboru ve vybranem editoru +// commands for the main thread (cannot be run from another thread) - uses the +// Find dialog (running in its own thread) +#define WM_USER_VIEWFILE WM_APP + 190 // [COpenViewerData *, altView] - open a file in the (alternate) viewer +#define WM_USER_EDITFILE WM_APP + 191 // [name, 0] - open a file in the editor +#define WM_USER_VIEWFILEWITH WM_APP + 192 // [COpenViewerData *, handlerID] - open a file in the selected viewer +#define WM_USER_EDITFILEWITH WM_APP + 193 // [name, handlerID] - open a file in the selected editor -#define WM_USER_DISPACHCHANGENOTIF WM_APP + 194 // [0, time] - zadost o rozeslani zprav o zmenach na cestach +#define WM_USER_DISPACHCHANGENOTIF WM_APP + 194 // [0, time] - request to distribute notifications about path changes -#define WM_USER_DISPACHCFGCHANGE WM_APP + 195 // [0, 0] - zadost o rozeslani zprav o zmenach v konfiguraci mezi plug-iny +#define WM_USER_DISPACHCFGCHANGE WM_APP + 195 // [0, 0] - request to distribute configuration change notifications among plugins -#define WM_USER_CFGCHANGED WM_APP + 196 // [0, 0] - zasilano internim viewerum a find oknum po zmene konfigurace +#define WM_USER_CFGCHANGED WM_APP + 196 // [0, 0] - sent to internal viewers and Find windows after configuration changes -#define WM_USER_CLEARHISTORY WM_APP + 197 // [0, 0] - informuje okno, ze ma promazat vsechny comboboxy obsahujici historie +#define WM_USER_CLEARHISTORY WM_APP + 197 // [0, 0] - instructs the window to clear all combo boxes containing histories -#define WM_USER_REFRESHTOOLTIP WM_APP + 198 // posti se do tooltip okna: dojde k novemu vytazeni textu, resize okna a prekresleni -#define WM_USER_HIDETOOLTIP WM_APP + 199 // zprava pro prekroceni hranic threadu; zhasne tooltip +#define WM_USER_REFRESHTOOLTIP WM_APP + 198 // sent to the tooltip window: fetch text again, resize the window, and repaint +#define WM_USER_HIDETOOLTIP WM_APP + 199 // cross-thread message; hides the tooltip //////////////////////////////////////////////////////// // // -// Prostor WM_APP + 200 az WM_APP + 399 je urcen // -// pro zpravy chodici take do oken pluginu. // -// Definice je v plugins\shared\spl_*.h // +// The range WM_APP + 200 to WM_APP + 399 is reserved // +// for messages also sent to plugin windows. // +// Definitions are in plugins\shared\spl_*.h // // // //////////////////////////////////////////////////////// -#define WM_USER_ENUMFILENAMES WM_APP + 400 // [requestUID, 0] - informuje zdroj (panely a Findy), ze maji resit pozadavek na enumeraci souboru pro viewer +#define WM_USER_ENUMFILENAMES WM_APP + 400 // [requestUID, 0] - tells the source (panels and Find windows) to \ + // handle a request for file enumeration for the viewer -#define WM_USER_SM_END_NOTIFY_DELAYED WM_APP + 401 // [0, 0] notifikace o ukonceni suspend modu (zpozdena o 200ms, aby nedochazelo ke kolizi s WM_QUERYENDSESSION pri Shutdown / Log Off) -#define WM_USER_REFRESH_DIR_EX_DELAYED WM_APP + 402 // [FALSE, time] - lisi se od WM_USER_REFRESH_DIR tim, ze jde pravdepodobne o zbytecny refresh (duvod: aktivace okna, zadost o lock-volume (dela se obdoba "hands-off"), atp.) (zpozdena o 200ms nebo 5s, aby nedochazelo ke kolizi s WM_QUERYENDSESSION pri Shutdown / Log Off nebo aby si proces zadajici o lock-volume stihl volume zamknout) +#define WM_USER_SM_END_NOTIFY_DELAYED WM_APP + 401 // [0, 0] notification that suspend mode ended \ + // delayed by 200 ms to avoid conflicts with \ + // WM_QUERYENDSESSION during Shutdown/Log Off +#define WM_USER_REFRESH_DIR_EX_DELAYED WM_APP + 402 // [FALSE, time] - unlike WM_USER_REFRESH_DIR this is \ + // probably an unnecessary refresh (window activation, \ + // request for a lock volume similar to "hands-off", etc.) \ + // delayed by 200 ms or 5 s so it does not collide with \ + // WM_QUERYENDSESSION during Shutdown/Log Off or so the \ + // process requesting the lock can lock the volume -#define WM_USER_CLOSE_MAINWND WM_APP + 403 // [0, 0] - pouziva se misto WM_CLOSE pro zavreni hlavniho okna Salamandera (vyhoda: je mozne zjistit, jestli se nedistribuuje z jine nez hlavni message-loopy) +#define WM_USER_CLOSE_MAINWND WM_APP + 403 // [0, 0] - used instead of WM_CLOSE for closing the main \ + // Salamander window (advantage: we can detect whether it \ + // is dispatched from a non-main message loop) -#define WM_USER_HELP_MOUSEMOVE WM_APP + 405 // [0, mousePos] - zasilano behem Shift+F1 (ctx help) mode vsem child oknum; po obdrzeni jedne nebo vice WM_USER_MOUSEMOVE prijde WM_USER_MOUSELEAVE; slouzi k trackovani kurzoru mysi bez, aniz bychom nahazaovali capture -#define WM_USER_HELP_MOUSELEAVE WM_APP + 406 // [0, 0] - prichazi po WM_USER_MOUSEMOVE, kdyz kurzor opousti childa +#define WM_USER_HELP_MOUSEMOVE WM_APP + 405 // [0, mousePos] - sent during Shift+F1 (context help) mode \ + // to all child windows; after one or more WM_USER_MOUSEMOVE \ + // messages WM_USER_MOUSELEAVE follows; used to track the \ + // mouse cursor without capture +#define WM_USER_HELP_MOUSELEAVE WM_APP + 406 // [0, 0] - sent after WM_USER_MOUSEMOVE when the cursor leaves a child window -//#define WM_USER_RENAME_NEXT_ITEM WM_APP + 407 // [next, 0] - postne se po zmacknuti (Shift)Tab v inplace QuickRename pro prechod na (predchozi) dalsi polozku; inspired by Vista; 'next' je TRUE pro dalsi a FALSE pro predchozi +//#define WM_USER_RENAME_NEXT_ITEM WM_APP + 407 // [next, 0] - posted after pressing (Shift)Tab in inplace QuickRename to move to the (previous) next item; inspired by Vista; 'next' is TRUE for next and FALSE for previous -#define WM_USER_PROGRDLG_UPDATEICON WM_APP + 408 // [0, 0] - CProgressDlgArray: po doruceni teto zpravy do CProgressDialog dojde k novemu nastaveni ikonky dialogu +#define WM_USER_PROGRDLG_UPDATEICON WM_APP + 408 // [0, 0] - CProgressDlgArray: when this message arrives the \ + // icon of the CProgressDialog is updated -#define WM_USER_FORCECLOSE_MAINWND WM_APP + 409 // [0, 0] - vynucene zavreni hlavniho okna Salamandera +#define WM_USER_FORCECLOSE_MAINWND WM_APP + 409 // [0, 0] - forced closing of the main Salamander window -#define WM_USER_INACTREFRESH_DIR WM_APP + 410 // [0, time] - zpozdeny refresh pri neaktivnim hl. okne Salamandera +#define WM_USER_INACTREFRESH_DIR WM_APP + 410 // [0, time] - delayed refresh when the main Salamander window is inactive -#define WM_USER_WAKEUP_FROM_IDLE WM_APP + 411 // [0, 0] - pokud je hlavni thread v IDLE, probere se +#define WM_USER_WAKEUP_FROM_IDLE WM_APP + 411 // [0, 0] - wakes up the main thread when it is IDLE -#define WM_USER_FINDFULLROWSEL WM_APP + 412 // [0, 0] - find okna maji nastavit sve list view, aby odpovidalo promenne Configuration.FindFullRowSelect +#define WM_USER_FINDFULLROWSEL WM_APP + 412 // [0, 0] - Find windows must set their list view to match Configuration.FindFullRowSelect -#define WM_USER_SLGINCOMPLETE WM_APP + 414 // [0, 0] - upozorneni, ze SLG neni kompletne prelozene, motivacni text aby se zapojili +#define WM_USER_SLGINCOMPLETE WM_APP + 414 // [0, 0] - notification that SLG is not fully translated; encourages contributions -#define WM_USER_USERMENUICONS_READY WM_APP + 415 // [bkgndReaderData, threadID] - notifikace pro hl. okno, ze se dokoncilo cteni ikon pro User Menu v threadu s ID 'threadID' +#define WM_USER_USERMENUICONS_READY WM_APP + 415 // [bkgndReaderData, threadID] - notification for the main window \ + // that reading icons for the User Menu has finished in the \ + // thread with ID 'threadID' // states for Shift+F1 help mode #define HELP_INACTIVE 0 // not in Shift+F1 help mode (must be 0) #define HELP_ACTIVE 1 // in Shift+F1 help mode (non-zero) #define HELP_ENTERING 2 // entering Shift+F1 help mode (non-zero) -#define STACK_CALLS_BUF_SIZE 5000 // kazdy thread bude mit 5KB prostor pro textovy call-stack -#define STACK_CALLS_MAX_MESSAGE_LEN 500 // nejdelsi zpravu uvazujeme 500 znaku +#define STACK_CALLS_BUF_SIZE 5000 // each thread will have 5KB space for the text call stack +#define STACK_CALLS_MAX_MESSAGE_LEN 500 // the longest message is assumed to be 500 characters -#define MENU_MARK_CX 9 // rozmery check mark pro menu +#define MENU_MARK_CX 9 // check mark dimensions for menus #define MENU_MARK_CY 9 -#define BOTTOMBAR_CX 17 // rozmer tlacitka v souboru bottomtb.bmp (v bodech) +#define BOTTOMBAR_CX 17 // button dimension in bottomtb.bmp (points) #define BOTTOMBAR_CY 13 -// barvy v CurrentColors[x] -#define FOCUS_ACTIVE_NORMAL 0 // barvy pera pro ramecek kolem polozky +// colors in CurrentColors[x] +#define FOCUS_ACTIVE_NORMAL 0 // pen colors for the item frame #define FOCUS_ACTIVE_SELECTED 1 #define FOCUS_FG_INACTIVE_NORMAL 2 #define FOCUS_FG_INACTIVE_SELECTED 3 #define FOCUS_BK_INACTIVE_NORMAL 4 #define FOCUS_BK_INACTIVE_SELECTED 5 -#define ITEM_FG_NORMAL 6 // barvy textu polozek v panelu +#define ITEM_FG_NORMAL 6 // text colors of items in the panel #define ITEM_FG_SELECTED 7 #define ITEM_FG_FOCUSED 8 #define ITEM_FG_FOCSEL 9 #define ITEM_FG_HIGHLIGHT 10 -#define ITEM_BK_NORMAL 11 // barvy pozadi polozek v panelu +#define ITEM_BK_NORMAL 11 // background color of panel items #define ITEM_BK_SELECTED 12 #define ITEM_BK_FOCUSED 13 #define ITEM_BK_FOCSEL 14 #define ITEM_BK_HIGHLIGHT 15 -#define ICON_BLEND_SELECTED 16 // barvy pro blend ikonek +#define ICON_BLEND_SELECTED 16 // colors for icon blending #define ICON_BLEND_FOCUSED 17 #define ICON_BLEND_FOCSEL 18 -#define PROGRESS_FG_NORMAL 19 // barvy progress bary +#define PROGRESS_FG_NORMAL 19 // progress bar colors #define PROGRESS_FG_SELECTED 20 #define PROGRESS_BK_NORMAL 21 #define PROGRESS_BK_SELECTED 22 -#define HOT_PANEL 23 // barva hot polozky v panelu -#define HOT_ACTIVE 24 // v aktivnim titulku panelu -#define HOT_INACTIVE 25 // v neaktivni tiulku panelu, statusbar,... +#define HOT_PANEL 23 // color of the hot item in the panel +#define HOT_ACTIVE 24 // in the active panel title +#define HOT_INACTIVE 25 // in the inactive panel caption, status bar, ... -#define ACTIVE_CAPTION_FG 26 // barva textu v aktivnim titulku panelu -#define ACTIVE_CAPTION_BK 27 // barva pozadi v aktivnim titulku panelu -#define INACTIVE_CAPTION_FG 28 // barva textu v neaktivnim titulku panelu -#define INACTIVE_CAPTION_BK 29 // barva pozadi v neaktivnim titulku panelu +#define ACTIVE_CAPTION_FG 26 // text color in the active panel title +#define ACTIVE_CAPTION_BK 27 // background color in the active panel title +#define INACTIVE_CAPTION_FG 28 // text color in the inactive panel title +#define INACTIVE_CAPTION_BK 29 // background color in the inactive panel caption -#define THUMBNAIL_FRAME_NORMAL 30 // barvy pera pro ramecek kolem thumbnails +#define THUMBNAIL_FRAME_NORMAL 30 // pen colors for the frame around thumbnails #define THUMBNAIL_FRAME_FOCUSED 31 #define THUMBNAIL_FRAME_SELECTED 32 #define THUMBNAIL_FRAME_FOCSEL 33 -#define VIEWER_FG_NORMAL 0 // normalni barvy viewru +#define VIEWER_FG_NORMAL 0 // normal viewer colors #define VIEWER_BK_NORMAL 1 #define VIEWER_FG_SELECTED 2 // selected text #define VIEWER_BK_SELECTED 3 -#define NUMBER_OF_COLORS 34 // pocet barev ve schematu -#define NUMBER_OF_VIEWERCOLORS 4 // pocet barev pro viewer -#define NUMBER_OF_CUSTOMCOLORS 16 // uzivatelelm definovane barvy v barevnem dialogu +#define NUMBER_OF_COLORS 34 // number of colors in the scheme +#define NUMBER_OF_VIEWERCOLORS 4 // number of colors for the viewer +#define NUMBER_OF_CUSTOMCOLORS 16 // user-defined colors in the color dialog -// interni drzak barvy, ktery navic obsahuje flag +// internal color holder with an extra flag typedef DWORD SALCOLOR; // SALCOLOR flags -#define SCF_DEFAULT 0x01 // barevna slozka se ignoruje a pouzije se default hodnota +#define SCF_DEFAULT 0x01 // the color component is ignored and the default value is used #define GetCOLORREF(rgbf) ((COLORREF)rgbf & 0x00ffffff) #define RGBF(r, g, b, f) ((COLORREF)(((BYTE)(r) | ((WORD)((BYTE)(g)) << 8)) | (((DWORD)(BYTE)(b)) << 16) | (((DWORD)(BYTE)(f)) << 24))) @@ -1263,34 +1301,34 @@ inline void SetRGBPart(SALCOLOR* salColor, COLORREF rgb) *salColor = rgb & 0x00ffffff | (((DWORD)(BYTE)((BYTE)((*salColor) >> 24))) << 24); } -extern SALCOLOR* CurrentColors; // aktualni barvy -extern SALCOLOR UserColors[NUMBER_OF_COLORS]; // zmenene barvy +extern SALCOLOR* CurrentColors; // current colors +extern SALCOLOR UserColors[NUMBER_OF_COLORS]; // modified colors -extern SALCOLOR SalamanderColors[NUMBER_OF_COLORS]; // standardni barvy -extern SALCOLOR ExplorerColors[NUMBER_OF_COLORS]; // standardni barvy -extern SALCOLOR NortonColors[NUMBER_OF_COLORS]; // standardni barvy -extern SALCOLOR NavigatorColors[NUMBER_OF_COLORS]; // standardni barvy +extern SALCOLOR SalamanderColors[NUMBER_OF_COLORS]; // standard colors +extern SALCOLOR ExplorerColors[NUMBER_OF_COLORS]; // standard colors +extern SALCOLOR NortonColors[NUMBER_OF_COLORS]; // standard colors +extern SALCOLOR NavigatorColors[NUMBER_OF_COLORS]; // standard colors -extern SALCOLOR ViewerColors[NUMBER_OF_VIEWERCOLORS]; // barvy vieweru +extern SALCOLOR ViewerColors[NUMBER_OF_VIEWERCOLORS]; // viewer colors -extern COLORREF CustomColors[NUMBER_OF_CUSTOMCOLORS]; // pro standardni color dialog +extern COLORREF CustomColors[NUMBER_OF_CUSTOMCOLORS]; // for the standard color dialog #define CARET_WIDTH 2 -#define MIN_PANELWIDTH 5 // uzsi panel nedostava focus +#define MIN_PANELWIDTH 5 // a narrower panel does not receive focus -#define REFRESH_PAUSE 200 // pauza mezi dvema nejblizsimi refreshi +#define REFRESH_PAUSE 200 // pause between the two nearest refreshes -extern int SPACE_WIDTH; // mezera mezi sloupcema v detailed view +extern int SPACE_WIDTH; // spacing between columns in detailed view -#define MENU_CHECK_WIDTH 8 // rozmery check bitmap pro menu +#define MENU_CHECK_WIDTH 8 // dimensions of the check bitmap for menus #define MENU_CHECK_HEIGHT 8 -// pocty pamatovanych stringu +// numbers of remembered strings #define SELECT_HISTORY_SIZE 20 // select / unselect #define COPY_HISTORY_SIZE 20 // copy / move #define EDIT_HISTORY_SIZE 30 // command line #define CHANGEDIR_HISTORY_SIZE 20 // Shift+F7 -#define PATH_HISTORY_SIZE 30 // forward/backward historie cest + historie navstivenych cest (Alt+F12) +#define PATH_HISTORY_SIZE 30 // forward/backward path history + visited paths history (Alt+F12) #define FILTER_HISTORY_SIZE 15 // filter #define FILELIST_HISTORY_SIZE 15 #define CREATEDIR_HISTORY_SIZE 20 // create directory @@ -1302,10 +1340,10 @@ extern int SPACE_WIDTH; // mezera mezi sloupcema v detailed view #define VK_BACKSLASH 220 #define VK_RBRACKET 221 -// kdy testovat pokus o preruseni stavby scriptu -#define BS_TIMEOUT 200 // milisekund od posledniho testu +// when to test for an attempt to interrupt script building +#define BS_TIMEOUT 200 // milliseconds since the last test -// identifikace bandu v rebaru +// band identifiers in the rebar #define BANDID_MENU 1 #define BANDID_TOPTOOLBAR 2 #define BANDID_UMTOOLBAR 3 @@ -1318,33 +1356,33 @@ extern int SPACE_WIDTH; // mezera mezi sloupcema v detailed view #define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp)) #define GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp)) -// urcuji duvod, proc jsou v panelu neobsazeny nektere soubory/adresare -#define HIDDEN_REASON_ATTRIBUTE 0x00000001 // maji atribut hidden nebo system a v konfiguraci je potlaceni zobrazovani takovych souboru/adresaru -#define HIDDEN_REASON_FILTER 0x00000002 // soubor je odfiltrovan na zaklade filtru v panelu -#define HIDDEN_REASON_HIDECMD 0x00000004 // jmeno bylo skryto prikazem Hide Selected/Unselected Names +// reasons why some files/directories are not shown in the panel +#define HIDDEN_REASON_ATTRIBUTE 0x00000001 // have the hidden or system attribute and configuration suppresses such files/directories +#define HIDDEN_REASON_FILTER 0x00000002 // file is filtered out based on the panel filter +#define HIDDEN_REASON_HIDECMD 0x00000004 // name was hidden using Hide Selected/Unselected Names -// bitove pole drivu 'a' .. 'z' +// bit field of drive letters 'a' .. 'z' #define DRIVES_MASK 0x03FFFFFF // // **************************************************************************** // Windows XP, Windows 2003.NET, Vista, Windows 7, Windows 8, Windows 8.1, Windows 10 -extern BOOL WindowsXP64AndLater; // Windows XP64 nebo pozdejsi -extern BOOL WindowsVistaAndLater; // Windows Vista nebo pozdejsi -extern BOOL Windows7AndLater; // Windows 7 nebo pozdejsi -extern BOOL Windows8AndLater; // Windows 8 nebo pozdejsi -extern BOOL Windows8_1AndLater; // Windows 8.1 nebo pozdejsi -extern BOOL Windows10AndLater; // Windows 10 nebo pozdejsi +extern BOOL WindowsXP64AndLater; // Windows XP64 or later +extern BOOL WindowsVistaAndLater; // Windows Vista or later +extern BOOL Windows7AndLater; // Windows 7 or later +extern BOOL Windows8AndLater; // Windows 8 or later +extern BOOL Windows8_1AndLater; // Windows 8.1 or later +extern BOOL Windows10AndLater; // Windows 10 or later -extern BOOL Windows64Bit; // x64 verze Windows +extern BOOL Windows64Bit; // x64 version of Windows -extern BOOL RunningAsAdmin; // TRUE pokud Salamander bezi "As Administrator" +extern BOOL RunningAsAdmin; // TRUE when Salamander runs "As Administrator" -extern DWORD CCVerMajor; // verze DLL common controls +extern DWORD CCVerMajor; // version of the common controls DLL extern DWORD CCVerMinor; -extern const char* SALAMANDER_TEXT_VERSION; // textove oznaceni aplikace vcetne verze +extern const char* SALAMANDER_TEXT_VERSION; // textual application label including the version extern const char *LOW_MEMORY, *MAINWINDOW_NAME, @@ -1353,56 +1391,56 @@ extern const char *LOW_MEMORY, *SAVEBITS_CLASSNAME, *SHELLEXECUTE_CLASSNAME; -extern const char* STR_NONE; // "(none)" - plug-iny: pro DLLName a Version pokud jsou nezjistitelne +extern const char* STR_NONE; // "(none)" - plugins: used for DLLName and Version when they cannot be determined -extern char DefaultDir['z' - 'a' + 1][MAX_PATH]; // kam jit pri zmene disku +extern char DefaultDir['z' - 'a' + 1][MAX_PATH]; // target path when changing drives -extern int MyTimeCounter; // po kazdem pouziti inkrementovat ! -extern CRITICAL_SECTION TimeCounterSection; // pro synchronizaci pristupu k ^ +extern int MyTimeCounter; // increment after each use! +extern CRITICAL_SECTION TimeCounterSection; // used to synchronize access to the above -extern HINSTANCE NtDLL; // handle k ntdll.dll -extern HINSTANCE Shell32DLL; // handle k shell32.dll (ikonky) -extern HINSTANCE ImageResDLL; // handle k imageres.dll (ikonky - Vista+) -extern HINSTANCE User32DLL; // handle k user32.dll (DisableProcessWindowsGhosting) -extern HINSTANCE HLanguage; // handle k jazykove zavislym resourcum (cesta: Configuration.LoadedSLGName) -extern char CurrentHelpDir[MAX_PATH]; // po prvnim pouziti helpu je zde cesta do adresare helpu (umisteni vsech .chm souboru) -extern WORD LanguageID; // language-id jazykove zavislych resourcu (.SLG souboru) +extern HINSTANCE NtDLL; // handle to ntdll.dll +extern HINSTANCE Shell32DLL; // handle to shell32.dll (icons) +extern HINSTANCE ImageResDLL; // handle to imageres.dll (icons - Vista+) +extern HINSTANCE User32DLL; // handle to user32.dll (DisableProcessWindowsGhosting) +extern HINSTANCE HLanguage; // handle to language-specific resources (path: Configuration.LoadedSLGName) +extern char CurrentHelpDir[MAX_PATH]; // after the first use of help this holds the path to the help directory (location of all .chm files) +extern WORD LanguageID; // language ID of the language-specific resources (.SLG file) -extern BOOL UseCustomPanelFont; // pokud je TRUE, vychazi Font a FontUL ze struktury LogFont; jinak ze systemoveho fontu (default) +extern BOOL UseCustomPanelFont; // if TRUE, Font and FontUL are based on LogFont; otherwise on the system font (default) extern HFONT Font; // panel font -extern HFONT FontUL; // podtrzena verze -extern int FontCharHeight; // vyska fontu -extern LOGFONT LogFont; // struktura popisujici panel font +extern HFONT FontUL; // underlined version +extern int FontCharHeight; // font height +extern LOGFONT LogFont; // structure describing the panel font -BOOL CreatePanelFont(); // naplni Font, FontULa FontCharHeight na zaklade LogFont +BOOL CreatePanelFont(); // fills Font, FontUL and FontCharHeight based on LogFont -extern HFONT EnvFont; // font prostredi (edit, toolbar, header, status) -extern HFONT EnvFontUL; // font listboxu podtrzeny -extern int EnvFontCharHeight; // vyska fontu -extern HFONT TooltipFont; // font pro tooltips (a statusbars, ale tam ho nepouzivame) +extern HFONT EnvFont; // environment font (edit, toolbar, header, status) +extern HFONT EnvFontUL; // underlined list box font +extern int EnvFontCharHeight; // font height +extern HFONT TooltipFont; // font for tooltips (and status bars, although we don't use it there) -BOOL GetSystemGUIFont(LOGFONT* lf); // vrati font pouzivany pro hlavni okno Salamandera -BOOL CreateEnvFonts(); // naplni EnvFont, EnvFontUL, EnvFontCharHeight, TooltipFont na zaklade metrics +BOOL GetSystemGUIFont(LOGFONT* lf); // retrieves the font used for the main Salamander window +BOOL CreateEnvFonts(); // fills EnvFont, EnvFontUL, EnvFontCharHeight and TooltipFont based on system metrics -extern DWORD MouseHoverTime; // po jake dobe ma dojit k vysviceni +extern DWORD MouseHoverTime; // how long before highlighting occurs -extern HBRUSH HNormalBkBrush; // pozadi obycejne polozky v panelu -extern HBRUSH HFocusedBkBrush; // pozadi focusle polozky v panelu -extern HBRUSH HSelectedBkBrush; // pozadi selected polozky v panelu -extern HBRUSH HFocSelBkBrush; // pozadi focused & selected polozky v panelu -extern HBRUSH HDialogBrush; // vypln pozadi dialogu -extern HBRUSH HButtonTextBrush; // text tlacitek -extern HBRUSH HDitherBrush; // sachovnice o barevne hloubce 1 bit; pri kresleni lze barvu nastavit pres SetTextColor/SetBkColor -extern HBRUSH HActiveCaptionBrush; // pozadi aktivniho tiutlku panelu -extern HBRUSH HInactiveCaptionBrush; // pozadi neaktivniho tiutlku panelu +extern HBRUSH HNormalBkBrush; // background of a regular panel item +extern HBRUSH HFocusedBkBrush; // background of the focused panel item +extern HBRUSH HSelectedBkBrush; // background of the selected panel item +extern HBRUSH HFocSelBkBrush; // background of a focused and selected item +extern HBRUSH HDialogBrush; // dialog background fill +extern HBRUSH HButtonTextBrush; // button text +extern HBRUSH HDitherBrush; // 1-bit checkerboard pattern; the color can be set via SetTextColor/SetBkColor +extern HBRUSH HActiveCaptionBrush; // background of the active panel title +extern HBRUSH HInactiveCaptionBrush; // background of the inactive panel title extern HBRUSH HMenuSelectedBkBrush; extern HBRUSH HMenuSelectedTextBrush; extern HBRUSH HMenuHilightBrush; extern HBRUSH HMenuGrayTextBrush; -extern HACCEL AccelTable1; // akceleratory v panelech a cmdline -extern HACCEL AccelTable2; // akceleratory v cmdline +extern HACCEL AccelTable1; // accelerators in panels and the command line +extern HACCEL AccelTable2; // accelerators in the command line extern int SystemDPI; @@ -1411,61 +1449,61 @@ enum CIconSizeEnum ICONSIZE_16, // 16x16 @ 100%DPI, 20x20 @ 125%DPI, 24x24 @ 150%DPI, ... ICONSIZE_32, // 32x32 @ 100%DPI, ... ICONSIZE_48, // 48x48 @ 100%DPI, ... - ICONSIZE_COUNT // items count + ICONSIZE_COUNT // item count }; -extern int IconSizes[ICONSIZE_COUNT]; // velikosti ikonek: 16, 32, 48 -extern int IconLRFlags; // ridi barevnou hloubku nacitanych ikon +extern int IconSizes[ICONSIZE_COUNT]; // icon sizes: 16, 32, 48 +extern int IconLRFlags; // controls the color depth of loaded icons -// POZOR: na Viste se pouziva pro ikony 48x48 overlay ICONSIZE_32 a pro thumbnaily overlay ICONSIZE_48 -extern HICON HSharedOverlays[ICONSIZE_COUNT]; // shared (ruka) ve vsech velikostech -extern HICON HShortcutOverlays[ICONSIZE_COUNT]; // shortcut (levy dolni roh) ve vsech velikostech -extern HICON HSlowFileOverlays[ICONSIZE_COUNT]; // slow files +// NOTE: on Vista a 48x48 icon uses overlay ICONSIZE_32 and thumbnails use overlay ICONSIZE_48 +extern HICON HSharedOverlays[ICONSIZE_COUNT]; // shared (hand) overlay in all sizes +extern HICON HShortcutOverlays[ICONSIZE_COUNT]; // shortcut (lower left corner) overlay in all sizes +extern HICON HSlowFileOverlays[ICONSIZE_COUNT]; // slow file overlays -extern CIconList* SimpleIconLists[ICONSIZE_COUNT]; // simple icons ve vsech velikostech +extern CIconList* SimpleIconLists[ICONSIZE_COUNT]; // simple icons in all sizes -#define THROBBER_WIDTH 12 // rozmery jednoho policka +#define THROBBER_WIDTH 12 // dimensions of one frame #define THROBBER_HEIGHT 12 -#define THROBBER_COUNT 36 // celkovy pocet policek -#define IDT_THROBBER_DELAY 30 // delay [ms] v animaci jednoho policka +#define THROBBER_COUNT 36 // total number of frames +#define IDT_THROBBER_DELAY 30 // delay [ms] for one frame of the animation extern CIconList* ThrobberFrames; -#define LOCK_WIDTH 8 // rozmery jednoho policka +#define LOCK_WIDTH 8 // size of one frame #define LOCK_HEIGHT 13 extern CIconList* LockFrames; -extern HICON HGroupIcon; // skupina pro UserMenu popupy -extern HICON HFavoritIcon; // hot path +extern HICON HGroupIcon; // group icon for UserMenu pop-ups +extern HICON HFavoritIcon; // hot path icon -#define TILE_LEFT_MARGIN 4 // pocet bodu vlevo pred ikonkou +#define TILE_LEFT_MARGIN 4 // number of pixels to the left of the icon -extern RGBQUAD ColorTable[256]; // paleta pouzivana pro vsechny toolbary (vcetne pluginu) +extern RGBQUAD ColorTable[256]; // palette used for all toolbars (including plugins) -// jednotlive pozice imagelistu SymbolsImageList a LargeSymbolsImageList +// individual indices in the SymbolsImageList and LargeSymbolsImageList image lists enum CSymbolsImageListIndexes { symbolsExecutable, // 0: exe/bat/pif/com symbolsDirectory, // 1: dir - symbolsNonAssociated, // 2: neasociovany soubor - symbolsAssociated, // 3: asociovany soubor - symbolsUpDir, // 4: up-dir ".." - symbolsArchive, // 5: archiv + symbolsNonAssociated, // 2: non-associated file + symbolsAssociated, // 3: associated file + symbolsUpDir, // 4: parent directory ".." + symbolsArchive, // 5: archive symbolsCount // TERMINATOR }; -extern HIMAGELIST HFindSymbolsImageList; // symboly pro find -extern HIMAGELIST HMenuMarkImageList; // check marky pro menu -extern HIMAGELIST HGrayToolBarImageList; // toolbar a menu v sedivem provedeni (pocitano z barevneho) -extern HIMAGELIST HHotToolBarImageList; // toolbar a menu v barevnem provedeni +extern HIMAGELIST HFindSymbolsImageList; // symbols for Find +extern HIMAGELIST HMenuMarkImageList; // check marks for menus +extern HIMAGELIST HGrayToolBarImageList; // toolbar and menu in a gray variant (generated from the colored one) +extern HIMAGELIST HHotToolBarImageList; // toolbar and menu in color extern HIMAGELIST HBottomTBImageList; // bottom toolbar (F1 - F12) extern HIMAGELIST HHotBottomTBImageList; // bottom toolbar (F1 - F12) -extern HPEN HActiveNormalPen; // pera pro ramecek kolem polozky +extern HPEN HActiveNormalPen; // pens for the rectangle around an item extern HPEN HActiveSelectedPen; extern HPEN HInactiveNormalPen; extern HPEN HInactiveSelectedPen; -extern HPEN HThumbnailNormalPen; // pera pro ramecek kolem thumbnail +extern HPEN HThumbnailNormalPen; // pens for the rectangle around a thumbnail extern HPEN HThumbnailFucsedPen; extern HPEN HThumbnailSelectedPen; extern HPEN HThumbnailFocSelPen; @@ -1477,32 +1515,32 @@ extern HPEN BtnFacePen; extern HPEN WndFramePen; extern HPEN WndPen; -extern HBITMAP HFilter; // bitmapa - panel skryva nejake soubory nebo adresare +extern HBITMAP HFilter; // bitmap - the panel hides some files or directories -extern HBITMAP HHeaderSort; // sipky pro HeaderLine +extern HBITMAP HHeaderSort; // arrows for HeaderLine -extern CBitmap ItemBitmap; // devecka pro vsechno mozne: kresleni polozek v panelu, header line, ... +extern CBitmap ItemBitmap; // helper for various things: drawing items in the panel, header line, etc. -extern HBITMAP HUpDownBitmap; // Sipky pro rolovani uvnitr kratkych popup menu. -extern HBITMAP HZoomBitmap; // Zoom panelu +extern HBITMAP HUpDownBitmap; // arrows for scrolling inside short popup menus +extern HBITMAP HZoomBitmap; // panel zoom bitmap //extern HBITMAP HWorkerBitmap; -extern HCURSOR HHelpCursor; // Context Help cursor - loadi se az kdyz je potreba +extern HCURSOR HHelpCursor; // context help cursor - loaded only when needed -#define THUMBNAIL_SIZE_DEFAULT 94 // podle XP -#define THUMBNAIL_SIZE_MIN 48 // pokud budeme chtit podpori mensi nez 48, je potreba zobrazovat mensi ikony +#define THUMBNAIL_SIZE_DEFAULT 94 // according to Windows XP +#define THUMBNAIL_SIZE_MIN 48 // to support less than 48 we would need to show smaller icons #define THUMBNAIL_SIZE_MAX 1000 -extern BOOL DragFullWindows; // pokud je TRUE, mame menit velikost panelu realtime, jinak az po releasu (optimalizace pro remote desktop) +extern BOOL DragFullWindows; // if TRUE the panel is resized in real time, otherwise only after release (optimization for remote desktop) -// CConfiguration::SizeFormat (format sloupce Size v panelech) -// !POZOR! nemenit konstanty, jsou vyvezene do pluginu pres SALCFG_SIZEFORMAT -#define SIZE_FORMAT_BYTES 0 // v bajtech (Open Salamander) -#define SIZE_FORMAT_KB 1 // v KB (Windows Explorer) -#define SIZE_FORMAT_MIXED 2 // bajty, KB, MB, GB, ... +// CConfiguration::SizeFormat (the Size column format in panels) +// WARNING! Do not change the constants; they are exported to plugins via SALCFG_SIZEFORMAT +#define SIZE_FORMAT_BYTES 0 // in bytes (Open Salamander) +#define SIZE_FORMAT_KB 1 // in KB (Windows Explorer) +#define SIZE_FORMAT_MIXED 2 // bytes, KB, MB, GB, ... -// jmena klicu v registry +// names of registry keys extern const char* SALAMANDER_ROOT_REG; extern const char* SALAMANDER_SAVE_IN_PROGRESS; extern const char* SALAMANDER_COPY_IS_OK; @@ -1562,8 +1600,9 @@ extern const char* SALAMANDER_PLUGINSORDER_SHOW; extern const char* SALAMANDER_PLUGINS_ISNETHOOD; extern const char* SALAMANDER_PLUGINS_USESPASSWDMAN; -// nasledujicich 8 retezcu je jen pro load konfigu verze 6 a nizsi, novejsi verze -// jiz pouzivaji SALAMANDER_PLUGINS_FUNCTIONS (ulozeni v bitech DWORDove masky funkci) +// the following eight strings are only for loading configuration version 6 and +// older; newer versions already use SALAMANDER_PLUGINS_FUNCTIONS (stored in bits +// of a DWORD mask of functions) extern const char* SALAMANDER_PLUGINS_PANELVIEW; extern const char* SALAMANDER_PLUGINS_PANELEDIT; extern const char* SALAMANDER_PLUGINS_CUSTPACK; @@ -1573,62 +1612,68 @@ extern const char* SALAMANDER_PLUGINS_LOADSAVE; extern const char* SALAMANDER_PLUGINS_VIEWER; extern const char* SALAMANDER_PLUGINS_FS; -// clipboard format pro SalIDataObject (znacka naseho IDataObjectu na clipboardu) +// clipboard format for SalIDataObject (marks our IDataObject on the clipboard) extern const char* SALCF_IDATAOBJECT; -// clipboard format pro CFakeDragDropDataObject (urcuje cestu, ktera se ma po dropu objevit -// v directory-line, command-line + blokuje drop do usermenu-toolbar); pokud je tazeno -// vic adresaru/souboru, je cesta prazdny retezec (drop do directory/command-line neni mozny) +// clipboard format for CFakeDragDropDataObject specifying the path that should +// appear after drop in the directory line or command line and blocking drop to +// the user menu toolbar; if multiple folders/files are dragged the path is an +// empty string (drop to directory/command line is not possible) extern const char* SALCF_FAKE_REALPATH; -// clipboard format pro CFakeDragDropDataObject (urcuje typ zdroje - 1=archiv, 2=FS) +// clipboard format for CFakeDragDropDataObject specifying the source type +// (1=archive, 2=FS) extern const char* SALCF_FAKE_SRCTYPE; -// clipboard format pro CFakeDragDropDataObject (jen je-li zdroj FS: zdrojova FS cesta) +// clipboard format for CFakeDragDropDataObject (only when the source is FS: +// source FS path) extern const char* SALCF_FAKE_SRCFSPATH; -// promenne pro CanChangeDirectory() a AllowChangeDirectory() -extern int ChangeDirectoryAllowed; // 0 znamena, ze je mozne menit adresar +// variables for CanChangeDirectory() and AllowChangeDirectory() +extern int ChangeDirectoryAllowed; // 0 means the directory can be changed extern BOOL ChangeDirectoryRequest; -// funkce obsluhujici automatickou zmenu aktualniho adresare na systemovy -// - kvuli odmapovavani z jinych softu a mazani adresaru zobrazenych Salamandrem +// function handling the automatic switch of the current directory to the system +// one-used when other software unmaps drives or deletes directories shown by +// Salamander BOOL CanChangeDirectory(); void AllowChangeDirectory(BOOL allow); -// promenna pro BeginStopRefresh() a EndStopRefresh() +// variable for BeginStopRefresh() and EndStopRefresh() extern int StopRefresh; -// po volani se neprovede zadny refresh adresare +// after calling no directory refresh will occur void BeginStopRefresh(BOOL debugSkipOneCaller = FALSE, BOOL debugDoNotTestCaller = FALSE); -// uvolni refreshovani -> pripadne posle WM_USER_SM_END_NOTIFY hlavnimu oknu (probehnou promeskane refreshe) +// releases refreshing -> possibly posts WM_USER_SM_END_NOTIFY to the main window +// so missed refreshes are processed void EndStopRefresh(BOOL postRefresh = TRUE, BOOL debugSkipOneCaller = FALSE, BOOL debugDoNotTestCaller = FALSE); -// promenna kontrolovana v hl. message-loope v "idle" casti, je-li TRUE, vyhleda a unloadne -// plug-iny s ShouldUnload==TRUE, rebuildne menu pluginum s ShouldRebuildMenu==TRUE + spusti -// prikazy postnute z pluginu + pozadovane prikazy Salamandera +// variable checked in the main message loop during the "idle" part; if TRUE, it unloads +// plugins with ShouldUnload==TRUE, rebuilds menus for plugins with ShouldRebuildMenu==TRUE, +// and runs commands posted from plugins plus requested Salamander commands extern BOOL ExecCmdsOrUnloadMarkedPlugins; -// promenna kontrolovana v hl. message-loope v "idle" casti, je-li TRUE, otevre Pack/Unpack -// dialog pro pluginy s OpenPackDlg==TRUE nebo OpenUnpackDlg==TRUE +// variable checked in the main message loop during the "idle" part; if TRUE, it opens the Pack/Unpack +// dialog for plugins with OpenPackDlg==TRUE or OpenUnpackDlg==TRUE extern BOOL OpenPackOrUnpackDlgForMarkedPlugins; -// promenna pro BeginStopIconRepaint() a EndStopIconRepaint() +// variable for BeginStopIconRepaint() and EndStopIconRepaint() extern int StopIconRepaint; extern BOOL PostAllIconsRepaint; -// po volani se neprovede zadny refresh ikony v panelech +// after calling no icon refresh in the panels takes place void BeginStopIconRepaint(); -// uvolni repaint -> pripadne posle WM_USER_REPAINTALLICONS hlavnimu oknu (obnova vsech ikon) +// releases repaint -> optionally posts WM_USER_REPAINTALLICONS to the main +// window (refresh of all icons) void EndStopIconRepaint(BOOL postRepaint = TRUE); -// promenna pro BeginStopStatusbarRepaint() a EndStopStatusbarRepaint() +// variable for BeginStopStatusbarRepaint() and EndStopStatusbarRepaint() extern int StopStatusbarRepaint; extern BOOL PostStatusbarRepaint; -// po volani se prestane prekreslovat throbber +// after calling the throbber stops repainting void BeginStopStatusbarRepaint(); -// uvolni repaint +// resumes repainting void EndStopStatusbarRepaint(); -// v modulu msgbox.cpp - centrovany messagebox podle pra parenta od hParent +// in module msgbox.cpp - center the message box according to the parent specified by hParent int SalMessageBox(HWND hParent, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType); int SalMessageBoxEx(const MSGBOXEX_PARAMS* params); -// vykresli ikonky z imagelistu s nastavenyma stylama +// draws icons from the image list with the specified styles #define IMAGE_STATE_FOCUSED 0x00000001 #define IMAGE_STATE_SELECTED 0x00000002 #define IMAGE_STATE_HIDDEN 0x00000004 @@ -1640,79 +1685,81 @@ BOOL StateImageList_Draw(CIconList* iconList, int imageIndex, HDC hDC, int xDst, DWORD state, CIconSizeEnum iconSize, DWORD iconOverlayIndex, const RECT* overlayRect, BOOL overlayOnly, BOOL iconOverlayFromPlugin, int pluginIconOverlaysCount, HICON* pluginIconOverlays); -DWORD GetImageListColorFlags(); // vrati ILC_COLOR??? podle verzi Windows - odladene pro pouziti imagelistu v listviewech +DWORD GetImageListColorFlags(); // returns the ILC_COLOR* flag for the current Windows version; tuned for using image lists in list views -// API GetOpenFileName/GetSaveFileName v pripade ze cesta k souboru (OPENFILENAME::lpstrFile) -// neexistuje (nebo obsahuje napriklad C:\) vrati FALSE a CommDlgExtendedError() == FNERR_INVALIDFILENAME. -// Proto zavadime jejich "bezpecnou" variantu, ktera tento pripad detekuje a pokusi se otevrit -// dialog pro Documents nebo Desktop. +// The GetOpenFileName/GetSaveFileName APIs return FALSE and set +// CommDlgExtendedError() to FNERR_INVALIDFILENAME when the file path in +// OPENFILENAME::lpstrFile does not exist (or contains e.g. C:\). To handle this +// case we introduce "safe" versions that detect the problem and try to open the +// dialog for Documents or Desktop instead. BOOL SafeGetOpenFileName(LPOPENFILENAME lpofn); BOOL SafeGetSaveFileName(LPOPENFILENAME lpofn); -extern char DecimalSeparator[5]; // "znaky" (max. 4 znaky) vytazene ze systemu -extern int DecimalSeparatorLen; // delka ve znacich bez nuly na konci +extern char DecimalSeparator[5]; // characters (max. 4) obtained from the system +extern int DecimalSeparatorLen; // length in characters without the terminating null extern char ThousandsSeparator[5]; extern int ThousandsSeparatorLen; -extern DWORD SalamanderStartTime; // cas startu Salamandera (GetTickCount) -extern DWORD SalamanderExceptionTime; // cas exceptiony v Salamanderu (GetTickCount) nebo cas posledniho vyvolani Bug Report dialogu +extern DWORD SalamanderStartTime; // Salamander start time (GetTickCount) +extern DWORD SalamanderExceptionTime; // time of the exception in Salamander (GetTickCount) or the last Bug Report dialog time -extern BOOL SkipOneActivateRefresh; // ma se preskocit refresh pri aktivaci hl. okna? (pro interni viewry) +extern BOOL SkipOneActivateRefresh; // should refresh be skipped when the main window is activated? (for internal viewers) -extern int MenuNewExceptionHasOccured; // spadlo uz menu New? (mozna prepsalo nekde pamet) -extern int FGIExceptionHasOccured; // spadlo uz SHGetFileInfo? -extern int ICExceptionHasOccured; // spadlo uz InvokeCommand? -extern int QCMExceptionHasOccured; // spadlo uz QueryContextMenu? -extern int OCUExceptionHasOccured; // spadlo uz OleUninitialize nebo CoUninitialize? -extern int GTDExceptionHasOccured; // spadlo uz GetTargetDirectory? -extern int SHLExceptionHasOccured; // spadlo uz neco z ShellLib? -extern int RelExceptionHasOccured; // spadlo uz nejaky volani IUnknown metody Release()? +extern int MenuNewExceptionHasOccured; // has the New menu crashed already? (maybe overwrote memory somewhere) +extern int FGIExceptionHasOccured; // has SHGetFileInfo crashed? +extern int ICExceptionHasOccured; // has InvokeCommand crashed? +extern int QCMExceptionHasOccured; // has QueryContextMenu crashed? +extern int OCUExceptionHasOccured; // has OleUninitialize or CoUninitialize failed? +extern int GTDExceptionHasOccured; // has GetTargetDirectory crashed? +extern int SHLExceptionHasOccured; // has something from ShellLib crashed? +extern int RelExceptionHasOccured; // has any IUnknown::Release() call crashed? -extern BOOL SalamanderBusy; // je Salamander busy? -extern DWORD LastSalamanderIdleTime; // GetTickCount() z okamziku, kdy SalamanderBusy naposledy presel na TRUE +extern BOOL SalamanderBusy; // is Salamander busy? +extern DWORD LastSalamanderIdleTime; // GetTickCount() from the moment SalamanderBusy last changed to TRUE -extern int PasteLinkIsRunning; // pokud je vetsi nez nula, probiha prave Past Shortcuts prikaz v jednom z panelu +extern int PasteLinkIsRunning; // when greater than zero a Paste Shortcuts command is in progress in one of the panels -extern BOOL CannotCloseSalMainWnd; // TRUE = nesmi dojit k zavreni hlavniho okna +extern BOOL CannotCloseSalMainWnd; // TRUE = the main window must not be closed -extern const char* DirColumnStr; // LoadStr(IDS_DIRCOLUMN) - pouziva se prilis casto, cachujeme -extern int DirColumnStrLen; // delka retezce -extern const char* ColExtStr; // LoadStr(IDS_COLUMN_NAME_EXT) - pouziva se prilis casto, cachujeme -extern int ColExtStrLen; // delka retezce -extern int TextEllipsisWidth; // sirka retezce "..." zobrazenho fontem 'Font' -extern int TextEllipsisWidthEnv; // sirka retezce "..." zobrazenho fontem 'FontEnv' -extern const char* ProgDlgHoursStr; // LoadStr(IDS_PROGDLGHOURS) - pouziva se prilis casto, cachujeme -extern const char* ProgDlgMinutesStr; // LoadStr(IDS_PROGDLGMINUTES) - pouziva se prilis casto, cachujeme -extern const char* ProgDlgSecsStr; // LoadStr(IDS_PROGDLGSECS) - pouziva se prilis casto, cachujeme +extern const char* DirColumnStr; // LoadStr(IDS_DIRCOLUMN) - used very often, cached +extern int DirColumnStrLen; // string length +extern const char* ColExtStr; // LoadStr(IDS_COLUMN_NAME_EXT) - used very often, cached +extern int ColExtStrLen; // string length +extern int TextEllipsisWidth; // width of "..." drawn with font 'Font' +extern int TextEllipsisWidthEnv; // width of "..." drawn with font 'FontEnv' +extern const char* ProgDlgHoursStr; // LoadStr(IDS_PROGDLGHOURS) - used very often, cached +extern const char* ProgDlgMinutesStr; // LoadStr(IDS_PROGDLGMINUTES) - used very often, cached +extern const char* ProgDlgSecsStr; // LoadStr(IDS_PROGDLGSECS) - used very often, cached -extern char FolderTypeName[80]; // file-type pro vsechny adresare (ziskany ze systemoveho adresare) -extern int FolderTypeNameLen; // delka retezce FolderTypeName -extern const char* UpDirTypeName; // LoadStr(IDS_UPDIRTYPENAME) - pouziva se prilis casto, cachujeme -extern int UpDirTypeNameLen; // delka retezce -extern const char* CommonFileTypeName; // LoadStr(IDS_COMMONFILETYPE) - pouziva se prilis casto, cachujeme -extern int CommonFileTypeNameLen; // delka retezce CommonFileTypeName -extern const char* CommonFileTypeName2; // LoadStr(IDS_COMMONFILETYPE2) - pouziva se prilis casto, cachujeme +extern char FolderTypeName[80]; // file type for all directories (obtained from the system directory) +extern int FolderTypeNameLen; // length of FolderTypeName +extern const char* UpDirTypeName; // LoadStr(IDS_UPDIRTYPENAME) - used very often, cached +extern int UpDirTypeNameLen; // string length +extern const char* CommonFileTypeName; // LoadStr(IDS_COMMONFILETYPE) - used very often, cached +extern int CommonFileTypeNameLen; // length of CommonFileTypeName +extern const char* CommonFileTypeName2; // LoadStr(IDS_COMMONFILETYPE2) - used very often, cached -extern char WindowsDirectory[MAX_PATH]; // cachovany vysledek GetWindowsDirectory +extern char WindowsDirectory[MAX_PATH]; // cached result of GetWindowsDirectory //#ifdef MSVC_RUNTIME_CHECKS -#define RTC_ERROR_DESCRIPTION_SIZE 2000 // buffer pro popis run-time check chyby +#define RTC_ERROR_DESCRIPTION_SIZE 2000 // buffer for the run-time check error description extern char RTCErrorDescription[RTC_ERROR_DESCRIPTION_SIZE]; //#endif // MSVC_RUNTIME_CHECKS -// cesta, kde vytvorime bug report a minidump, umisteni: do Visty u salamand.exe, ve Viste (a dale) v CSIDL_APPDATA + "\\Open Salamander" +// path where the bug report and minidump are created: before Vista, next to +// salamand.exe; in Vista and later, in CSIDL_APPDATA + "\\Open Salamander" extern char BugReportPath[MAX_PATH]; -// nazev souboru, ktery bude importovan (pokud existuje) do registry +// name of the file that will be imported into the registry if it exists extern char ConfigurationName[MAX_PATH]; extern BOOL ConfigurationNameIgnoreIfNotExists; -extern HWND PluginProgressDialog; // pokud si plug-in otevre progress dialog, je zde jeho HWND, jinak NULL -extern HWND PluginMsgBoxParent; // parent pro messageboxy plug-inu (hlavni okno, Plugins dialog, atd.) +extern HWND PluginProgressDialog; // if a plugin opens a progress dialog this is its HWND, otherwise NULL +extern HWND PluginMsgBoxParent; // parent for plugin message boxes (main window, Plugins dialog, etc.) -extern BOOL CriticalShutdown; // TRUE = probiha "critical shutdown", neni cas se ptat, rychle koncime, 5s do zabiti +extern BOOL CriticalShutdown; // TRUE = "critical shutdown" in progress; no time to ask, exiting quickly, 5s until kill -// "preklad" POSIX jmena na MS +// "translation" of POSIX names to MS equivalents #define itoa _itoa #define stricmp _stricmp #define strnicmp _strnicmp @@ -1722,11 +1769,11 @@ extern BOOL CriticalShutdown; // TRUE = probiha "critical shutdown", neni cas se #define SKILL_LEVEL_INTERMEDIATE 1 #define SKILL_LEVEL_ADVANCED 2 -// konvertuje promennou CConfiguration::SkillLevel do SkillLevel pro menu. +// converts the CConfiguration::SkillLevel variable to the menu SkillLevel DWORD CfgSkillLevelToMenu(BYTE cfgSkillLevel); -// atributy, ktere ukazujeme v panelu a kteryma je treba maskovat napriklad pri porovnani adresaru -// POZOR: FILE_ATTRIBUTE_DIRECTORY nezobrazujeme jako atribut, takze v masce nema co delat +// Attributes shown in the panel which must also be masked when comparing directories. +// NOTE: FILE_ATTRIBUTE_DIRECTORY is not displayed as an attribute so it has no place in the mask. #define DISPLAYED_ATTRIBUTES (FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | \ FILE_ATTRIBUTE_SYSTEM | \ FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_ENCRYPTED | \ @@ -1757,16 +1804,17 @@ DWORD CfgSkillLevelToMenu(BYTE cfgSkillLevel); #define IDT_DELAYEDTHROBBER 950 #define IDT_UPDATETASKLIST 951 -// POZOR: skoro vsechny funkce v teto sekci pri chybe zobrazuji hlaseni o LOAD / SAVE -// konfigurace, coz z nich dela nevhodne pro bezny pristup do Registry, -// reseni viz funkce na zacatku regwork.h: OpenKeyAux, CreateKeyAux, atd. +// NOTE: nearly all functions in this section display LOAD/SAVE configuration +// error messages on failure, which makes them unsuitable for general +// registry access. See the functions at the beginning of regwork.h: +// OpenKeyAux, CreateKeyAux, etc. BOOL ClearKey(HKEY key); BOOL CreateKey(HKEY hKey, const char* name, HKEY& createdKey); BOOL OpenKey(HKEY hKey, const char* name, HKEY& openedKey); void CloseKey(HKEY key); BOOL DeleteKey(HKEY hKey, const char* name); BOOL DeleteValue(HKEY hKey, const char* name); -// pro dataSize = -1 si funkce napocita delku stringu pres strlen +// when dataSize is -1 the function calculates the string length using strlen BOOL SetValue(HKEY hKey, const char* name, DWORD type, const void* data, DWORD dataSize); BOOL GetValue(HKEY hKey, const char* name, DWORD type, void* buffer, DWORD bufferSize); @@ -1791,30 +1839,30 @@ BOOL ImportConfiguration(HWND hParent, const char* fileName, BOOL ignoreIfNotExi class CHighlightMasks; void UpdateDefaultColors(SALCOLOR* colors, CHighlightMasks* highlightMasks, BOOL processColors, BOOL processMasks); -extern BOOL ImageDragging; // prave se tahne image -extern BOOL ImageDraggingVisible; // je prave image zobrazeny? -void ImageDragBegin(int width, int height, int dxHotspot, int dyHotspot); // velikost tazeneho obrazku -void ImageDragEnd(); // ukonceni tazeni -BOOL ImageDragInterfereRect(const RECT* rect); // rect je v obrazovkovych souradnicich, zjistit, jestli tazena polozka zasahuje do rect -void ImageDragEnter(int x, int y); // x a y jsou obrazovkove souradnice -void ImageDragMove(int x, int y); // x a y jsou obrazovkove souradnice +extern BOOL ImageDragging; // an image is being dragged +extern BOOL ImageDraggingVisible; // is the image currently visible? +void ImageDragBegin(int width, int height, int dxHotspot, int dyHotspot); // size of the dragged image +void ImageDragEnd(); // end dragging +BOOL ImageDragInterfereRect(const RECT* rect); // rect is in screen coordinates, check whether the dragged item intersects it +void ImageDragEnter(int x, int y); // x and y are screen coordinates +void ImageDragMove(int x, int y); // x and y are screen coordinates void ImageDragLeave(); -void ImageDragShow(BOOL show); // zhasne / rozsviti, neovlivni ImageDragging, pouze ImageDraggingVisible +void ImageDragShow(BOOL show); // hides/shows; does not affect ImageDragging, only ImageDraggingVisible -// nastavuje kurzor ve tvaru ruky +// sets the cursor to a hand shape HCURSOR SetHandCursor(); //****************************************************************************** // // CreateToolbarBitmaps // -// IN: hInstance - instance, ve ktere lezi bitmapa s resID -// resID - identifikator vstupni bitmapy -// transparent - tato barva bude pruhledna -// bkColorForAlpha - barva, ktera bude prosvitat pod alpha castma ikonek (WinXP) -// OUT: hMaskBitmap - maska (b&w) -// hGrayBitmap - sedive provedeni -// hColorBitmap - barevne provedeni +// IN: hInstance - instance containing the bitmap with resID +// resID - identifier of the input bitmap +// transparent - this color will be transparent +// bkColorForAlpha - color showing through the alpha parts of icons (WinXP) +// OUT: hMaskBitmap - mask (b&w) +// hGrayBitmap - grayscale variant +// hColorBitmap - color variant // struct CSVGIcon @@ -1831,9 +1879,8 @@ BOOL CreateToolbarBitmaps(HINSTANCE hInstance, int resID, COLORREF transparent, // // CreateGrayscaleAndMaskBitmaps // -// Vytvori novou bitmapu o hloubce 24 bitu, nakopiruje do ni zdrojovou -// bitmapu a prevede ji na stupne sedi. Zaroven pripravi druhou bitmapu -// s maskou dle transparentni barvy. +// Creates a new 24-bit bitmap, copies the source bitmap into it and converts it to grayscale. +// At the same time prepares another bitmap with a mask based on the transparent color. // BOOL CreateGrayscaleAndMaskBitmaps(HBITMAP hSource, COLORREF transparent, @@ -1862,83 +1909,82 @@ DWORD UpdateCrc32(const void* buffer, DWORD count, DWORD crcVal); //****************************************************************************** // -// Rizeni Idle procesingu (CMainWindow::OnEnterIdle) +// Idle processing control (CMainWindow::OnEnterIdle) // -// promenne jsou pro snadnou dostupnost globalni -// a ne jako atributy tridy CMainWindow +// variables are global for easy access and not attributes of CMainWindow // -extern BOOL IdleRefreshStates; // pokud je nastavena, budou pri nejblizim CMainWindow::OnEnterIdle vytazeny stavove promenne pro commandy (toolbar, menu) -extern BOOL IdleForceRefresh; // je-li nastavena IdleRefreshStates, nastaveni promenne IdleForceRefresh vyradi cache na urovni Salamandera -extern BOOL IdleCheckClipboard; // pokud je IdleRefreshStates==TRUE a zaroven je nastavena tato promenna, bude se kontrolovat tak clipboard (casove narocne) - -// ".." neni pocitano mezi soubory|adresare -extern DWORD EnablerUpDir; // existuje parent directory? -extern DWORD EnablerRootDir; // nejsme jeste v rootu? (pozor: UNC root ma updir, ale je to root) -extern DWORD EnablerForward; // je v historii dostupny forward? -extern DWORD EnablerBackward; // je v historii dostupny backward? -extern DWORD EnablerFileOnDisk; // focus je na souboru && panel je disk -extern DWORD EnablerFileOnDiskOrArchive; // focus je na souboru && panel je disk nebo archiv -extern DWORD EnablerFileOrDirLinkOnDisk; // focus je na souboru nebo adresari linku && panel je disk -extern DWORD EnablerFiles; // focus|select je na souborech|adresarich -extern DWORD EnablerFilesOnDisk; // focus|select je na souborech|adresarich && panel je disk -extern DWORD EnablerFilesOnDiskCompress; // focus|select je na souborech|adresarich && panel je disk && je podporovana komprese -extern DWORD EnablerFilesOnDiskEncrypt; // focus|select je na souborech|adresarich && panel je disk && je podporovano sifrovani -extern DWORD EnablerFilesOnDiskOrArchive; // focus|select je na souborech|adresarich && panel je disk nebo archiv -extern DWORD EnablerOccupiedSpace; // panel je disk nebo archiv s VALID_DATA_SIZE a zaroven plati EnablerFilesOnDiskOrArchive -extern DWORD EnablerFilesCopy; // focus|select je na souborech|adresarich && panel je disk, archiv nebo FS s podporou "copy from fs" -extern DWORD EnablerFilesMove; // focus|select je na souborech|adresarich && panel je disk nebo FS s podporou "move from fs" -extern DWORD EnablerFilesDelete; // focus|select je na souborech|adresarich && (panel je disk, editovatelny archiv nebo FS s podporou "delete") -extern DWORD EnablerFileDir; // focus je na souboru|adresari -extern DWORD EnablerFileDirANDSelected; // focus je na souboru|adresari && jsou oznaceny nejake soubory|adresare -extern DWORD EnablerQuickRename; // focus je na souboru|adresari && panel je disk nebo FS (s podporou quick-rename) -extern DWORD EnablerOnDisk; // panel je disk -extern DWORD EnablerCalcDirSizes; // panel je disk nebo archiv s VALID_DATA_SIZE -extern DWORD EnablerPasteFiles; // je mozne provest Paste? (soubory na clipboardu) (vyuzite jako pamet posledniho stavu clipboardu pro 'pasteFiles' v CMainWindow::RefreshCommandStates()) -extern DWORD EnablerPastePath; // je mozne provest Paste? (text cesty na clipboardu) (vyuzite jako pamet posledniho stavu clipboardu pro 'pastePath' v CMainWindow::RefreshCommandStates()) -extern DWORD EnablerPasteLinks; // je mozne provest Paste Links? (soubory pres "copy" na clipboardu) (vyuzite jako pamet posledniho stavu clipboardu pro 'pasteLinks' v CMainWindow::RefreshCommandStates()) -extern DWORD EnablerPasteSimpleFiles; // jsou na clipboardu soubory/adresare z jedine cesty? (aneb: je sance na Paste do archivu nebo FS?) -extern DWORD EnablerPasteDefEffect; // jaky je defaultni paste-effect, muze byt i kombinace DROPEFFECT_COPY+DROPEFFECT_MOVE (aneb: slo o Copy nebo Cut?) -extern DWORD EnablerPasteFilesToArcOrFS; // je mozny Paste souboru do archivu/FS v aktualnim panelu? (v panelu je archiv/FS && EnablerPasteSimpleFiles && operace podle EnablerPasteDefEffect je mozna) -extern DWORD EnablerPaste; // je mozne provest Paste? (soubory na clipboardu && panel je disk || je mozne provest paste do archivu nebo FS || text cesty na clipboardu) -extern DWORD EnablerPasteLinksOnDisk; // je mozne provest Paste Links a panel je disk? -extern DWORD EnablerSelected; // jsou oznaceny nejake soubory|adresare -extern DWORD EnablerUnselected; // existuje alespon jeden neoznaceny soubor|adresar (UpDir ".." se neuvazuje) -extern DWORD EnablerHiddenNames; // pole HiddenNames obsahuje nejake nazvy -extern DWORD EnablerSelectionStored; // je ulozena selection v OldSelection aktivniho panelu? -extern DWORD EnablerGlobalSelStored; // je ulozena selection v GlobalSelection? -extern DWORD EnablerSelGotoPrev; // existuje pred focusem vybrana polozka? -extern DWORD EnablerSelGotoNext; // existuje za focusem vybrana polozka? -extern DWORD EnablerLeftUpDir; // existuje v levem panelu parent directory? -extern DWORD EnablerRightUpDir; // existuje v pravem panelu parent directory? -extern DWORD EnablerLeftRootDir; // nejsme jeste v levem panelu v rootu? (pozor: UNC root ma updir, ale je to root) -extern DWORD EnablerRightRootDir; // nejsme jeste v pravem panelu v rootu? (pozor: UNC root ma updir, ale je to root) -extern DWORD EnablerLeftForward; // je v historii leveho panelu dostupny forward? -extern DWORD EnablerRightForward; // je v historii praveho panelu dostupny forward? -extern DWORD EnablerLeftBackward; // je v historii leveho panelu dostupny backward? -extern DWORD EnablerRightBackward; // je v historii praveho panelu dostupny backward? -extern DWORD EnablerFileHistory; // je v view/edit historii dostupny soubor? -extern DWORD EnablerDirHistory; // je v directory historii dostupny adresar? -extern DWORD EnablerCustomizeLeftView; // je mozne konfigurovat sloupce pro levy pohled? -extern DWORD EnablerCustomizeRightView; // je mozne konfigurovat sloupce pro pravy pohled? -extern DWORD EnablerDriveInfo; // je mozne zobrazit Drive Info? -extern DWORD EnablerCreateDir; // panel je disk nebo FS (s podporou create-dir) -extern DWORD EnablerViewFile; // focus je na souboru && panel je disk, archiv nebo FS (s podporou view-file) -extern DWORD EnablerChangeAttrs; // focus|select je na souborech|adresarich && panel je disk nebo FS (s podporou change-attributes) -extern DWORD EnablerShowProperties; // focus|select je na souborech|adresarich && panel je disk nebo FS (s podporou show-properties) -extern DWORD EnablerItemsContextMenu; // focus|select je na souborech|adresarich && panel je disk nebo FS (s podporou context-menu) -extern DWORD EnablerOpenActiveFolder; // panel je disk nebo FS (s podporou open-active-folder) -extern DWORD EnablerPermissions; // focus|select je na souborech|adresarich && panel je disk, bezime nejmene na W2K, disk umi ACL (NTFS) +extern BOOL IdleRefreshStates; // when set, the next CMainWindow::OnEnterIdle will update command states (toolbar, menu) +extern BOOL IdleForceRefresh; // if IdleRefreshStates is set, setting IdleForceRefresh bypasses Salamander's cache +extern BOOL IdleCheckClipboard; // when IdleRefreshStates is TRUE and this flag is set, the clipboard is checked as well (time consuming) + +// ".." is not counted among files/directories +extern DWORD EnablerUpDir; // is a parent directory available? +extern DWORD EnablerRootDir; // are we already at the root? (note: UNC roots have an updir but are still roots) +extern DWORD EnablerForward; // is forward available in history? +extern DWORD EnablerBackward; // is backward available in history? +extern DWORD EnablerFileOnDisk; // focus is on a file and the panel is disk-based +extern DWORD EnablerFileOnDiskOrArchive; // focus is on a file and the panel is disk or archive +extern DWORD EnablerFileOrDirLinkOnDisk; // focus is on a file or directory link and the panel is disk +extern DWORD EnablerFiles; // focus/selection is on files/directories +extern DWORD EnablerFilesOnDisk; // focus/selection is on files/directories and the panel is a disk +extern DWORD EnablerFilesOnDiskCompress; // focus/selection is on files/directories and the panel is a disk that supports compression +extern DWORD EnablerFilesOnDiskEncrypt; // focus/selection is on files/directories and the panel is a disk that supports encryption +extern DWORD EnablerFilesOnDiskOrArchive; // focus/selection is on files/directories and the panel is disk or archive +extern DWORD EnablerOccupiedSpace; // panel is disk or archive with VALID_DATA_SIZE and EnablerFilesOnDiskOrArchive holds +extern DWORD EnablerFilesCopy; // focus/selection is on files/directories and the panel is disk, archive or FS supporting "copy from fs" +extern DWORD EnablerFilesMove; // focus/selection is on files/directories and the panel is disk or FS supporting "move from fs" +extern DWORD EnablerFilesDelete; // focus/selection is on files/directories and the panel is a disk, an editable archive, or an FS supporting "delete" +extern DWORD EnablerFileDir; // focus is on a file/directory +extern DWORD EnablerFileDirANDSelected; // focus is on a file/directory and some files/directories are selected +extern DWORD EnablerQuickRename; // focus is on a file/directory and the panel is disk or FS (with quick-rename support) +extern DWORD EnablerOnDisk; // panel is a disk +extern DWORD EnablerCalcDirSizes; // panel is a disk or archive with VALID_DATA_SIZE +extern DWORD EnablerPasteFiles; // can Paste be performed? (files on the clipboard) used as memory of the last clipboard state for 'pasteFiles' in CMainWindow::RefreshCommandStates() +extern DWORD EnablerPastePath; // can Paste be performed? (path text on the clipboard) used as memory of the last clipboard state for 'pastePath' in CMainWindow::RefreshCommandStates() +extern DWORD EnablerPasteLinks; // can Paste Links be performed? (files copied to the clipboard) used as memory of the last clipboard state for 'pasteLinks' in CMainWindow::RefreshCommandStates() +extern DWORD EnablerPasteSimpleFiles; // are there files/directories from a single path on the clipboard? (chance to Paste into an archive or FS) +extern DWORD EnablerPasteDefEffect; // what is the default paste effect; may be a combination of DROPEFFECT_COPY+DROPEFFECT_MOVE (Copy or Cut?) +extern DWORD EnablerPasteFilesToArcOrFS; // can files be pasted into the archive/FS in the current panel? (the panel is archive/FS && EnablerPasteSimpleFiles && the operation according to EnablerPasteDefEffect is allowed) +extern DWORD EnablerPaste; // can Paste be performed? (files on clipboard && panel is disk || paste into archive/FS is possible || path text on clipboard) +extern DWORD EnablerPasteLinksOnDisk; // can Paste Links be performed and the panel is a disk? +extern DWORD EnablerSelected; // are any files/directories selected +extern DWORD EnablerUnselected; // is there at least one unselected file/directory (UpDir ".." not considered) +extern DWORD EnablerHiddenNames; // the HiddenNames array contains some names +extern DWORD EnablerSelectionStored; // is a selection stored in OldSelection of the active panel? +extern DWORD EnablerGlobalSelStored; // is a selection stored in GlobalSelection? +extern DWORD EnablerSelGotoPrev; // is there a selected item before the focus? +extern DWORD EnablerSelGotoNext; // is there a selected item after the focus? +extern DWORD EnablerLeftUpDir; // does the left panel have a parent directory? +extern DWORD EnablerRightUpDir; // does the right panel have a parent directory? +extern DWORD EnablerLeftRootDir; // are we not yet at the root in the left panel? (UNC roots have an updir but are still roots) +extern DWORD EnablerRightRootDir; // are we not yet at the root in the right panel? (UNC roots have an updir but are still roots) +extern DWORD EnablerLeftForward; // is forward available in the left panel history? +extern DWORD EnablerRightForward; // is forward available in the right panel history? +extern DWORD EnablerLeftBackward; // is backward available in the left panel history? +extern DWORD EnablerRightBackward; // is backward available in the right panel history? +extern DWORD EnablerFileHistory; // is a file available in the view/edit history? +extern DWORD EnablerDirHistory; // is a directory available in the directory history? +extern DWORD EnablerCustomizeLeftView; // can columns be configured for the left view? +extern DWORD EnablerCustomizeRightView; // can columns be configured for the right view? +extern DWORD EnablerDriveInfo; // can Drive Info be displayed? +extern DWORD EnablerCreateDir; // panel is disk or FS (supports create-dir) +extern DWORD EnablerViewFile; // focus is on a file and the panel is disk, archive or FS (supports view-file) +extern DWORD EnablerChangeAttrs; // focus/selection is on files/directories and the panel is disk or FS (supports change-attributes) +extern DWORD EnablerShowProperties; // focus/selection is on files/directories and the panel is disk or FS (supports show-properties) +extern DWORD EnablerItemsContextMenu; // focus/selection is on files/directories and the panel is disk or FS (supports context menu) +extern DWORD EnablerOpenActiveFolder; // panel is a disk or an FS (with open-active-folder support) +extern DWORD EnablerPermissions; // focus/selection is on files/directories and the panel is a disk; running at least on W2K with NTFS supporting ACLs //****************************************************************************** // // ToolBar Bitmap indexes // -// Polozky lze pridavat do pole. -// Pole je rozdeleno na dve casti. V Prnim jsou indexy, ke kterym se v bitmape -// opravdu nachazeji obrazky. -// Pak nasleduji indexy, na ktere jsou vytazeny ikonky z shell32.dll. -// Tyto dve skupiny musi byt vzdy celistve a neni mozne indexy stridat. +// Items can be added to the array. +// The array is divided into two parts. The first contains indexes with real +// images in the bitmap. After that come indexes with icons pulled from +// shell32.dll. These two groups must always be contiguous and the indexes cannot +// be mixed. // #define IDX_TB_CONNECTNET 0 // Connect Network Drive @@ -1996,8 +2042,8 @@ extern DWORD EnablerPermissions; // focus|select je na souborech|adresa #define IDX_TB_UNSELECTALL 52 // Unselect all #define IDX_TB_VIEW_MODE 53 // View Mode #define IDX_TB_HOTPATHS 54 // Hot Paths -#define IDX_TB_FOCUS 55 // Focus (zelena sipka) -#define IDX_TB_STOP 56 // Stop (cervene kolecko s krizkem) +#define IDX_TB_FOCUS 55 // Focus (green arrow) +#define IDX_TB_STOP 56 // Stop (red circle with a cross) #define IDX_TB_EMAIL 57 // Email Files #define IDX_TB_EDITNEW 58 // Edit New #define IDX_TB_PASTESHORTCUT 59 // Paste Shortcut @@ -2020,9 +2066,9 @@ extern DWORD EnablerPermissions; // focus|select je na souborech|adresa #define IDX_TB_SHOW_ALL 76 // Show All Names #define IDX_TB_SMART_COLUMN_MODE 77 // Smart Column Mode -#define IDX_TB_FD 78 // first "dynamic added" index -// nasledujici ikony budou pridany k bitmape dynamicky -// a nektere budou nacteny z shell32.dll +#define IDX_TB_FD 78 // first "dynamically added" index +// the following icons will be added to the bitmap dynamically +// and some will be loaded from shell32.dll #define IDX_TB_CHANGEDRIVEL IDX_TB_FD + 0 // Change Drive Left #define IDX_TB_CHANGEDRIVER IDX_TB_FD + 1 // Change Drive Right @@ -2036,242 +2082,228 @@ extern DWORD EnablerPermissions; // focus|select je na souborech|adresa #define IDX_TB_OPENFONTS IDX_TB_FD + 9 // Open Fonts #define IDX_TB_OPENMYDOC IDX_TB_FD + 10 // Open Documents -#define IDX_TB_COUNT IDX_TB_FD + 11 // pocet bitmap vcetne tahanych z shell32.dll +#define IDX_TB_COUNT IDX_TB_FD + 11 // number of bitmaps including those pulled from shell32.dll //****************************************************************************** // // Custom Exceptions // -#define OPENSAL_EXCEPTION_RTC 0xE0EA4321 // vyvolame v rtc callbacku -#define OPENSAL_EXCEPTION_BREAK 0xE0EA4322 // vyvolame v pripade breaku (z jineho salama nebo promoci salbreak) +#define OPENSAL_EXCEPTION_RTC 0xE0EA4321 // raised in the RTC callback +#define OPENSAL_EXCEPTION_BREAK 0xE0EA4322 // raised when breaking from another Salamander or via salbreak //****************************************************************************** // -// Sada promennych a funkci pro otevirani asociaci pomoci SalOpen.exe +// Set of variables and functions for opening associations via SalOpen.exe // -// sdilena pamet +// shared memory extern HANDLE SalOpenFileMapping; extern void* SalOpenSharedMem; -// uvolneni sluzby +// release the service void ReleaseSalOpen(); -// spusteni salopen.exe a predani 'fileName' pres sdilenou pamet -// vraci TRUE pokud se to povedlo, jinak FALSE (asociace by se mela spustit jinak) +// launch salopen.exe and pass 'fileName' via shared memory +// returns TRUE on success, otherwise FALSE (the association should be launched another way) BOOL SalOpenExecute(HWND hWindow, const char* fileName); //****************************************************************************** -// mapovani salCmd (cislo prikazu Salamandera spousteneho z plug-inu, viz SALCMD_XXX) -// na cislo prikazu pro WM_COMMAND +// mapping salCmd (the Salamander command number from a plugin, see SALCMD_XXX) +// to the command number for WM_COMMAND int GetWMCommandFromSalCmd(int salCmd); //****************************************************************************** -// pocet polozek v poli SalamanderConfigurationRoots +// number of items in the SalamanderConfigurationRoots array #define SALCFG_ROOTS_COUNT 83 -// id hlavniho threadu (platne az po vstupu do WinMain()) +// ID of the main thread (valid only after entering WinMain()) extern DWORD MainThreadID; -extern BOOL IsNotAlphaNorNum[256]; // pole TRUE/FALSE pro znaky (TRUE = neni pismeno ani cislice) -extern BOOL IsAlpha[256]; // pole TRUE/FALSE pro znaky (TRUE = pismeno) +extern BOOL IsNotAlphaNorNum[256]; // TRUE/FALSE array for characters (TRUE = not a letter or digit) +extern BOOL IsAlpha[256]; // TRUE/FALSE array for characters (TRUE = letter) -extern int UserCharset; // defaultni useruv charset pro fonty +extern int UserCharset; // user's default charset for fonts -// granularita alokaci (potreba pro pouzivani souboru mapovanych do pameti) +// allocation granularity (needed when using memory-mapped files) extern DWORD AllocationGranularity; -// ma se cekat na pusteni ESC pred zacatkem listovani cesty v panelu? +// should we wait for ESC to be released before starting to list the path in the panel? extern BOOL WaitForESCReleaseBeforeTestingESC; -// vrati pozici v screen coord., kde se ma vybalit context menu -// pouziva se pri vybalovani contextoveho menu pomoci klavesnice (Shift+F10 nebo VK_APP) +// returns the screen coordinates where the context menu should appear +// used when invoking the context menu via keyboard (Shift+F10 or VK_APP) void GetListViewContextMenuPos(HWND hListView, POINT* p); -// na zaklade barevne hloubky displeje urci, jestli pouzivat 256 barevne -// nebo 16 barevne bitmapy. +// based on the display color depth decides whether to use 256-color +// or 16-color bitmaps BOOL Use256ColorsBitmap(); -// obnovi focus ve zdrojovem panelu (pouziva se pokud mizi focus - po disablovani hl. okna, atp.) +// restores focus in the source panel (used when focus disappears after disabling the main window, etc.) void RestoreFocusInSourcePanel(); #define ISSLGINCOMPLETE_SIZE 200 extern char IsSLGIncomplete[ISSLGINCOMPLETE_SIZE]; //****************************************************************************** -// enumerace jmen souboru z panelu/Findu pro viewery +// enumeration of file names from panels/Find for viewers -// init+release dat spojenych s enumeraci +// initialization and release of data associated with enumeration void InitFileNamesEnumForViewers(); void ReleaseFileNamesEnumForViewers(); enum CFileNamesEnumRequestType { - fnertFindNext, // hledame dalsi soubor ve zdroji - fnertFindPrevious, // hledame predchozi soubor ve zdroji - fnertIsSelected, // zjistujeme oznaceni souboru ve zdroji - fnertSetSelection, // nastavujeme oznaceni souboru ve zdroji + fnertFindNext, // look for the next file in the source + fnertFindPrevious, // look for the previous file in the source + fnertIsSelected, // query whether the file is selected in the source + fnertSetSelection, // set the selection state of the file in the source }; struct CFileNamesEnumData { - // pozadavek: - int RequestUID; // cislo pozadavku - CFileNamesEnumRequestType RequestType; // typ pozadavku + // request: + int RequestUID; // request ID + CFileNamesEnumRequestType RequestType; // type of request int SrcUID; int LastFileIndex; char LastFileName[MAX_PATH]; BOOL PreferSelected; BOOL OnlyAssociatedExtensions; - CPluginInterfaceAbstract* Plugin; // pouziva se pri 'OnlyAssociatedExtensions'==TRUE, oznacuje pro jaky plugin filtrovat jmena souboru ('Plugin'==NULL = interni viewer) + CPluginInterfaceAbstract* Plugin; // used when 'OnlyAssociatedExtensions'==TRUE; designates which plugin to filter file names for ('Plugin'==NULL = internal viewer) char FileName[MAX_PATH]; BOOL Select; - BOOL TimedOut; // TRUE pokud uz na vysledek nikdo neceka (zbytecne provadet hledani jmena) + BOOL TimedOut; // TRUE when nobody is waiting for the result anymore (searching the name would be pointless) - // vysledek: - BOOL Found; // TRUE pokud bylo nalezeno pozadovane jmeno souboru + // result: + BOOL Found; // TRUE when the desired file name was found BOOL NoMoreFiles; BOOL SrcBusy; BOOL IsFileSelected; }; -// sekce pro praci s daty spojenymi s enumeraci (FileNamesEnumSources, FileNamesEnumData, -// FileNamesEnumDone, NextRequestUID a NextSourceUID) +// section for handling enumeration data (FileNamesEnumSources, FileNamesEnumData, +// FileNamesEnumDone, NextRequestUID and NextSourceUID) extern CRITICAL_SECTION FileNamesEnumDataSect; -// struktura s pozadavkem+vysledky enumerace +// structure containing the enumeration request and results extern CFileNamesEnumData FileNamesEnumData; -// event je "signaled" jakmile zdroj naplni vysledek do FileNamesEnumData +// the event is signaled once the source fills FileNamesEnumData with the result extern HANDLE FileNamesEnumDone; -#define FILENAMESENUM_TIMEOUT 1000 // timeout pro doruceni zpravy WM_USER_ENUMFILENAMES oknu zdroje +#define FILENAMESENUM_TIMEOUT 1000 // timeout for delivering WM_USER_ENUMFILENAMES to the source window -// vraci TRUE pokud je zdroj enumerace panel, v 'panel' pak vraci PANEL_LEFT nebo -// PANEL_RIGHT; pokud nebyl zdroj enumerace nalezen nebo jde o Find okno, vraci FALSE +// returns TRUE if the enumeration source is a panel; 'panel' then receives +// PANEL_LEFT or PANEL_RIGHT. Returns FALSE if the enumeration source was not +// found or if it is a Find window BOOL IsFileEnumSourcePanel(int srcUID, int* panel); -// vraci dalsi jmeno souboru pro viewer ze zdroje (levy/pravy panel nebo Findy); -// 'srcUID' je unikatni identifikator zdroje (predava se jako parametr pri otevirani -// vieweru); 'lastFileIndex' (nesmi byt NULL) je IN/OUT parametr, ktery by plugin mel -// menit jen pokud chce vratit jmeno prvniho souboru, v tomto pripade nastavit 'lastFileIndex' -// na -1; pocatecni hodnota 'lastFileIndex' se predava jako parametr pri otevirani -// vieweru; 'lastFileName' je plne jmeno aktualniho souboru (prazdny retezec pokud neni -// zname, napr. je-li 'lastFileIndex' -1); je-li 'preferSelected' TRUE a aspon jedno -// jmeno oznacene, budou se vracet oznacena jmena; je-li 'onlyAssociatedExtensions' -// TRUE, vraci jen soubory s priponou asociovanou s viewerem tohoto pluginu (F3 na tomto -// souboru by se pokusilo otevrit viewer tohoto pluginu + ignoruje pripadne zastineni -// viewerem jineho pluginu); 'fileName' je buffer pro ziskane jmeno (velikost alespon -// MAX_PATH); vraci TRUE pokud se podari jmeno ziskat; vraci FALSE pri chybe: zadne -// dalsi jmeno souboru ve zdroji neni (neni-li 'noMoreFiles' NULL, vraci se v nem TRUE), -// zdroj je zaneprazdnen (nezpracovava zpravy; neni-li 'srcBusy' NULL, vraci se v nem -// TRUE), jinak zdroj prestal existovat (zmena cesty v panelu, zmena razeni, atp.) +// Returns the next file name for the viewer from the source (left/right panel or Find window). +// 'srcUID' is the unique identifier of the source (it is passed as a parameter when opening +// the viewer). 'lastFileIndex' (must not be NULL) is an IN/OUT parameter that the plugin should +// change only if it wants to return the first file name; in that case, set 'lastFileIndex' +// to -1. The initial value of 'lastFileIndex' is passed as a parameter when opening the +// viewer. 'lastFileName' is the full name of the current file (an empty string if it is not +// known, for example if 'lastFileIndex' is -1). If 'preferSelected' is TRUE and at least one +// name is selected, selected names are returned. If 'onlyAssociatedExtensions' is TRUE, only +// files with an extension associated with this plugin's viewer are returned (pressing F3 on that +// file would attempt to open this plugin's viewer, and possible shadowing by another plugin's +// viewer is ignored). 'fileName' is the buffer for the retrieved name (size at least +// MAX_PATH). Returns TRUE if the name is retrieved successfully. Returns FALSE on error: there +// is no next file name in the source (if 'noMoreFiles' is not NULL, TRUE is returned in it), +// the source is busy (it is not processing messages; if 'srcBusy' is not NULL, TRUE is returned +// in it), or the source no longer exists (panel path changed, sorting changed, etc.). BOOL GetNextFileNameForViewer(int srcUID, int* lastFileIndex, const char* lastFileName, BOOL preferSelected, BOOL onlyAssociatedExtensions, char* fileName, BOOL* noMoreFiles, BOOL* srcBusy, CPluginInterfaceAbstract* plugin); -// vraci predchozi jmeno souboru pro viewer ze zdroje (levy/pravy panel nebo Findy); -// 'srcUID' je unikatni identifikator zdroje (predava se jako parametr pri otevirani -// vieweru); 'lastFileIndex' (nesmi byt NULL) je IN/OUT parametr, ktery by plugin mel -// menit jen pokud chce vratit jmeno posledniho souboru, v tomto pripade nastavit 'lastFileIndex' -// na -1; pocatecni hodnota 'lastFileIndex' se predava jako parametr pri otevirani -// vieweru; 'lastFileName' je plne jmeno aktualniho souboru (prazdny retezec pokud neni -// zname, napr. je-li 'lastFileIndex' -1); je-li 'preferSelected' TRUE a aspon jedno -// jmeno oznacene, budou se vracet oznacena jmena; je-li 'onlyAssociatedExtensions' TRUE, -// vraci jen soubory s priponou asociovanou s viewerem tohoto pluginu (F3 na tomto -// souboru by se pokusilo otevrit viewer tohoto pluginu + ignoruje pripadne zastineni -// viewerem jineho pluginu); 'fileName' je buffer pro ziskane jmeno (velikost alespon -// MAX_PATH); vraci TRUE pokud se podari jmeno ziskat; vraci FALSE pri chybe: zadne -// predchozi jmeno souboru ve zdroji neni (neni-li 'noMoreFiles' NULL, vraci se v nem -// TRUE), zdroj je zaneprazdnen (nezpracovava zpravy; neni-li 'srcBusy' NULL, vraci -// se v nem TRUE), jinak zdroj prestal existovat (zmena cesty v panelu, zmena -// razeni, atp.) +// Retrieves the previous file name for the viewer from the given source. +// Usage and return values are equivalent to GetNextFileNameForViewer but walk +// backwards through the list of files. BOOL GetPreviousFileNameForViewer(int srcUID, int* lastFileIndex, const char* lastFileName, BOOL preferSelected, BOOL onlyAssociatedExtensions, char* fileName, BOOL* noMoreFiles, BOOL* srcBusy, CPluginInterfaceAbstract* plugin); -// zjisti, jestli je aktualni soubor z vieweru oznaceny (selected) ve zdroji (levy/pravy -// panel nebo Findy); 'srcUID' je unikatni identifikator zdroje (predava se jako parametr -// pri otevirani vieweru); 'lastFileIndex' je parametr, ktery by plugin nemel menit, -// pocatecni hodnota 'lastFileIndex' se predava jako parametr pri otevirani vieweru; -// 'lastFileName' je plne jmeno aktualniho souboru; vraci TRUE pokud se podarilo zjistit, -// jestli je aktialni soubor oznaceny, vysledek je v 'isFileSelected' (nesmi byt NULL); -// vraci FALSE pri chybe: zdroj prestal existovat (zmena cesty v panelu, atp.) nebo soubor -// 'lastFileName' uz ve zdroji neni (pri techto dvou chybach, neni-li 'srcBusy' NULL, -// vraci se v nem FALSE), zdroj je zaneprazdnen (nezpracovava zpravy; pri teto chybe, -// neni-li 'srcBusy' NULL, vraci se v nem TRUE) +// Checks whether the current viewer file is selected in the source (left/right +// panel or Find window). 'srcUID' uniquely identifies the source. 'lastFileIndex' +// should not be modified by the plugin except when requesting the last file +// (set it to -1). 'lastFileName' is the full name of the current file. Returns +// TRUE on success and stores the result in 'isFileSelected' (must not be NULL). +// Returns FALSE if the source no longer exists or the file is missing (and sets +// 'srcBusy' to FALSE if provided) or if the source is busy processing messages +// (sets 'srcBusy' to TRUE). BOOL IsFileNameForViewerSelected(int srcUID, int lastFileIndex, const char* lastFileName, BOOL* isFileSelected, BOOL* srcBusy); -// nastavi oznaceni (selectionu) na aktualnim souboru z vieweru ve zdroji (levy/pravy -// panel nebo Findy); 'srcUID' je unikatni identifikator zdroje (predava se jako parametr -// pri otevirani vieweru); 'lastFileIndex' je parametr, ktery by plugin nemel menit, -// pocatecni hodnota 'lastFileIndex' se predava jako parametr pri otevirani vieweru; -// 'lastFileName' je plne jmeno aktualniho souboru; 'select' je TRUE/FALSE pokud se ma -// aktualni soubor oznacit/odznacit; vraci TRUE pri uspechu; vraci FALSE pri chybe: -// zdroj prestal existovat (zmena cesty v panelu, atp.) nebo soubor 'lastFileName' uz -// ve zdroji neni (pri techto dvou chybach, neni-li 'srcBusy' NULL, vraci se v nem FALSE), -// zdroj je zaneprazdnen (nezpracovava zpravy; pri teto chybe, neni-li 'srcBusy' NULL, -// vraci se v nem TRUE) +// Sets or clears the selection of the current file from the viewer in the source +// (left/right panel or Find window); 'srcUID' is the unique identifier of the source +// (passed as a parameter when opening the viewer); 'lastFileIndex' is a parameter that +// the plugin should not modify, its initial value is passed as a parameter when opening +// the viewer; 'lastFileName' is the full name of the current file; 'select' is TRUE/FALSE +// depending on whether the current file should be selected/deselected; returns TRUE on +// success; returns FALSE on error: the source no longer exists (panel path changed, etc.) +// or the file 'lastFileName' is no longer in the source (for these two errors, if +// 'srcBusy' is not NULL, FALSE is returned in it), or the source is busy (not processing +// messages; for this error, if 'srcBusy' is not NULL, TRUE is returned in it). BOOL SetSelectionOnFileNameForViewer(int srcUID, int lastFileIndex, const char* lastFileName, BOOL select, BOOL* srcBusy); -// zmeni zdroji (panelu nebo Findu) UID (negeneruje nove, aktualizuje pole -// FileNamesEnumSources a vrati nove UID v 'srcUID') +// Changes the UID assigned to a source panel or Find window without generating +// a new one. The FileNamesEnumSources array is updated and the new UID is +// returned in 'srcUID'. void EnumFileNamesChangeSourceUID(HWND hWnd, int* srcUID); -// prida zdroji (panelu nebo Findu) UID (negeneruje nove, prida dvojici -// hWnd+UID do pole FileNamesEnumSources a vrati nove UID v 'srcUID') +// Adds a source to FileNamesEnumSources without creating a new UID. The pair +// hWnd+UID is stored and the new UID is returned in 'srcUID'. void EnumFileNamesAddSourceUID(HWND hWnd, int* srcUID); -// vyradi zdroj (panelu nebo Findu) z pole FileNamesEnumSources +// Removes the specified source from FileNamesEnumSources void EnumFileNamesRemoveSourceUID(HWND hWnd); //****************************************************************************** -// neblokujici cteni volume-name CD drivu +// non-blocking reading of the volume name of a CD drive -extern CRITICAL_SECTION ReadCDVolNameCS; // kriticka sekce pro pristup k datum -extern UINT_PTR ReadCDVolNameReqUID; // UID pozadavku (pro rozpoznani jestli na vysledek jeste nekdo ceka) +extern CRITICAL_SECTION ReadCDVolNameCS; // critical section for access to data +extern UINT_PTR ReadCDVolNameReqUID; // request UID (to detect if someone still waits for the result) extern char ReadCDVolNameBuffer[MAX_PATH]; // IN/OUT buffer (root/volume_name) //****************************************************************************** -// funkce pro praci s historiemi posledne pouzitych hodnot v comboboxech +// functions for handling histories of recently used values in combo boxes -// prida do sdilene historie ('historyArr'+'historyItemsCount') naalokovanou kopii -// nove hodnoty 'value'; je-li 'caseSensitiveValue' TRUE, hleda se hodnota (retezec) -// v poli historie pomoci case-sensitive porovnani (FALSE = case-insensitive porovnani), -// nalezena hodnota se pouze presouva na prvni misto v poli historie +// adds an allocated copy of the new value 'value' to the shared history ('historyArr'+'historyItemsCount'); +// if 'caseSensitiveValue' is TRUE the value is looked up in the history using a case-sensitive comparison +// (FALSE = case-insensitive); when found, the existing value is just moved to the first position void AddValueToStdHistoryValues(char** historyArr, int historyItemsCount, const char* value, BOOL caseSensitiveValue); -// prida do comboboxu ('combo') texty ze sdilene historie ('historyArr'+'historyItemsCount'); -// pred pridavanim provede reset obsahu comboboxu (viz CB_RESETCONTENT) +// adds the texts from the shared history ('historyArr'+'historyItemsCount') to the combo box 'combo'; +// before adding it resets the combo box content (see CB_RESETCONTENT) void LoadComboFromStdHistoryValues(HWND combo, char** historyArr, int historyItemsCount); //****************************************************************************** -// funkce pro pridani vsech dosud neznamych aktivnich (naloadenych) modulu procesu +// function for adding all yet unknown loaded modules of the process void AddNewlyLoadedModulesToGlobalModulesStore(); //****************************************************************************** -// quicksort s porovnavanim pres StrICmp +// quicksort using StrICmp for comparisons void SortNames(char* files[], int left, int right); -// hleda retezec 'name' v poli 'usedNames' (pole je serazene pomoci StrICmp); -// vraci TRUE pri nalezeni + nalezeny index v 'index' (neni-li NULL); vraci -// FALSE pokud prvek nebyl nalezen + index pro vlozeni v 'index' (neni-li NULL) +// searches for the string 'name' in the 'usedNames' array (sorted via StrICmp); +// returns TRUE when found and the found index in 'index' (if not NULL); returns +// FALSE when the item is missing and provides the insertion index in 'index' (if not NULL) BOOL ContainsString(TIndirectArray* usedNames, const char* name, int* index = NULL); //****************************************************************************** -// v pripade uspechu vrati TRUE a cestu na "Documents", pripadne na "Desktop" -// v pripade neuspechu vrati FALSE -// 'pathLen' udava velikost bufferu 'path'; funkce zajisti terminovani retezce i v -// pripade zkraceni +// returns TRUE on success and stores the path to "Documents" or "Desktop" +// returns FALSE on failure +// 'pathLen' specifies the size of the 'path' buffer; the function ensures the +// string is null-terminated even if truncated BOOL GetMyDocumentsOrDesktopPath(char* path, int pathLen); // To optimize performance, it is good practice for applications to detect whether they @@ -2285,30 +2317,30 @@ BOOL GetMyDocumentsOrDesktopPath(char* path, int pathLen); // application is running on the console. BOOL IsRemoteSession(void); -// vraci TRUE, pokud je uzivatel mezi Administratory -// v pripade chyby vraci FALSE +// returns TRUE if the user is a member of the Administrators group +// returns FALSE on error BOOL IsUserAdmin(); //****************************************************************************** -// pro zajisteni uniku z odstranenych drivu na fixed drive (po vysunuti device - USB flash disk, atd.) -extern BOOL ChangeLeftPanelToFixedWhenIdleInProgress; // TRUE = prave se meni cesta, nastaveni ChangeLeftPanelToFixedWhenIdle na TRUE je zbytecne +// ensures we escape from removed drives to a fixed drive (after ejecting a device such as a USB flash disk) +extern BOOL ChangeLeftPanelToFixedWhenIdleInProgress; // TRUE when the path is currently being changed; setting ChangeLeftPanelToFixedWhenIdle to TRUE is unnecessary extern BOOL ChangeLeftPanelToFixedWhenIdle; -extern BOOL ChangeRightPanelToFixedWhenIdleInProgress; // TRUE = prave se meni cesta, nastaveni ChangeRightPanelToFixedWhenIdle na TRUE je zbytecne +extern BOOL ChangeRightPanelToFixedWhenIdleInProgress; // TRUE when the path is currently being changed; setting ChangeRightPanelToFixedWhenIdle to TRUE is unnecessary extern BOOL ChangeRightPanelToFixedWhenIdle; -extern BOOL OpenCfgToChangeIfPathIsInaccessibleGoTo; // TRUE = v idle otevre konfiguraci na Drives a focusne "If path in panel is inaccessible, go to:" +extern BOOL OpenCfgToChangeIfPathIsInaccessibleGoTo; // TRUE = open configuration on Drives during idle and focus "If path in panel is inaccessible, go to:" -// root drivu (i UNC), pro ktery je zobrazen messagebox "drive not ready" s Retry+Cancel -// tlacitky (pouziva se pro automaticke Retry po vlozeni media do drivu) +// drive root (including UNC) for which the "drive not ready" message box with Retry+Cancel buttons is shown +// used for automatic Retry after inserting media into the drive extern char CheckPathRootWithRetryMsgBox[MAX_PATH]; -// dialog "drive not ready" s Retry+Cancel tlacitky (pouziva se pro automaticke Retry po -// vlozeni media do drivu) +// dialog "drive not ready" with Retry+Cancel buttons (used for automatic Retry after +// inserting media into the drive) extern HWND LastDriveSelectErrDlgHWnd; // GetDriveFormFactor returns the drive form factor. // It returns 350 if the drive is a 3.5" floppy drive. // It returns 525 if the drive is a 5.25" floppy drive. -// It returns 800 if the drive is a 8" floppy drive. +// It returns 800 if the drive is an 8" floppy drive. // It returns 1 if the drive supports removable media other than 3.5", 5.25", and 8" floppies. // It returns 0 on error. // iDrive is 1 for drive A:, 2 for drive B:, etc. @@ -2316,44 +2348,43 @@ DWORD GetDriveFormFactor(int iDrive); //****************************************************************************** -// seradi pole pluginu podle PluginFSCreateTime (pro zobrazeni v Alt+F1/F2 a Disconnect dialogu) +// sorts the array of plugins by PluginFSCreateTime (for display in Alt+F1/F2 and the Disconnect dialog) void SortPluginFSTimes(CPluginFSInterfaceEncapsulation** list, int left, int right); -// vraci poradove cislo pro text polozky do change drive menu a Disconnect dialog; -// viz CPluginFSInterfaceEncapsulation::ChngDrvDuplicateItemIndex +// returns the index for the item text in the Change Drive menu and Disconnect dialog; +// see CPluginFSInterfaceEncapsulation::ChngDrvDuplicateItemIndex int GetIndexForDrvText(CPluginFSInterfaceEncapsulation** fsList, int count, CPluginFSInterfaceAbstract* fsIface, int currentIndex); //****************************************************************************** -// pomoci TweakUI si mohou uzivatele menit ikonku shortcuty (default, custom, zadna) -// tato funkce vytahne HShortcutOverlayXX -// existujici zahodi +// using TweakUI users can change the shortcut icon (default, custom or none) +// this function obtains HShortcutOverlayXX and discards any existing one BOOL GetShortcutOverlay(); -// vraci textovou podobou 'hotKey' (LOBYTE=vk, HIBYTE=mods), 'buff' musi mit nejmene 50 znaku +// returns a textual representation of 'hotKey' (LOBYTE=vk, HIBYTE=mods); 'buff' must have at least 50 characters void GetHotKeyText(WORD hotKey, char* buff); -// vraci bits per pixel displeje +// returns the display bits per pixel int GetCurrentBPP(HDC hDC = NULL); -// iteruje pres parenty smerem k tomu nejparentovanejsimu +// iterates through parents up to the topmost one HWND GetTopLevelParent(HWND hWindow); //****************************************************************************** -// promenne pouzite behem ukladani konfigurace pri shutdownu, log-offu nebo restartu (musime -// pumpovat zpravy, aby nas system nesestrelil jako "not responding" softik) +// variables used while saving the configuration during shutdown, logoff, or restart +// we must pump messages so the system does not terminate us as a "not responding" application class CWaitWindow; -extern CWaitWindow* GlobalSaveWaitWindow; // pokud existuje globalni wait okenko pro Save, je zde (jinak je zde NULL) -extern int GlobalSaveWaitWindowProgress; // aktualni hodnota progresu globalniho wait okenka pro Save +extern CWaitWindow* GlobalSaveWaitWindow; // if a global wait window for Save exists, it is stored here (otherwise NULL) +extern int GlobalSaveWaitWindowProgress; // current progress value of the global wait window for Save -extern BOOL IsSetSALAMANDER_SAVE_IN_PROGRESS; // TRUE = v registry je vytvorena hodnota SALAMANDER_SAVE_IN_PROGRESS (detekce preruseni ukladani konfigurace) +extern BOOL IsSetSALAMANDER_SAVE_IN_PROGRESS; // TRUE if the SALAMANDER_SAVE_IN_PROGRESS value exists in the registry (used to detect interrupted configuration saving) //****************************************************************************** -// podpurna struktura a funkce pro otevreni kontextoveho menu + spousteni jeho polozek -// v CSalamanderGeneral::OpenNetworkContextMenu() +// helper structure and functions for opening a context menu and executing its items +// in CSalamanderGeneral::OpenNetworkContextMenu() struct CTmpEnumData { @@ -2369,70 +2400,70 @@ void ShellActionAux6(CFilesWindow* panel); //****************************************************************************** -// vraci v 'path' (buffer aspon MAX_PATH znaku) cestu Configuration.IfPathIsInaccessibleGoTo; -// zohlednuje nastaveni Configuration.IfPathIsInaccessibleGoToIsMyDocs +// returns in 'path' (buffer at least MAX_PATH characters) the path Configuration.IfPathIsInaccessibleGoTo; +// respects the setting Configuration.IfPathIsInaccessibleGoToIsMyDocs void GetIfPathIsInaccessibleGoTo(char* path, BOOL forceIsMyDocs = FALSE); -// nacte z konfigurace v registry konfiguraci icon overlay handleru +// loads icon overlay handler configuration from the registry void LoadIconOvrlsInfo(const char* root); -// vraci TRUE pokud je icon overlay handler zakazany (nebo jsou zakazane vsechny) +// returns TRUE if the icon overlay handler is disabled, or if custom icon overlays are disabled globally BOOL IsDisabledCustomIconOverlays(const char* name); -// vraci TRUE pokud je icon overlay handler v seznamu zakazanych icon overlay handleru +// returns TRUE if the icon overlay handler is in the list of disabled icon overlay handlers BOOL IsNameInListOfDisabledCustomIconOverlays(const char* name); -// vycisti seznam zakazanych icon overlay handleru +// clears the list of disabled icon overlay handlers void ClearListOfDisabledCustomIconOverlays(); -// prida 'name' do seznamu zakazanych icon overlay handleru +// adds 'name' to the list of disabled icon overlay handlers BOOL AddToListOfDisabledCustomIconOverlays(const char* name); -// nacte ikonu z ImageResDLL +// loads an icon from ImageResDLL HICON SalLoadImage(int vistaResID, int otherResID, int cx, int cy, UINT flags); -// nacte ikonu pro archivy +// loads an icon for archives HICON LoadArchiveIcon(int cx, int cy, UINT flags); -// ziska login pro zadanou sitovou cestu, pripadne obnovi jeji mapovani +// obtains login credentials for the given network path and optionally restores its mapping BOOL RestoreNetworkConnection(HWND parent, const char* name, const char* remoteName, DWORD* retErr = NULL, LPNETRESOURCE lpNetResource = NULL); -// sestavi text do sloupce Type v panelu pro neasociovany soubor (napr. "AAA File" nebo "File") +// builds the text for the Type column in the panel for an unassociated file (e.g. "AAA File" or "File") void GetCommonFileTypeStr(char* buf, int* resLen, const char* ext); -// najde zdvojene separatory a vymaze ty nadbytecne (na Viste se mi objevily zdvojene -// separatory v kontextovem menu na .bar souborech) +// finds duplicate separators and removes the redundant ones (on Vista duplicate +// separators appeared in the context menu on .bar files) void RemoveUselessSeparatorsFromMenu(HMENU h); -// vraci adresar "Open Salamander" na ceste CSIDL_APPDATA do 'buf' (buffer o velikosti MAX_PATH) +// returns the "Open Salamander" directory in the CSIDL_APPDATA path in 'buf' (buffer of size MAX_PATH) BOOL GetOurPathInRoamingAPPDATA(char* buf); -// vytvori adresar "Open Salamander" na ceste CSIDL_APPDATA; vraci TRUE pokud se cesta -// vejde do MAX_PATH (jeji existence neni zarucena, vysledek CreateDirectory se nekontroluje); -// neni-li 'buf' NULL, jde o buffer o velikosti MAX_PATH, ve kterem se vraci tato cesta -// POZOR: pouziti jen Vista+ +// creates the "Open Salamander" directory in the CSIDL_APPDATA path; returns TRUE if the path +// fits into MAX_PATH (its existence is not guaranteed and the result of CreateDirectory is not checked); +// if 'buf' is not NULL it is a buffer of size MAX_PATH that receives this path +// NOTE: Vista+ only BOOL CreateOurPathInRoamingAPPDATA(char* buf); #ifndef _WIN64 -// jen 32-bitova verze pod jen Win64: zjistuje jestli jde o cestu, kterou redirector presmeruje do -// SysWOW64 nebo naopak zpet do System32 +// 32-bit version on Win64 only: checks whether the path is redirected by the +// file system redirector to SysWOW64 or back to System32 BOOL IsWin64RedirectedDir(const char* path, char** lastSubDir, BOOL failIfDirWithSameNameExists); -// jen 32-bitova verze pod Win64: zjistuje jestli selectiona obsahuje pseudo-adresar, ktery redirector -// presmeruje do SysWOW64 nebo naopak zpet do System32 a zaroven na disku neexistuje stejne pojmenovany -// adresar (pseudo-adresar pridany jen na zaklade AddWin64RedirectedDir) +// 32-bit build on Win64 only: tests whether the selection contains a pseudo +// directory that the redirector sends to SysWOW64 or back to System32 while no +// real directory with the same name exists on disk (pseudo-directories are +// added only via AddWin64RedirectedDir) BOOL ContainsWin64RedirectedDir(CFilesWindow* panel, int* indexes, int count, char* redirectedDir, BOOL onlyAdded); #endif // _WIN64 -// nase varianty funkci RegQueryValue a RegQueryValueEx, narozdil od API variant -// zajistuji pridani null-terminatoru pro typy REG_SZ, REG_MULTI_SZ a REG_EXPAND_SZ -// POZOR: pri zjistovani potrebne velikosti bufferu vraci o jeden nebo dva (dva -// jen u REG_MULTI_SZ) znaky vic pro pripad, ze by string bylo potreba -// zakoncit nulou/nulami +// our variants of RegQueryValue and RegQueryValueEx add a null terminator for +// REG_SZ, REG_MULTI_SZ and REG_EXPAND_SZ values unlike their API counterparts. +// WARNING: when calculating the required buffer size they return one extra +// character (two for REG_MULTI_SZ) in case the string needs terminating nulls extern "C" { LONG SalRegQueryValue(HKEY hKey, LPCSTR lpSubKey, LPSTR lpData, PLONG lpcbData); @@ -2440,16 +2471,17 @@ extern "C" LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData); } -// Win7 a novejsi OS - notifikace od taskbar, ze doslo k vytvoreni tlacitka pro okno -// nastavuje se pri startu Salamandera, testovat zda je nenulova +// Notification from the taskbar on Win7 and newer that a button was created for +// our window. Set at startup, check that it is non-zero extern UINT TaskbarBtnCreatedMsg; -// vrati rozmer ikony s ohledem na promennou SystemDPI -// pokud je 'large' TRUE, vraci rozmer pro velkou ikonu, jinak pro malou +// returns the icon size with respect to SystemDPI +// if 'large' is TRUE returns the size for a large icon, otherwise for a small one int GetIconSizeForSystemDPI(CIconSizeEnum iconSize); -// vraci aktualni systemove DPI (96, 120, 144, ...) +// returns the current system DPI (96, 120, 144, ...) int GetSystemDPI(); -// vraci scale odpovidajici aktualnimu DPI; misto 1.0 vraci 100, pro 1.25 vraci 125, atd +// returns the scale corresponding to the current DPI; instead of 1.0 returns +// 100, for 1.25 returns 125, etc. int GetScaleForSystemDPI(); diff --git a/src/dialogs.cpp b/src/dialogs.cpp index 5443eb4d5..79dde1512 100644 --- a/src/dialogs.cpp +++ b/src/dialogs.cpp @@ -126,7 +126,7 @@ void CChangeAttrDialog::Transfer(CTransferInfo& ti) DateTime_SetSystemtime(HModifiedDate, GDT_NONE, &TimeModified); DateTime_SetSystemtime(HCreatedDate, GDT_NONE, &TimeCreated); DateTime_SetSystemtime(HAccessedDate, GDT_NONE, &TimeAccessed); - // fill in the times + // populate the time fields DateTime_SetSystemtime(HModifiedTime, GDT_VALID, &TimeModified); DateTime_SetSystemtime(HCreatedTime, GDT_VALID, &TimeCreated); DateTime_SetSystemtime(HAccessedTime, GDT_VALID, &TimeAccessed); @@ -310,7 +310,7 @@ unsigned ThreadProgressDlgBody(void* parameter) CProgressDialog dlg(NULL, data->Script, data->Caption, attrsData, convertData, TRUE, data); INT_PTR res = dlg.Execute(); - if (res == 0 || res == -1 || res == IDABORT) // failed to open the dialog or worker thread + if (res == 0 || res == -1 || res == IDABORT) // failed to open the dialog or start the worker thread SetEvent(data->ContEvent); // let the main thread continue (opening the dialog or starting the operation failed) if (workPath1[0] != 0) @@ -683,7 +683,7 @@ CProgressDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) WorkerNotSuspended = NULL; HANDLES(CloseHandle(WContinue)); WContinue = NULL; - EndDialog(HWindow, IDABORT); // fatal error + EndDialog(HWindow, IDABORT); // abort } else { @@ -918,7 +918,7 @@ CProgressDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { if (wParam == IDT_REPAINT) { - if (!FlushCachedData()) // WM_USER_SETDIALOG did not arrive, we can safely cancel the timer + if (!FlushCachedData()) // WM_USER_SETDIALOG was not received, so the timer can be safely canceled { TimerIsRunning = FALSE; KillTimer(HWindow, IDT_REPAINT); @@ -993,7 +993,7 @@ CProgressDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) */ secs.Value++; // add one second so we finish the operation with "time left: 1 sec" (instead of 0 sec) - // rounding calculation (roughly 10% error + rounded to nice numbers 1,2,5,10,20,40) + // rounding calculation (approximately 10% error; rounded to nice values: 1, 2, 5, 10, 20, 40) CQuadWord dif = (secs + CQuadWord(5, 0)) / CQuadWord(10, 0); int expon = 0; while (dif >= CQuadWord(50, 0)) @@ -1205,7 +1205,7 @@ MENU_TEMPLATE_ITEM ProgressDialogMenu2[] = { if (CanClose) { - if (!IsWindowEnabled(HWindow)) // there is a modal dialog above this dialog (a message box asking about operation canceling or reporting an error) + if (!IsWindowEnabled(HWindow)) // a modal dialog is open over this dialog (a message box asking whether to cancel the operation or reporting an operation error) CloseAllOwnedEnabledDialogs(HWindow); CancelWorker = TRUE; // set worker cancel EnableWindow(GetDlgItem(HWindow, IDB_PAUSERESUME), FALSE); @@ -1235,7 +1235,7 @@ MENU_TEMPLATE_ITEM ProgressDialogMenu2[] = SetThreadPriority(Worker, THREAD_PRIORITY_NORMAL); AcceptCommands = TRUE; } - if (!IsWindowEnabled(HWindow)) // there is a modal window above this dialog (a message box asking about operation canceling or reporting an error) + if (!IsWindowEnabled(HWindow)) // a modal window is open over this dialog (a message box asking whether to cancel the operation or reporting an operation error) { HWND dlg = GetLastActivePopup(HWindow); if (dlg != NULL && dlg != HWindow) @@ -1269,7 +1269,7 @@ MENU_TEMPLATE_ITEM ProgressDialogMenu2[] = if (RunningInOwnThread && !Configuration.AlwaysOnTop && GetForegroundWindow() == HWindow) { // Prior to Windows Vista we only called GetNextWindow(), which was enough to reach the next window in the Z-order. - // Vista introduced new hidden helper windows such as "MSCTFIME UI" and "Default IME" that sit between us and + // Vista introduced new hidden helper windows such as "MSCTFIME UI" and "Default IME" that sit between us and // our window (main, viver, ect.). So we skip hidden windows here. BOOL valid; HWND hNext = HWindow; @@ -1353,8 +1353,8 @@ MENU_TEMPLATE_ITEM ProgressDialogMenu2[] = int ret = SalMessageBox(HWindow, LoadStr(IDS_CANCELOPERATION), LoadStr(IDS_QUESTION), MB_YESNO | MB_ICONQUESTION /*| MSGBOXEX_ESCAPEENABLED*/); // Escape key is not a good - // idea -- Zarevak accidentally started deleting a large batch of files, then began hitting Escape (the machine was - // heavily loaded so it did not respond immediately) canceling the confirmation, therefore the confirmation can + // idea -- Zarevak accidentally started deleting a large batch of files, then began hitting Escape (the machine was + // heavily loaded so it did not respond immediately) canceling the confirmation, therefore the confirmation can // no longer be closed with Escape. // BeginSuspendMode(); // we are doing something again ... @@ -1379,10 +1379,10 @@ MENU_TEMPLATE_ITEM ProgressDialogMenu2[] = if ((CancelWorker || ShowPause) && // only if it's Cancel or the operation isn't paused WorkerNotSuspended != NULL) { - SetEvent(WorkerNotSuspended); // may be NULL if the message box was closed from IDOK via WM_CLOSE + SetEvent(WorkerNotSuspended); // may be NULL if the message box was closed by IDOK via WM_CLOSE } } - return TRUE; // only the worker using IDOK will terminate the dialog ... + return TRUE; // only the worker can close the dialog using IDOK ... } case CM_RESUMEOPER: // resume posted from the operations queue @@ -1478,8 +1478,8 @@ MENU_TEMPLATE_ITEM ProgressDialogMenu2[] = SetThreadPriority(Worker, THREAD_PRIORITY_NORMAL); AcceptCommands = TRUE; } - if (wParam == FALSE) // when deactivated we leave directories shown in the panels, - { // so they can be deleted, disconnected, etc. from other software + if (wParam == FALSE) // when deactivated, we leave the directories shown in the panels + { // so other software can delete or disconnect them if (!RunningInOwnThread && CanChangeDirectory()) SetCurrentDirectoryToSystem(); } @@ -2070,7 +2070,7 @@ CBetaExpiredDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) hl = new CHyperLink(HWindow, IDC_BETAEXPIREDURL); if (hl != NULL) { - // if the environment is Czech or Slovak, we will automatically show the Czech version of the web + // if the language is Czech or Slovak, automatically show the Czech version of the website BOOL english = LanguageID != 0x405 /* Czech */ && LanguageID != 0x41B /* Slovak */; const char* url = @@ -2100,7 +2100,7 @@ CBetaExpiredDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) sprintf(buff, orig, today, expired); SetDlgItemText(HWindow, IDC_BETAEXPIREDDATE, buff); - // the OK button will show numbers counting down, store the original text + // The OK button will display countdown numbers; store the original text. GetDlgItemText(HWindow, IDOK, OldOK, 100); EnableWindow(GetDlgItem(HWindow, IDOK), FALSE); @@ -2186,7 +2186,7 @@ void CSetSpeedLimDialog::Transfer(CTransferInfo& ti) { speedLimNum /= 1024; speedLimUnits++; - if (speedLimNum == 0 || speedLimUnits > 3) // should not happen, just for peace of mind + if (speedLimNum == 0 || speedLimUnits > 3) // cannot occur; defensive check { TRACE_E("CSetSpeedLimDialog::Transfer(): unexpected situation!"); speedLimNum = 4; diff --git a/src/dialogs.h b/src/dialogs.h index db68009ad..ba6e2d491 100644 --- a/src/dialogs.h +++ b/src/dialogs.h @@ -277,7 +277,7 @@ class CProgressDlgArray HWND GetNextOpenedDlg(int* index); // ensures all open dialogs are closed - // call only from the main thread (otherwise another dialog might open and it won't + // call only from the main thread (otherwise another dialog might open and won't // know it should terminate) void PostCancelToAllDlgs(); @@ -635,7 +635,7 @@ class CConvertFilesDlg : public CCommonDialog char Mask[MAX_PATH]; // which files will be converted? int Change; // which conversion should be performed? BOOL SubDirs; // include subdirectories? - int CodeType; // selected encoding (0 = none) + int CodeType; // which encoding is selected (0 = none) int EOFType; // selected line endings (0 = none) // 1 = CRLF // 2 = LF @@ -831,7 +831,7 @@ class CSplashScreen : public CDialog protected: CBitmap* Bitmap; // includes the text - CBitmap* OriginalBitmap; // graphics only, without text + CBitmap* OriginalBitmap; // bitmap only, without text HFONT HNormalFont; HFONT HBoldFont; RECT OpenSalR; @@ -935,7 +935,7 @@ class CChangeIconDialog : public CCommonDialog char* IconFile; int* IconIndex; BOOL Dirty; - HICON* Icons; // array of enumerated icon handles + HICON* Icons; // array of icon handles DWORD IconsCount; // number of icons in the array public: @@ -988,8 +988,8 @@ class CPluginsDlg : public CCommonDialog void InitColumns(); // add columns to the listview void SetColumnWidths(); // set optimal column widths void RefreshListView(BOOL setOnly = TRUE, int selIndex = -1, const CPluginData* selectPlugin = NULL, BOOL setColumnWidths = FALSE); - void OnSelChanged(); // selected item in the listview changed - CPluginData* GetSelectedPlugin(int* index = NULL, int* lvIndex = NULL); // returns NULL if no item is selected; index returns index to the Plugins array; lvIndex returns index within listview, can be NULL + void OnSelChanged(); // the selected item in the list view changed + CPluginData* GetSelectedPlugin(int* index = NULL, int* lvIndex = NULL); // returns NULL if no item is selected; index returns the index into the Plugins array; lvIndex returns the index within the list view and can be NULL void EnableButtons(CPluginData* plugin); void OnContextMenu(int x, int y); // show the context menu for the selected item at coordinates x, y void OnMove(BOOL up); @@ -1025,7 +1025,7 @@ class CPluginKeys : public CCommonDialog void RefreshListView(BOOL setOnly = TRUE); WORD GetHotKey(BYTE* virtKey = NULL, BYTE* mods = NULL); - CPluginMenuItem* GetSelectedItem(int* orgIndex); // orgIndex returns index to Plugin array->MenuItems; may be NULL + CPluginMenuItem* GetSelectedItem(int* orgIndex); // orgIndex receives the index into the Plugin->MenuItems array; it may be NULL CPluginMenuItem* GetItem(int index); void EnableButtons(); void HandleConflictWarning(); @@ -1167,9 +1167,9 @@ struct CImportOldKey class CImportConfigDialog : public CCommonDialog { public: - // array corresponding to SalamanderConfigurationRoots array; TRUE:the configuration exists, FALSE:it doesn't + // array corresponding to the SalamanderConfigurationRoots array; TRUE: configuration exists, FALSE: does not exist BOOL ConfigurationExist[SALCFG_ROOTS_COUNT]; - // pointer to the same sized array where the dialog stores TRUE for configurations to delete + // pointer to an array of the same size where the dialog stores TRUE for configurations to be deleted BOOL* DeleteConfigurations; // dialog returns here which configuration the user wants to import; -1 -> none // index points into the SalamanderConfigurationRoots array @@ -1213,7 +1213,7 @@ class CLanguageSelectorDialog : public CCommonDialog BOOL Initialize(const char* slgSearchPath = NULL, HINSTANCE pluginDLL = NULL); int GetLanguagesCount() { return Items.Count; } - BOOL GetSLGName(char* path, int index = 0); // returns xxxx.slg of the item at index 'index' + BOOL GetSLGName(char* path, int index = 0); // returns the xxxx.slg for the item at index 'index' BOOL SLGNameExists(const char* slgName); // checks whether 'slgName' exists in 'Items' void FillControls(); @@ -1286,8 +1286,8 @@ class CSharesDialog : public CCommonDialog public: CSharesDialog(HWND hParent); - const char* GetFocusedPath(); // returns the path of the selected share; call only after the dialog returns - // returns NULL if "Focus" wasn't clicked and the dialog returned IDOK + const char* GetFocusedPath(); // returns the path of the selected share; call only after Execute() returns + // returns NULL if the "Focus" button was not pressed and the dialog returned IDOK // from Execute() protected: @@ -1299,7 +1299,7 @@ class CSharesDialog : public CCommonDialog void Refresh(); // loads shared folders and adds them to the listview static int CALLBACK SortFunc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort); void SortItems(); // sorts items based on the SortBy variable - int GetFocusedIndex(); // returns index to SharetDirs array or -1 if no item is selected + int GetFocusedIndex(); // returns the index into the SharetDirs array, or -1 if no item is selected void DeleteShare(const char* shareName); // request the system to remove the share void OnContextMenu(int x, int y); // shows the context menu for the selected item at coordinates x, y void EnableControls(); // button enabler @@ -1349,9 +1349,9 @@ class CDisconnectDialog : public CCommonDialog CDisconnectDialog(CFilesWindow* panel); ~CDisconnectDialog(); - const char* GetFocusedPath(); // returns the path of the selected share; call only after the dialog returns - // returns NULL if "Focus" wasn't clicked and the dialog returned IDOK - // from Execute() + const char* GetFocusedPath(); // returns the path of the selected share; call only after Execute() returns + // returns NULL if the "Focus" button was not pressed and the dialog returned IDOK + // from Execute() BOOL NoConnection() { return NoConncection; } // returns TRUE if the dialog wasn't opened because there was no connection protected: @@ -1446,7 +1446,7 @@ class CCompareDirsDialog : public CCommonDialog int OriginalHeight; // full dialog height int OriginalButtonsY; // Y position of the buttons in client coordinates int SpacerHeight; // spacer used when shrinking/expanding the dialog - BOOL Expanded; // are we currently expanded? + BOOL Expanded; // is the dialog currently expanded? public: CCompareDirsDialog(HWND hParent, BOOL enableByDateAndTime, BOOL enableBySize, @@ -1499,7 +1499,7 @@ class CCmpDirProgressDialog : public CCommonDialog CITaskBarList3* TaskBarList3; // pointer to the interface owned by the Salamander main window public: - CCmpDirProgressDialog(HWND hParent, BOOL hasProgress, CITaskBarList3* taskBarList3); // if 'hasProgress' is TRUE, the dialog shows a progress bar + CCmpDirProgressDialog(HWND hParent, BOOL hasProgress, CITaskBarList3* taskBarList3); // if 'hasProgress' is TRUE, the dialog with a progress bar is used // text setup void SetSource(const char* text); diff --git a/src/dialogs2.cpp b/src/dialogs2.cpp index 776bf8bbc..cd722edbe 100644 --- a/src/dialogs2.cpp +++ b/src/dialogs2.cpp @@ -269,7 +269,7 @@ CCommonDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) else CallEndStopRefresh = FALSE; - // when opening the dialog set the plug-ins' msgbox parent to this dialog (main thread only) + // when opening the dialog, set the message-box parent for plugins to this dialog (main thread only) if (Modal && MainThreadID == GetCurrentThreadId()) { HOldPluginMsgBoxParent = PluginMsgBoxParent; @@ -301,15 +301,15 @@ CCommonDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_DESTROY: { - if (GetKeyState(VK_ESCAPE) & 0x8000) // measure to avoid interrupting panel listing after each ESC + if (GetKeyState(VK_ESCAPE) & 0x8000) // safeguard against interrupting panel listing on each Esc WaitForESCReleaseBeforeTestingESC = TRUE; - // the dialog is closing - the user might have changed the clipboard - // (for example pasted text from an editline), so we'll verify it + // the dialog is closing; the user might have changed the clipboard + // (for example by putting text into an edit line), so we will check it IdleRefreshStates = TRUE; // force the state variables check during the next Idle IdleCheckClipboard = TRUE; // also let the clipboard be checked - // when closing the dialog restore the msgbox parent for plug-ins + // when closing the dialog restore the msgbox parent for plugins if (HOldPluginMsgBoxParent != NULL) PluginMsgBoxParent = HOldPluginMsgBoxParent; @@ -875,7 +875,7 @@ void CLanguageSelectorDialog::LoadListView() void CLanguageSelectorDialog::Transfer(CTransferInfo& ti) { - if (PluginName != NULL) // show this checkbox only when selecting an alternative language for a plug-in + if (PluginName != NULL) // show this checkbox only when selecting an alternative language for a plugin ti.CheckBox(IDC_USESAMESLGINOTHERPLUGINS, Configuration.UseAsAltSLGInOtherPlugins); if (ti.Type == ttDataToWindow) @@ -894,7 +894,7 @@ void CLanguageSelectorDialog::Transfer(CTransferInfo& ti) if (index != -1) { lstrcpy(SLGName, Items[index].FileName); - if (PluginName != NULL) // store the alternative language name only when selecting an alternative language for a plug-in + if (PluginName != NULL) // store the alternative language name only when selecting an alternative language for a plugin { if (Configuration.UseAsAltSLGInOtherPlugins) lstrcpy(Configuration.AltPluginSLGName, SLGName); @@ -923,7 +923,7 @@ BOOL CLanguageSelectorDialog::Initialize(const char* slgSearchPath, HINSTANCE pl do { char* point = strrchr(file.cFileName, '.'); - if (point != NULL && stricmp(point + 1, "slg") == 0) // it was returning *.slg* + if (point != NULL && stricmp(point + 1, "slg") == 0) // FindFirstFile was returning *.slg* too { CLanguage lang; if (lang.Init(file.cFileName, pluginDLL)) @@ -950,7 +950,7 @@ int CLanguageSelectorDialog::GetPreferredLanguageIndex(const char* selectSLGName WORD primaryID = PRIMARYLANGID(langID); int localeIndex = -1; // index corresponding to the user's locale int primarylocaleIndex = -1; // index corresponding to the user's primary language locale - int englishIndex = -1; // index of the file "english.slg" + int englishIndex = -1; // index of the "english.slg" file int i; for (i = 0; i < Items.Count; i++) { @@ -1014,18 +1014,18 @@ CLanguageSelectorDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { if (PluginName != NULL) { - // put the plug-in name in the title so the user knows which plug-in the language is for + // put the plugin name in the title so the user knows which plugin the language is for char buf[200]; _snprintf_s(buf, _TRUNCATE, "%s: ", PluginName); - buf[99] = 0; // use only 100 characters for the plug-in name so some space remains for the original title dialog + buf[99] = 0; // use only 100 characters for the plugin name so some space remains for the original title dialog int len = (int)strlen(buf); if (GetWindowText(HWindow, buf + len, 200 - len)) SetWindowText(HWindow, buf); } } - if (!OpenedFromConfiguration && PluginName == NULL) // turn the Cancel button into Exit + if (!OpenedFromConfiguration && PluginName == NULL) // change the Cancel button to Exit SetDlgItemText(HWindow, IDCANCEL, ExitButtonLabel); - if (PluginName != NULL) // disable closing + if (PluginName != NULL) // disable the Close command EnableMenuItem(GetSystemMenu(HWindow, FALSE), SC_CLOSE, MF_BYCOMMAND | MF_GRAYED); Web = new CHyperLink(HWindow, IDC_SLG_WEB, STF_HYPERLINK_COLOR); diff --git a/src/dialogs3.cpp b/src/dialogs3.cpp index e11ad66ef..08e30d070 100644 --- a/src/dialogs3.cpp +++ b/src/dialogs3.cpp @@ -226,7 +226,7 @@ CConvertFilesDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) SetMenuItemBitmaps(hMenu, mi.wID, MF_BYCOMMAND, NULL, HMenuCheckDot); } - // insert a separator after none + // insert a separator after 'None' mi.fMask = MIIM_TYPE; mi.fType = MFT_SEPARATOR; InsertMenuItem(hMenu, 1, TRUE, &mi); @@ -519,8 +519,8 @@ CEditNewFileDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { if (LOWORD(wParam) == IDB_BROWSE) { - /* used by the export_mnu.py script which generates salmenu.mnu for the Translator - keep synchronized with the InsertMenu() call below... + /* Used by the export_mnu.py script that generates salmenu.mnu for Translator. + Keep synchronized with the InsertMenu() call below. MENU_TEMPLATE_ITEM EditNewFileDialogMenu[] = { {MNTT_PB, 0 @@ -687,7 +687,7 @@ void CCopyMoveMoreDialog::TransferCriteriaControls(CTransferInfo& ti) { Criteria->Masks.SetMasksString(masks); int errpos = 0; - // masks must go out in the Prepared state + // masks must be passed out in the Prepared state if (!Criteria->Masks.PrepareMasks(errpos)) // invalid mask, this shouldn't happen thanks to validation Criteria->UseMasks = FALSE; char dummy[200]; @@ -723,7 +723,7 @@ void CCopyMoveMoreDialog::TransferCriteriaControls(CTransferInfo& ti) { speedLimNum /= 1024; speedLimUnits++; - if (speedLimNum == 0 || speedLimUnits > 3) // cannot happen, just for peace of mind + if (speedLimNum == 0 || speedLimUnits > 3) // cannot happen; defensive check { TRACE_E("CCopyMoveMoreDialog::TransferCriteriaControls(): unexpected situation!"); speedLimNum = 4; @@ -1644,7 +1644,7 @@ CDriveInfo::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) HDC hdc = HANDLES(GetDC(HWindow)); int devCaps = GetDeviceCaps(hdc, NUMCOLORS); HANDLES(ReleaseDC(HWindow, hdc)); - if (devCaps == -1) // more than 256 colors + if (devCaps == -1) // more than 256 colors available { FreeLight = RGB(35, 245, 156); FreeDark = RGB(9, 159, 96); @@ -1667,7 +1667,7 @@ CDriveInfo::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (cr != NULL) cr->SetColor(UsedLight); - Graph = new CColorGraph(HWindow, IDB_GRAPH); // JRYFIXME - rewrite to W10 look; see disk properties, it won't be comfortable to use GDI+ maybe our SVG? + Graph = new CColorGraph(HWindow, IDB_GRAPH); // JRYFIXME - rewrite to match the Windows 10 look; see disk properties. Would it be better to use GDI+ or our SVGs? if (Graph != NULL) Graph->SetColor(FreeLight, FreeDark, UsedLight, UsedDark); @@ -1826,7 +1826,7 @@ void CPackDialog::Transfer(CTransferInfo& ti) char* s = strrchr(Path, '.'); char* s2 = strrchr(Path, '\\'); int nameLen = (int)strlen(Path); - if ((s == NULL || s2 != NULL && s2 > s) && // '.cvspass' in Windows is considered an extension ... + if ((s == NULL || s2 != NULL && s2 > s) && // '.cvspass' is treated as an extension in Windows ... (s2 == NULL || (s2 - Path + 1) < nameLen) && nameLen > 0 && nameLen + 1 + 1 + strlen(ext) < MAX_PATH) @@ -1862,7 +1862,7 @@ BOOL CPackDialog::ChangeExtension(char* name, const char* ext) { char* s = strrchr(name, '.'); char* s2 = strrchr(name, '\\'); - if (s != NULL && // '.cvspass' in Windows is considered an extension ... + if (s != NULL && // '.cvspass' is treated as an extension in Windows ... //if (s != NULL && s > name && (s2 == NULL || s > s2) && strlen(ext) + 1 + ((s + 1) - name) < MAX_PATH) @@ -2589,7 +2589,7 @@ void CWaitWindow::PaintText(HDC hDC) HFONT hOldFont = (HFONT)SelectObject(hDestDC, EnvFont); int prevBkMode = SetBkMode(hDestDC, TRANSPARENT); SetTextColor(hDestDC, GetSysColor(COLOR_BTNTEXT)); - // we won't clip so that we survive minor text extension + // do not clip, to tolerate minor text extension // that may occur during a SetText call DrawText(hDestDC, Text, (int)strlen(Text), &r, DT_LEFT | DT_NOPREFIX | DT_NOCLIP | (NeedWrap ? DT_WORDBREAK : 0)); SetBkMode(hDestDC, prevBkMode); diff --git a/src/drivelst.cpp b/src/drivelst.cpp index 34c7824bc..6873a2ac3 100644 --- a/src/drivelst.cpp +++ b/src/drivelst.cpp @@ -92,7 +92,7 @@ BOOL GetUserName(const char* drive, const char* remoteName, char* userName, DWOR HKEY network; LONG res = HANDLES_Q(RegOpenKeyEx(HKEY_CURRENT_USER, "Network", 0, KEY_READ, &network)); if (res != ERROR_SUCCESS) - return FALSE; // well, nothing ... + return FALSE; // nothing to do ... BOOL ret = FALSE; char keyName[MAX_PATH]; @@ -115,7 +115,7 @@ BOOL GetUserName(const char* drive, const char* remoteName, char* userName, DWOR type = REG_SZ; res = SalRegQueryValueEx(driveKey, "UserName", 0, &type, (unsigned char*)userName, &keyNameSize); - if (res == ERROR_SUCCESS && type == REG_SZ && userName[0] != 0) // do we have a user? + if (res == ERROR_SUCCESS && type == REG_SZ && userName[0] != 0) // do we have a user name? TRACE_I("Found user name: " << keyName << ", " << userName); else userName[0] = 0; @@ -124,7 +124,7 @@ BOOL GetUserName(const char* drive, const char* remoteName, char* userName, DWOR type = REG_SZ; res = SalRegQueryValueEx(driveKey, "ProviderName", 0, &type, (unsigned char*)providerBuf, &keyNameSize); - if (res != ERROR_SUCCESS || type != REG_SZ) // if we do not have a provider, we will reset the buffer + if (res != ERROR_SUCCESS || type != REG_SZ) // if we do not have a provider, clear the buffer providerBuf[0] = 0; } HANDLES(RegCloseKey(driveKey)); @@ -158,7 +158,7 @@ DWORD WINAPI NBWNetAC3ThreadF(void* param) { CALL_STACK_MESSAGE_NONE CNBWNetAC3ThreadFParams* data = &NBWNetAC3ThreadFParams; - data->err = WNetAddConnection3(NULL /* we're not using CONNECT_INTERACTIVE, we're in another thread */, + data->err = WNetAddConnection3(NULL /* CONNECT_INTERACTIVE is not used because this runs in another thread */, &data->netResource, data->lpPassword, data->lpUserName, data->dwFlags); memset(data->bufPassword, 0, sizeof(data->bufPassword)); if (data->err == ERROR_EXTENDED_ERROR && @@ -189,28 +189,28 @@ BOOL NonBlockingWNetAddConnection3(DWORD& err, LPNETRESOURCE lpNetResource, if (errProviderName != NULL) errProviderName[0] = 0; - // first all we will wait for the previous "calculation" to finish + // first wait for the previous "operation" to finish GetAsyncKeyState(VK_ESCAPE); // init GetAsyncKeyState - see help if (NBWNetAC3Thread.ShutdownArrived) - return FALSE; // soft has already ended, no further action + return FALSE; // the application is already shutting down; no further action if (NBWNetAC3Thread.Thread != NULL) { while (1) { DWORD res = WaitForSingleObject(NBWNetAC3Thread.Thread, 200); if (res == WAIT_FAILED) - return FALSE; // invalid thread handle (closed from outside when ending the soft) + return FALSE; // invalid thread handle (closed externally during application shutdown) if (res != WAIT_TIMEOUT) break; if (UserWantsToCancelSafeWaitWindow()) return FALSE; } if (NBWNetAC3Thread.ShutdownArrived) - return FALSE; // soft has already ended, no further action + return FALSE; // the application is already shutting down; no further action NBWNetAC3Thread.Close(); } - // then we will set the parameters and try to start a new thread + // then set the parameters and try to start a new thread if (lpUserName != NULL) { lstrcpyn(NBWNetAC3ThreadFParams.bufUserName, lpUserName, USERNAME_MAXLEN); @@ -248,7 +248,7 @@ BOOL NonBlockingWNetAddConnection3(DWORD& err, LPNETRESOURCE lpNetResource, { memset(NBWNetAC3ThreadFParams.bufPassword, 0, sizeof(NBWNetAC3ThreadFParams.bufPassword)); TRACE_E("Unable to start add-net-connection-3 thread."); - return FALSE; // error (simulation of ESC) + return FALSE; // error (ESC simulation) } // we will wait for the "calculation" to finish so that we can return the result @@ -256,14 +256,14 @@ BOOL NonBlockingWNetAddConnection3(DWORD& err, LPNETRESOURCE lpNetResource, { DWORD res = WaitForSingleObject(NBWNetAC3Thread.Thread, 200); if (res == WAIT_FAILED) - return FALSE; // invalid thread handle (closed from outside when ending the soft) + return FALSE; // invalid thread handle (closed externally during application shutdown) if (res != WAIT_TIMEOUT) break; if (UserWantsToCancelSafeWaitWindow()) return FALSE; } if (NBWNetAC3Thread.ShutdownArrived) - return FALSE; // soft has already ended, no further action + return FALSE; // the application is already shutting down; no further action NBWNetAC3Thread.Close(); if (errProviderCode != NULL) @@ -278,7 +278,7 @@ BOOL NonBlockingWNetAddConnection3(DWORD& err, LPNETRESOURCE lpNetResource, BOOL IsLogonFailureErr(DWORD err) { - return err == ERROR_ACCESS_DENIED || // defense against e.g. "no files found" + return err == ERROR_ACCESS_DENIED || // guard against e.g. "no files found" err == ERROR_LOGON_FAILURE || err == ERROR_ACCOUNT_RESTRICTION || err == ERROR_INVALID_LOGON_HOURS || @@ -297,7 +297,7 @@ BOOL IsLogonFailureErr(DWORD err) err == ERROR_BAD_USERNAME || err == ERROR_NO_SUCH_USER || err == ERROR_DOWNGRADE_DETECTED || - err == ERROR_EXTENDED_ERROR; // who knows what extended error this is, but "password expired" belongs here, so that it's a logon failure (at least user says Cancel) + err == ERROR_EXTENDED_ERROR; // This extended error is not specific, but "password expired" can be reported here, so treat it as a logon failure in general (at worst, the user clicks Cancel). } BOOL IsBadUserNameOrPasswdErr(DWORD err) @@ -357,7 +357,7 @@ BOOL IsAdminShareExtraLogonFailureErr(DWORD err, const char* root) const char* server = root + 2; root++; while (*++root != 0 && *root != '\\' && CharIsAllowedInServerName(*root)) - ; // skip server name + simple test (incomplete, e.g. forbids dots in IPv4 and IPv6), whether it is really an invalid name (in that case we will not ask for username+password) + ; // skip the server name and do a simple check (incomplete; for example, it also rejects dots in IPv4 and IPv6) whether this is really an invalid name (in that case, we will not ask for a username and password) if (*root == '.') // we will take care of IPv4 adresses (let's ignore IPv6) { const char* r = root; @@ -434,7 +434,7 @@ typedef WINADVAPI DWORD (WINAPI *FT_CredUIParseUserNameA)( */ #define CREDUI_FLAGS_DO_NOT_PERSIST 0x00002 // Do not show "Save" checkbox, and do not persist credentials -#define CREDUI_FLAGS_EXPECT_CONFIRMATION 0x20000 // do not persist unless caller later confirms credential via CredUIConfirmCredential() api +#define CREDUI_FLAGS_EXPECT_CONFIRMATION 0x20000 // Do not persist unless the caller later confirms the credential via CredUIConfirmCredential() API #define CREDUI_FLAGS_GENERIC_CREDENTIALS 0x40000 // Credential is a generic credential BOOL RestoreNetworkConnection(HWND parent, const char* name, const char* remoteName, DWORD* retErr, LPNETRESOURCE lpNetResource) @@ -488,12 +488,12 @@ BOOL RestoreNetworkConnection(HWND parent, const char* name, const char* remoteN if (end != NULL && *(end + 1) != '\\' && *(end + 1) != 0) { const char* last = strchr(end + 2, '\\'); - if (last == NULL || *(last + 1) == 0) // the own dialog under XP+Vista will be only shown for simple UNC paths: "\\server\share" and "\\server\\share\\" + if (last == NULL || *(last + 1) == 0) // show the custom dialog on XP and Vista only for simple UNC paths: "\\server\share" and "\\server\share\\" lstrcpyn(serverName, remoteName + 2, (int)min(MAX_PATH, (end - (remoteName + 2)) + 1)); } } - if (name != NULL && // mapped paths only (for the drive letter) + if (name != NULL && // mapped paths only (to a drive letter) GetUserName(name, remoteName, userNameBuf, USERNAME_MAXLEN, providerBuf, MAX_PATH)) // unknown user name for the restored connection { if (userNameBuf[0] != 0) @@ -508,8 +508,8 @@ BOOL RestoreNetworkConnection(HWND parent, const char* name, const char* remoteN DWORD err; char* passwd = NULL; - // XP+Vista: we will dynamically extract functions for getting username+password in the standard dialog (including the option to save to Credential Manager - see "Manage your network passwords" in User Accounts in Control Panel) - // Windows 7: there is a new dialog again and I have not yet discovered the interface for it + // XP+Vista: load functions dynamically to obtain the username and password in the standard dialog (including the option to save them to Credential Manager; see "Manage your network passwords" in User Accounts in Control Panel) + // Windows 7: uses a new dialog again, and no interface for it has been found yet HMODULE credUIDLL = !Windows7AndLater ? HANDLES(LoadLibrary("CREDUI.DLL")) : NULL; FT_CredUIPromptForCredentialsA credUIPromptForCredentialsA = NULL; FT_CredUIConfirmCredentialsA credUIConfirmCredentialsA = NULL; @@ -530,7 +530,7 @@ BOOL RestoreNetworkConnection(HWND parent, const char* name, const char* remoteN } BOOL connectInteractive = FALSE; // TRUE: Windows 7 always, XP+Vista only if CREDUI.DLL is not available or it is not a simple UNC path: we will use the CONNECT_INTERACTIVE flag (can do with "network passwords") and therefore the blocking call WNetAddConnection3 (must be in the same thread with the parent) - BOOL confirmCred = FALSE; // TRUE: calling CredUIConfirmCredentialsA is needed + BOOL confirmCred = FALSE; // TRUE: CredUIConfirmCredentialsA must be called // char domain[DOMAIN_MAXLEN]; CREDUI_INFOA uiInfo = {0}; @@ -542,9 +542,9 @@ BOOL RestoreNetworkConnection(HWND parent, const char* name, const char* remoteN char messageBuf[MAX_PATH + 100]; messageBuf[0] = 0; - if (name == NULL) // mapping UNC paths to "none" + if (name == NULL) // map UNC paths to "none" { - if (!Windows7AndLater && // there's a new dialog again on Windows 7 and I haven't found the interface for it yet + if (!Windows7AndLater && // Windows 7 uses a new dialog again, and no interface for it has been found yet credUIPromptForCredentialsA != NULL && credUIConfirmCredentialsA != NULL /*&& credUIParseUserNameA != NULL*/ && serverName[0] != 0) // own dialog for entering username+password we will show only for simple UNC paths (\\server\share), we will leave DFS and others to the system { @@ -558,30 +558,30 @@ BOOL RestoreNetworkConnection(HWND parent, const char* name, const char* remoteN else { if (lpNetResource == NULL) - UpdateWindow(MainWindow->HWindow); // doesn't make sense to use from nethood - if (err == NO_ERROR) // user confirmed with OK + UpdateWindow(MainWindow->HWindow); // not useful from Network Neighborhood + if (err == NO_ERROR) // user clicked OK { confirmCred = TRUE; lstrcpyn(userNameBuf, dlg.User, USERNAME_MAXLEN); userName = userNameBuf; passwd = dlg.Passwd; - /* // there was a problem with trimming the domain from the username, they just couldn't log in because we made their domain name local - if (credUIParseUserNameA(dlg.User, userNameBuf, USERNAME_MAXLEN, domain, DOMAIN_MAXLEN) == NO_ERROR) - { - confirmCred = TRUE; - userName = userNameBuf; - passwd = dlg.Passwd; - } - else - { - TRACE_E("RestoreNetworkConnection(): CredUIParseUserNameA failed for: " << dlg.User); - userNameBuf[0] = 0; - userName = NULL; - credUIConfirmCredentialsA(serverName, FALSE); - connectInteractive = TRUE; // another error, let the system variant deal with it - err = ERROR_BAD_USERNAME; - } -*/ + /* // there was a problem with stripping the domain from the username; users could not log in because we converted their domain username into a local one + if (credUIParseUserNameA(dlg.User, userNameBuf, USERNAME_MAXLEN, domain, DOMAIN_MAXLEN) == NO_ERROR) + { + confirmCred = TRUE; + userName = userNameBuf; + passwd = dlg.Passwd; + } + else + { + TRACE_E("RestoreNetworkConnection(): CredUIParseUserNameA failed for: " << dlg.User); + userNameBuf[0] = 0; + userName = NULL; + credUIConfirmCredentialsA(serverName, FALSE); + connectInteractive = TRUE; // another error, let the system implementation handle it + err = ERROR_BAD_USERNAME; + } + */ } else connectInteractive = TRUE; // another error, let the system variant deal with it @@ -618,7 +618,7 @@ BOOL RestoreNetworkConnection(HWND parent, const char* name, const char* remoteN memset(dlg.Passwd, 0, sizeof(dlg.Passwd)); passwd = NULL; - if (err == ERROR_CANCELLED) // cancel + if (err == ERROR_CANCELLED) // canceled { ret = FALSE; break; @@ -715,7 +715,7 @@ BOOL RestoreNetworkConnection(HWND parent, const char* name, const char* remoteN } BOOL newConnectInteractive = FALSE; - if (!Windows7AndLater && // there's a new dialog again on Windows 7 and I haven't found the interface for it yet + if (!Windows7AndLater && // Windows 7 uses a new dialog again, and no interface for it has been found yet credUIPromptForCredentialsA != NULL && credUIConfirmCredentialsA != NULL /*&& credUIParseUserNameA != NULL*/ && serverName[0] != 0) // own dialog for entering username+password we will show only for simple UNC paths (\\server\share), we will leave DFS and others to the system { @@ -731,8 +731,8 @@ BOOL RestoreNetworkConnection(HWND parent, const char* name, const char* remoteN else { if (lpNetResource == NULL) - UpdateWindow(MainWindow->HWindow); // doesn't make sense to use from nethood - if (err == NO_ERROR) // user confirmed with OK + UpdateWindow(MainWindow->HWindow); // not meaningful when used from Network Neighborhood + if (err == NO_ERROR) // user clicked OK { if (name == NULL) confirmCred = TRUE; @@ -773,7 +773,7 @@ BOOL RestoreNetworkConnection(HWND parent, const char* name, const char* remoteN if (newConnectInteractive) { - if (!connectInteractive) // let's try an interactive mode only if we haven't used it already (a defense against an infinite cycle) + if (!connectInteractive) // try interactive mode only if it has not been used already (to prevent an infinite loop) { connectInteractive = TRUE; continue; @@ -805,7 +805,7 @@ BOOL RestoreNetworkConnection(HWND parent, const char* name, const char* remoteN if (MainWindow != NULL && MainWindow->HWindow != NULL) PostMessage(MainWindow->HWindow, WM_USER_DRIVES_CHANGE, 0, 0); - break; // returning TRUE + break; // function returns TRUE } } memset(dlg.Passwd, 0, sizeof(dlg.Passwd)); @@ -826,7 +826,7 @@ BOOL CheckAndRestoreNetworkConnection(HWND parent, const char drive, BOOL& pathI GetNetworkDrives(netDrives, netRemotePath); - if (netDrives & (1 << (LowerCase[drive] - 'a'))) // disk existed, try to restore + if (netDrives & (1 << (LowerCase[drive] - 'a'))) // the drive existed, so try to restore it { char name[4] = " :"; name[0] = drive; @@ -836,7 +836,7 @@ BOOL CheckAndRestoreNetworkConnection(HWND parent, const char drive, BOOL& pathI name[3] = 0; DWORD err = NO_ERROR; char* netPath = netRemotePath[LowerCase[drive] - 'a']; - if (netPath[0] == '\\' && netPath[1] == '\\' && strchr(netPath + 2, '\\') != NULL && // at least a primitive test of a valid UNC path + if (netPath[0] == '\\' && netPath[1] == '\\' && strchr(netPath + 2, '\\') != NULL && // at least a basic validity check for the UNC path (err = SalCheckPath(FALSE, name, ERROR_SUCCESS, TRUE, parent)) != ERROR_SUCCESS && err != ERROR_USER_TERMINATED && // mapped disk is not accessible (err = SalCheckPath(FALSE, netPath, ERROR_SUCCESS, TRUE, parent)) == ERROR_SUCCESS && // UNC is accessible (err = SalCheckPath(FALSE, name, ERROR_SUCCESS, TRUE, parent)) == ERROR_SUCCESS) // now the mapped disk is accessible again @@ -864,7 +864,7 @@ BOOL CheckAndConnectUNCNetworkPath(HWND parent, const char* UNCPath, BOOL& pathI CALL_STACK_MESSAGE3("CheckAndConnectUNCNetworkPath(, %s, , %d)", UNCPath, donotReconnect); pathInvalid = FALSE; if (!IsUNCPath(UNCPath) || UNCPath[2] == '?') - return FALSE; // no basic format UNC path + return FALSE; // not a UNC path in the basic UNC format char root[MAX_PATH + 4]; char* s = root + GetRootPath(root, UNCPath); @@ -876,13 +876,13 @@ BOOL CheckAndConnectUNCNetworkPath(HWND parent, const char* UNCPath, BOOL& pathI { // UNC root path is accessible, we will not do anything HANDLES(FindClose(h)); } - else // UNC root of the path is not listable + else // the UNC root path cannot be listed { *(s - 1) = 0; // we will trim the backslash at the end of the root path DWORD err = GetLastError(); BOOL trySharepoint = err == ERROR_BAD_NET_NAME; // try to call shell when error 67 occurs, so that it can make the path accessible if (!donotReconnect && - (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)) // on XP, this error is returned if the user does not have access to the server or the share does not exist on the server, to distinguish these two errors, we call WNetAddConnection3 + (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)) // on XP, this error is returned if the user does not have access to the server or if the share does not exist; we call WNetAddConnection3 to distinguish between the two cases { NETRESOURCE ns; ns.dwType = RESOURCETYPE_DISK; @@ -893,15 +893,15 @@ BOOL CheckAndConnectUNCNetworkPath(HWND parent, const char* UNCPath, BOOL& pathI err = ERROR_PATH_NOT_FOUND; // ESC } - if (IsLogonFailureErr(err) || // a defense against e.g. "no files found" + if (IsLogonFailureErr(err) || // guard against e.g. "no files found" IsAdminShareExtraLogonFailureErr(err, root)) { if (donotReconnect) pathInvalid = TRUE; // we report the error directly else { - // Petr: I commented out, Explorer or TC do not show any error before displaying the dialog for entering user + password; besides - // we now show a new error after trying to establish a connection (so that the user finds out that he has an expired password, etc.) + // Petr: commented out. Explorer and TC do not show any error before displaying the user name and password dialog; moreover, + // the error is now shown only after an attempt to establish a connection, so the user learns about an expired password, etc. // SalMessageBox(parent, GetErrorText(err), LoadStr(IDS_NETWORKERROR), // MB_OK | MB_ICONEXCLAMATION); @@ -911,7 +911,7 @@ BOOL CheckAndConnectUNCNetworkPath(HWND parent, const char* UNCPath, BOOL& pathI } else { - if (trySharepoint) // we will try to call shell when error 67 occurs, so that it can make the path accessible + if (trySharepoint) // on error 67, try calling the shell to make the path accessible { SHFILEINFO fi; if (SHGetFileInfoAux(UNCPath, 0, &fi, sizeof(fi), SHGFI_ATTRIBUTES)) @@ -923,15 +923,15 @@ BOOL CheckAndConnectUNCNetworkPath(HWND parent, const char* UNCPath, BOOL& pathI } // **************************************************************************** -// tenhle kod je vzaty z Knowledge Base a slouzi k ziskani informaci o typu media -// floppy mechaniky (3.5", 5.25", 8") +// this code is taken from the Knowledge Base and is used to obtain information about the media type +// of floppy drives (3.5", 5.25", 8") /* GetDriveFormFactor returns the drive form factor. It returns 350 if the drive is a 3.5" floppy drive. It returns 525 if the drive is a 5.25" floppy drive. - It returns 800 if the drive is a 8" floppy drive. + It returns 800 if the drive is an 8" floppy drive. It returns 1 if the drive supports removable media other than 3.5", 5.25", and 8" floppies. It returns 0 on error. @@ -1027,7 +1027,7 @@ void DisplayMenuAux(IContextMenu2* contextMenu, CMINVOKECOMMANDINFO* ici) void DisplayMenuAux2(IContextMenu2* contextMenu, HMENU h) { CALL_STACK_MESSAGE_NONE - // temporary lower the thread priority so that some confused shell extension doesn't eat our CPU + // temporarily lower the thread priority so that some confused shell extension does not eat all the CPU HANDLE hThread = GetCurrentThread(); // pseudo-handle, no need to release int oldThreadPriority = GetThreadPriority(hThread); SetThreadPriority(hThread, THREAD_PRIORITY_NORMAL); @@ -1073,7 +1073,7 @@ CDrivesList::CDrivesList(CFilesWindow* filesWindow, const char* currentPath, CachedDrivesMask = 0; CachedCloudStoragesMask = 0; - // standardne nejde o post-cmd, proto nulujeme + // this is normally not a post-command, so clear it *PostCmd = 0; *PostCmdParam = NULL; *FromContextMenu = FALSE; @@ -1090,7 +1090,7 @@ CDrivesList::OwnGetDriveType(const char* rootPath) case DRIVE_REMOVABLE: ret = drvtRemovable; break; - case DRIVE_NO_ROOT_DIR: // subst of which the directory was deleted (can also be remote, but we don't care about that) + case DRIVE_NO_ROOT_DIR: // subst drive whose directory was deleted (it can also be remote, but we ignore that) case DRIVE_FIXED: ret = drvtFixed; break; @@ -1136,7 +1136,7 @@ unsigned ReadCDVolNameThreadFBody(void* param) // directory accessibility test HANDLES(EnterCriticalSection(&ReadCDVolNameCS)); BOOL run = FALSE; - if (uid == ReadCDVolNameReqUID) // someone is still waiting for an answer + if (uid == ReadCDVolNameReqUID) // someone is still waiting for the response { lstrcpyn(root, ReadCDVolNameBuffer, MAX_PATH); run = TRUE; @@ -1148,12 +1148,12 @@ unsigned ReadCDVolNameThreadFBody(void* param) // directory accessibility test DWORD dummy; char fileSystem[11]; if (!GetVolumeInformation(root, buf, MAX_PATH, NULL, &dummy, &dummy, fileSystem, 10)) - buf[0] = 0; // error GetVolumeInformation + buf[0] = 0; // GetVolumeInformation failed if (buf[0] == 0) GetDisplayNameFromSystem(root, buf, MAX_PATH); HANDLES(EnterCriticalSection(&ReadCDVolNameCS)); - if (uid == ReadCDVolNameReqUID) // someone is still waiting for an answer + if (uid == ReadCDVolNameReqUID) // someone is still waiting for the response lstrcpyn(ReadCDVolNameBuffer, buf, MAX_PATH); HANDLES(LeaveCriticalSection(&ReadCDVolNameCS)); } @@ -1240,7 +1240,7 @@ int GetIndexForDrvText(CPluginFSInterfaceEncapsulation** fsList, int count, { CPluginFSInterfaceEncapsulation* fs = NULL; int z; - for (z = 0; z < count; z++) // found encapsulation FS (if there is a lack of memory, the indexes in fsList and Drives (from the firstFSIndex offset) may not match) + for (z = 0; z < count; z++) // found FS encapsulation (if memory is low, the indexes in fsList and Drives may not match from firstFSIndex onward) { if (fsList[z]->GetInterface() == fsIface) { @@ -1258,8 +1258,8 @@ int GetIndexForDrvText(CPluginFSInterfaceEncapsulation** fsList, int count, return currentIndex; } -// based on 'hSrcIcon' creates a black and white version of the icon -// WARNING, SLOW, use with caution +// creates a grayscale version of the icon from 'hSrcIcon' +// WARNING: slow; use with caution HICON ConvertIcon16x16ToGray(HICON hSrcIcon) { CIconList il; @@ -1356,7 +1356,7 @@ void InitDropboxPath() if (hFile != INVALID_HANDLE_VALUE) { LARGE_INTEGER size; - if (GetFileSizeEx(hFile, &size) && size.QuadPart < 100000) // 100KB is enough for a stupid config file + if (GetFileSizeEx(hFile, &size) && size.QuadPart < 100000) // 100 KB is more than enough for a config file { char* buf = (char*)malloc(size.LowPart); DWORD read; @@ -1373,7 +1373,7 @@ void InitDropboxPath() char* secRowEnd = secRow; while (secRowEnd < end && *secRowEnd != '\r' && *secRowEnd != '\n') secRowEnd++; - if (secRow < secRowEnd) // I have a text 2. rows, where the base64 encoded searched path is + if (secRow < secRowEnd) // second line text containing the target path encoded in Base64 { int pathLen; if (base64_decode(secRow, (int)(secRowEnd - secRow), &pathLen, "Dropbox path: ")) @@ -1460,10 +1460,10 @@ BOOL COneDriveBusinessStorages::Find(const char* displayName, const char** userF void InitOneDrivePath() { - OneDrivePath[0] = 0; // we find out the path to OneDrive over and over again, because after the commend "Unlink OneDrive" (from OneDrive) we should stop showing it + OneDrivePath[0] = 0; // The OneDrive path is resolved every time, because after the "Unlink OneDrive" command in OneDrive, it should no longer be shown. BOOL done = FALSE; - if (WindowsVistaAndLater) // SHGetKnownFolderPath has existed since Vista + if (WindowsVistaAndLater) // SHGetKnownFolderPath has been available since Vista { typedef HRESULT(WINAPI * FSHGetKnownFolderPath)(REFKNOWNFOLDERID rfid, DWORD /* KNOWN_FOLDER_FLAG */ dwFlags, @@ -1476,11 +1476,11 @@ void InitOneDrivePath() PWSTR path = NULL; if (DynSHGetKnownFolderPath(my_FOLDERID_SkyDrive, 0, NULL, &path) == S_OK && path != NULL) { - if (path[0] != 0) // FOLDERID_SkyDrive was introduced in Windows 8.1 = we should not need to hunt it in the registry + if (path[0] != 0) // FOLDERID_SkyDrive was introduced in Windows 8.1, so it should not be necessary to look it up in the registry { done = ConvertU2A(path, -1, OneDrivePath, _countof(OneDrivePath)) != 0; if (!done) - OneDrivePath[0] = 0; // just for sync + OneDrivePath[0] = 0; // just to be safe //else TRACE_I("OneDrive path (FOLDERID_SkyDrive): " << OneDrivePath); } CoTaskMemFree(path); @@ -1490,12 +1490,12 @@ void InitOneDrivePath() HKEY hKey; char path[MAX_PATH]; - for (int i = 0; !done && i < 2; i++) // theoretically only needed for Windows 8 and lower (from 8.1 we have FOLDERID_SkyDrive) + for (int i = 0; !done && i < 2; i++) // theoretically only needed for Windows 8 and earlier (from 8.1 onward we have FOLDERID_SkyDrive) { if (HANDLES_Q(RegOpenKeyEx(HKEY_CURRENT_USER, - Windows8_1AndLater && !Windows10AndLater ? (i == 0 ? "Software\\Microsoft\\Windows\\CurrentVersion\\OneDrive" : // jen Win 8.1 + Windows8_1AndLater && !Windows10AndLater ? (i == 0 ? "Software\\Microsoft\\Windows\\CurrentVersion\\OneDrive" : // Windows 8.1 only "Software\\Microsoft\\Windows\\CurrentVersion\\SkyDrive") - : (i == 0 ? "Software\\Microsoft\\OneDrive" : "Software\\Microsoft\\SkyDrive"), // krom Win 8.1 + : (i == 0 ? "Software\\Microsoft\\OneDrive" : "Software\\Microsoft\\SkyDrive"), // except Windows 8.1 0, KEY_READ, &hKey)) == ERROR_SUCCESS) { DWORD size = sizeof(path); // size in bytes @@ -1504,7 +1504,7 @@ void InitOneDrivePath() type == REG_SZ && size > 1) { //TRACE_I("OneDrive path (UserFolder): " << path); - strcpy_s(OneDrivePath, path); // we have needed path + strcpy_s(OneDrivePath, path); // we have the required path done = TRUE; } HANDLES(RegCloseKey(hKey)); @@ -1524,7 +1524,7 @@ void InitOneDrivePath() if (RegEnumKeyEx(hKey, i, keyName, &keyNameLen, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) { // opening the account key HKEY hAccount; - if (StrICmp(keyName, "Personal") != 0 && // we don't want to read personal account here (see OneDrivePath) + if (StrICmp(keyName, "Personal") != 0 && // do not read the personal account here (see OneDrivePath) HANDLES_Q(RegOpenKeyEx(hKey, keyName, 0, KEY_READ, &hAccount)) == ERROR_SUCCESS) { // we read all accounts except Personal (for now only "Business???", where ??? is a number) char disp[ONEDRIVE_MAXBUSINESSDISPLAYNAME]; @@ -1536,7 +1536,7 @@ void InitOneDrivePath() size = sizeof(path); // size in bytes if (SalRegQueryValueEx(hAccount, "UserFolder", 0, &type, (BYTE*)path, &size) == ERROR_SUCCESS && type == REG_SZ && size > 1) - { // we will collect everything that has DisplayName and UserFolder, no matter what it is, we will offer it to the user under "OneDrive" + { // Collect every item that has DisplayName and UserFolder and offer it to the user as "OneDrive" //TRACE_I("OneDrive Business: DisplayName: " << disp << ", UserFolder: " << path); OneDriveBusinessStorages.SortIn(new COneDriveBusinessStorage(DupStr(disp), DupStr(path))); } @@ -1545,7 +1545,7 @@ void InitOneDrivePath() } } else - break; // end of enumeration (can also be a small buffer, but I don't consider it reasonable to handle) + break; // end of enumeration (this can also mean the buffer is too small, but handling that is not considered worthwhile) i++; } HANDLES(RegCloseKey(hKey)); @@ -1561,7 +1561,7 @@ void CDrivesList::AddToDrives(CDriveData& drv, int textResId, char hotkey, CDriv BOOL getGrayIcons, HICON icon, BOOL destroyIcon, const char* itemText) { const char* s = itemText != NULL ? itemText : LoadStr(textResId); - // WARNING: for drvtOneDriveBus, DisplayName is later taken from drv.DriveText, when changing the text format, change it !!! + // WARNING: for drvtOneDriveBus, DisplayName is later taken from drv.DriveText; if the text format changes, update this accordingly char* txt = (char*)malloc(1 + (hotkey == 0 ? 0 : 1) + strlen(s) + 1); strcpy(txt, hotkey == 0 ? "\t" : " \t"); if (hotkey != 0) @@ -1610,11 +1610,11 @@ BOOL CDrivesList::BuildData(BOOL noTimeout, TDirectArray* copyDrives ZeroMemory(&drvSeparator, sizeof(drvSeparator)); drvSeparator.DriveType = drvtSeparator; - if (copyDrives != NULL) // optimization: data is just copied (e.g. it's the second Drives Bar, so we copy the data from the first Drives Bar, for which we got it from the system a few ms ago) + if (copyDrives != NULL) // optimization: the data is simply copied (e.g. this is the second Drives Bar, so we copy the data from the first Drives Bar, for which we retrieved it from the system a few ms ago) { CachedDrivesMask = copyCachedDrivesMask; - // I will add drives a..z + // Add drives A..Z int lastDiskDrv = -1; int x; for (x = 0; x < copyDrives->Count; x++) @@ -1658,7 +1658,7 @@ BOOL CDrivesList::BuildData(BOOL noTimeout, TDirectArray* copyDrives else { // remembered and not refreshed network drives will not be returned from GetLogicalDrives() - DWORD netDrives; // bitove pole network disku + DWORD netDrives; // bit array of network drives char netRemotePath['z' - 'a' + 1][MAX_PATH]; GetNetworkDrives(netDrives, netRemotePath); @@ -1672,14 +1672,14 @@ BOOL CDrivesList::BuildData(BOOL noTimeout, TDirectArray* copyDrives CQuadWord freeSpace; // how much space we have on the disk - Shares.PrepareSearch(""); // now we will search for drives roots + Shares.PrepareSearch(""); // now we will look for drive roots - BOOL separateNextDrive = FALSE; // before we insert drive, should we insert separator? + BOOL separateNextDrive = FALSE; // before inserting the drive, should we insert a separator? - // I will add drives a..z + // Add drives A..Z while (i != 0) { - if (!(noDrivesPolicy & i) && ((mask & i) || (netDrives & i))) // disk is accessible + if (!(noDrivesPolicy & i) && ((mask & i) || (netDrives & i))) // drive is accessible { root[0] = drive; int driveType; @@ -1853,8 +1853,8 @@ BOOL CDrivesList::BuildData(BOOL noTimeout, TDirectArray* copyDrives // we separate drives that the user wanted to separate if (separateNextDrive && Drives->Count > 0 && !IsLastItemSeparator()) Drives->Add(drvSeparator); - // if there's no drive A or B in the system and the user has set the separator after A or B, we've shown it after C - // that's why we have to drop the flag in any case, not just in the previous condition + // if drive A or B is not present in the system and the user set a separator after A or B, we displayed it after C + // therefore we must clear the flag in every case, not just in the previous condition separateNextDrive = FALSE; int index = Drives->Add(drv); @@ -1956,7 +1956,7 @@ BOOL CDrivesList::BuildData(BOOL noTimeout, TDirectArray* copyDrives drv.DLLName = NULL; // just for sure int iconSize = GetIconSizeForSystemDPI(ICONSIZE_16); - // I will add the separator if it is not the first item and if there is no separator yet + // add a separator if this is not the first item and there is not one already if (Drives->Count > 0 && !IsLastItemSeparator()) Drives->Add(drvSeparator); @@ -1967,11 +1967,11 @@ BOOL CDrivesList::BuildData(BOOL noTimeout, TDirectArray* copyDrives SalLoadIcon(ImageResDLL, 112, iconSize)); } - // adding Cloud Storages (Google Drive, etc.), if I find any... + // Add cloud storages (Google Drive, etc.) if any are found CachedCloudStoragesMask = 0; if (Configuration.ChangeDriveCloudStorage) { - CSQLite3DynLoadBase* sqlite3_Dyn_InOut = NULL; // I somewhat expected that sqlite3 will be needed for Dropbox, too, which eventually did not happen (so this is here just in case) + CSQLite3DynLoadBase* sqlite3_Dyn_InOut = NULL; // sqlite3 was expected to be needed for Dropbox too, but that turned out not to be the case, so this is kept here just in case ShellIconOverlays.InitGoogleDrivePath(&sqlite3_Dyn_InOut, TRUE); if (ShellIconOverlays.HasGoogleDrivePath()) { @@ -1999,7 +1999,7 @@ BOOL CDrivesList::BuildData(BOOL noTimeout, TDirectArray* copyDrives char itemText[200 + ONEDRIVE_MAXBUSINESSDISPLAYNAME]; HICON oneDriveIco = c == 0 ? NULL : SalLoadIcon(HInstance, IDI_ONEDRIVE, iconSize); BOOL destroyOneDriveIco = oneDriveIco != NULL; - if (forDriveBar && c > 1) // data for drive-bar && more storages = let the user choose from the menu (drop down) + if (forDriveBar && c > 1) // for the drive bar with multiple storages, let the user choose from a drop-down menu { strcpy_s(itemText, LoadStr(IDS_ONEDRIVE)); AddToDrives(drv, 0, 0, drvtOneDriveMenu, getGrayIcons, oneDriveIco, destroyOneDriveIco, itemText); @@ -2007,7 +2007,7 @@ BOOL CDrivesList::BuildData(BOOL noTimeout, TDirectArray* copyDrives } else // data for change drive menu || drive-bar && the only storage (we give a simple button on the drive-bar) { - if (OneDrivePath[0] != 0) // personal + if (OneDrivePath[0] != 0) // personal storage { if (c == 1) strcpy_s(itemText, LoadStr(IDS_ONEDRIVE)); // the only personal storage = we write only: OneDrive @@ -2016,8 +2016,8 @@ BOOL CDrivesList::BuildData(BOOL noTimeout, TDirectArray* copyDrives AddToDrives(drv, 0, 0, drvtOneDrive, getGrayIcons, oneDriveIco, destroyOneDriveIco, itemText); destroyOneDriveIco = FALSE; } - for (int i = 0; i < OneDriveBusinessStorages.Count; i++) // business - { // WARNING: for drvtOneDriveBus, DisplayName is later taken from drv.DriveText, when changing the text format, change it !!! + for (int i = 0; i < OneDriveBusinessStorages.Count; i++) // business storages + { // WARNING: For drvtOneDriveBus, DisplayName is later taken from drv.DriveText; if the text format changes, update this too. sprintf_s(itemText, "%s - %s", LoadStr(IDS_ONEDRIVE), OneDriveBusinessStorages[i]->DisplayName); AddToDrives(drv, 0, 0, drvtOneDriveBus, getGrayIcons, oneDriveIco, destroyOneDriveIco, itemText); destroyOneDriveIco = FALSE; @@ -2041,7 +2041,7 @@ BOOL CDrivesList::BuildData(BOOL noTimeout, TDirectArray* copyDrives neighborhoodIndex = Drives->Count - 1; } - // adding FS commands from all plug-ins + // adding FS commands from all plugins if (!Plugins.AddItemsToChangeDrvMenu(this, currentFSIndex, FilesWindow->GetPluginFS()->GetPluginInterfaceForFS()->GetInterface(), getGrayIcons)) @@ -2049,7 +2049,7 @@ BOOL CDrivesList::BuildData(BOOL noTimeout, TDirectArray* copyDrives return FALSE; } - // finding the index of the Nethood plug-in and setting it to neighborhoodIndex (we represent the Network item with everything) + // find the index of the Nethood plugin and store it in neighborhoodIndex (we fully represent the Network item) if (existsNethoodPlugin && nethoodPlugin != NULL && neighborhoodIndex == -1) { int i2; @@ -2073,7 +2073,7 @@ BOOL CDrivesList::BuildData(BOOL noTimeout, TDirectArray* copyDrives } else { - if (CurrentPath[0] != 0) // only if we have a path (it's not ptPluginFS) + if (CurrentPath[0] != 0) // only if we have a path (it is not ptPluginFS) { if (currentDiskIndex != -1) FocusIndex = currentDiskIndex; @@ -2120,13 +2120,13 @@ BOOL CDrivesList::BuildData(BOOL noTimeout, TDirectArray* copyDrives { BOOL destroyIcon; HICON icon = panel->GetPluginFS()->GetFSIcon(destroyIcon); - if (icon != NULL) // defined by a plugin + if (icon != NULL) // defined by the plugin { drv.HIcon = icon; drv.HGrayIcon = NULL; drv.DestroyIcon = destroyIcon; // we are driven by the plugin } - else // standard + else // default { drv.HIcon = SalLoadIcon(HInstance, IDI_PLUGINFS, iconSize); drv.HGrayIcon = NULL; @@ -2181,7 +2181,7 @@ BOOL CDrivesList::BuildData(BOOL noTimeout, TDirectArray* copyDrives drv.Accessible = TRUE; drv.Shared = FALSE; Drives->Add(drv); - drv.DestroyIcon = FALSE; // I won't clean up other icons anymore + drv.DestroyIcon = FALSE; // Do not clean up the remaining icons } else { @@ -2196,7 +2196,7 @@ BOOL CDrivesList::BuildData(BOOL noTimeout, TDirectArray* copyDrives if (Drives->Count > 0 && IsLastItemSeparator()) Drives->Delete(Drives->Count - 1); - if (drv.DestroyIcon) // no hot path, we have to remove the icon here + if (drv.DestroyIcon) // not a hot path, so we must destroy the icon here { HANDLES(DestroyIcon(drv.HIcon)); } @@ -2258,7 +2258,7 @@ BOOL CDrivesList::LoadMenuFromData() mii.HOverlay = HSharedOverlays[ICONSIZE_16]; mii.String = item->DriveText; mii.State = 0; - if (i == FocusIndex) // if FocusIndex==-1, nothing is marked + if (i == FocusIndex) // if FocusIndex == -1, nothing is checked mii.State = MENU_STATE_CHECKED; if (item->DriveType == drvtPluginFSInOtherPanel) mii.State |= MFS_DISABLED | MFS_GRAYED; @@ -2399,14 +2399,14 @@ BOOL CDrivesList::ExecuteItem(int index, HWND hwnd, const RECT* exclude, BOOL* f break; } - case drvtPluginFS: // a plug-in item: opened FS (active/disconnected) + case drvtPluginFS: // plugin item: open FS (active/disconnected) case drvtPluginFSInOtherPanel: // this should never come, we will stop it later (no action) { *DriveTypeParam = (DWORD_PTR)item->PluginFS; break; } - case drvtPluginCmd: // a plug-in item: FS command + case drvtPluginCmd: // a plugin item: FS command { *DriveTypeParam = (DWORD_PTR)item->DLLName; break; @@ -2721,7 +2721,7 @@ BOOL CDrivesList::OnContextMenu(BOOL posByMouse, int itemIndex, int panel, const if (pluginFSDLLName != NULL) *pluginFSDLLName = NULL; - // for the MenuPopup variable, access is only allowed if posByMouse == FALSE + // MenuPopup may only be accessed if posByMouse == FALSE int selectedIndex; if (itemIndex == -1 || !posByMouse) @@ -2781,7 +2781,7 @@ BOOL CDrivesList::OnContextMenu(BOOL posByMouse, int itemIndex, int panel, const } } else - return FALSE; // we can't do the context menu for other types of paths (relative, FS plugin) + return FALSE; // context menus are not supported for other path types (relative paths or plugin FS paths) break; } @@ -2802,7 +2802,7 @@ BOOL CDrivesList::OnContextMenu(BOOL posByMouse, int itemIndex, int panel, const if (dt == drvtPluginFS) { CPluginFSInterfaceAbstract* fs = Drives->At(selectedIndex).PluginFS; - // we need to verify, that 'fs' is still a valid interface + // we must verify that 'fs' is still a valid interface if (FilesWindow->Is(ptPluginFS) && FilesWindow->GetPluginFS()->GetInterface() == fs) { // active FS selection - we will do refresh pluginData = Plugins.GetPluginData(FilesWindow->GetPluginFS()->GetPluginInterfaceForFS()->GetInterface()); @@ -2850,7 +2850,7 @@ BOOL CDrivesList::OnContextMenu(BOOL posByMouse, int itemIndex, int panel, const p.y = selectedIndexRect.bottom; } - char pluginFSNameBuf[MAX_PATH]; // 'pluginFS' may cease to exist, so we put 'fsName' into a local buffer + char pluginFSNameBuf[MAX_PATH]; // 'pluginFS' may cease to exist, so we copy 'fsName' into a local buffer if (pluginFSName != NULL) lstrcpyn(pluginFSNameBuf, pluginFSName, MAX_PATH); if (pluginData->ChangeDriveMenuItemContextMenu(MainWindow->HWindow, panel, p.x, p.y, pluginFS, @@ -2885,14 +2885,14 @@ BOOL CDrivesList::OnContextMenu(BOOL posByMouse, int itemIndex, int panel, const } if (!failed) { - if (postCmd != 0) // closing Change Drive menu + executing postCmd + if (postCmd != 0) // closing the Change Drive menu and executing postCmd { *PostCmd = postCmd; *PostCmdParam = postCmdParam; *FromContextMenu = TRUE; return TRUE; } - else // just closing Change Drive menu + else // just closing the Change Drive menu { *PostCmd = 0; // not needed (set from constructor), just for clarity *FromContextMenu = TRUE; @@ -2900,7 +2900,7 @@ BOOL CDrivesList::OnContextMenu(BOOL posByMouse, int itemIndex, int panel, const } } } - if (refreshMenu) // plug-in asks for menu refresh + if (refreshMenu) // plugin requests a menu refresh { PostMessage(MainWindow->HWindow, WM_USER_DRIVES_CHANGE, 0, 0); } @@ -2923,7 +2923,7 @@ BOOL CDrivesList::OnContextMenu(BOOL posByMouse, int itemIndex, int panel, const case drvtOneDriveBus: case drvtOneDriveMenu: { - // for Documents, Network, As Other Panel a Cloud Storages we can't do context menu) + // no context menu for Documents, Network, As Other Panel, or Cloud Storages return FALSE; } @@ -2973,21 +2973,21 @@ BOOL CDrivesList::OnContextMenu(BOOL posByMouse, int itemIndex, int panel, const DWORD cmd = contextPopup.Track(MENU_TRACK_RETURNCMD | MENU_TRACK_RIGHTBUTTON, pt.x, pt.y, MainWindow->HWindow, NULL); - // WARNING: during the opened context menu, the object can be refreshed (e.g. user inserts - // a USB stick or disconnects a network drive), we have to count on it when accessing the - // data of this object (e.g. Drives can contain different data) + // WARNING: while the context menu is open, this object may be refreshed (for example, when the user inserts + // a USB stick or disconnects a network drive); this must be taken into account when accessing the + // object's data (for example, Drives may contain different data) if (cmd != 0) { BOOL releaseLeft = FALSE; // disconnect left panel from disk? BOOL releaseRight = FALSE; // disconnect right panel from disk? - char cmdName[2000]; // we have 2000 instead of 200 on purpose, shell extensions sometimes write double (consideration: unicode = 2 * "number of characters"), etc. + char cmdName[2000]; // we intentionally use 2000 instead of 200; shell extensions sometimes write twice as much (roughly: Unicode = 2 * "number of characters"), etc. if (AuxGetCommandString(MainWindow->ContextMenuChngDrv, cmd, GCS_VERB, NULL, cmdName, 200) != NOERROR) { cmdName[0] = 0; } - if (stricmp(cmdName, "properties") != 0 && // not mandatory for properties + if (stricmp(cmdName, "properties") != 0 && // not needed for Properties stricmp(cmdName, "find") != 0 && // not mandatory for find stricmp(cmdName, "open") != 0 && // not mandatory for open stricmp(cmdName, "explore") != 0 && // not mandatory for explore @@ -2998,7 +2998,7 @@ BOOL CDrivesList::OnContextMenu(BOOL posByMouse, int itemIndex, int panel, const for (i = 0; i < 2; i++) { win = i == 0 ? MainWindow->LeftPanel : MainWindow->RightPanel; - if (HasTheSameRootPath(win->GetPath(), path)) // identical disk (both normal and UNC) + if (HasTheSameRootPath(win->GetPath(), path)) // same drive (local or UNC) { if (i == 0) releaseLeft = TRUE; @@ -3031,15 +3031,15 @@ BOOL CDrivesList::OnContextMenu(BOOL posByMouse, int itemIndex, int panel, const ici.ptInvoke.y = pt.y; } - BOOL changeToFixedDrv = cmd == 35; // "format" is not modal, we need to change to fixed drive + BOOL changeToFixedDrv = cmd == 35; // "format" is not modal, so we need to switch to a fixed drive if (releaseLeft) { if (changeToFixedDrv) { MainWindow->LeftPanel->ChangeToFixedDrive(MainWindow->LeftPanel->HWindow); - // WARNING: we have to invalidate the window, so that the cached bitmap of Alt+F1/2 menu is broken - // otherwise, the old part of the panel was displayed in this situation: - // there is disk S: in the left panel; Alt+F1, right click on S, Format + // WARNING: The window must be invalidated to discard the cached bitmap of the Alt+F1/2 menu + // otherwise, an old part of the panel would be displayed in this situation: + // the left panel shows drive S:; Alt+F1, right-click S:, Format InvalidateRect(MainWindow->LeftPanel->HWindow, NULL, TRUE); } else @@ -3058,9 +3058,9 @@ BOOL CDrivesList::OnContextMenu(BOOL posByMouse, int itemIndex, int panel, const DisplayMenuAux(MainWindow->ContextMenuChngDrv, (CMINVOKECOMMANDINFO*)&ici); - // it's possible to change clipboard from context menu, we will check it ... + // the context menu can change the clipboard, so we will verify it ... IdleRefreshStates = TRUE; // we will force the check of the state variables at the next Idle - IdleCheckClipboard = TRUE; // we will the clipboard to be checked as well + IdleCheckClipboard = TRUE; // we will force the clipboard check as well UpdateWindow(MainWindow->HWindow); if (releaseLeft && !changeToFixedDrv) @@ -3068,7 +3068,7 @@ BOOL CDrivesList::OnContextMenu(BOOL posByMouse, int itemIndex, int panel, const if (releaseRight && !changeToFixedDrv) MainWindow->RightPanel->HandsOff(FALSE); - if (!selectedIndexAccessible) // unmap the remembered inactive network connection? + if (!selectedIndexAccessible) // unmapping a remembered inactive network connection? PostMessage(MainWindow->HWindow, WM_USER_DRIVES_CHANGE, 0, 0); /* @@ -3106,7 +3106,7 @@ BOOL CDrivesList::RebuildMenu() // remove old data DestroyData(); // get new ones - BuildData(TRUE); // timeout can't be used, reading CD labels takes long time (1,5s) - system notifies the driver earlier than it's loaded + BuildData(TRUE); // A timeout cannot be used; reading the CD label takes a long time (1.5 s), and the system notifies the drive before the label has been read. // remove items from menu MenuPopup->RemoveAllItems(); // get new items @@ -3122,7 +3122,7 @@ BOOL CDrivesList::FindPanelPathIndex(CFilesWindow* panel, DWORD* index) if (panel->Is(ptPluginFS)) { if (!panel->GetPluginFS()->IsServiceSupported(FS_SERVICE_GETCHANGEDRIVEORDISCONNECTITEM)) - { // searching for a plug-in FS without its own item in Change Drive menu (these items are not in Drive bars) + { // searching for a plugin FS without its own item in Change Drive menu (these items are not in Drive bars) int i; for (i = 0; i < Drives->Count; i++) { @@ -3141,7 +3141,7 @@ BOOL CDrivesList::FindPanelPathIndex(CFilesWindow* panel, DWORD* index) if (path[0] == '\\' && path[1] == '\\') { if (path[2] == '.' && path[3] == '\\' && path[4] != 0 && path[5] == ':') - return FALSE; // "\\.\C:\" type path + return FALSE; // path in the "\\.\C:\" form CPluginData* nethoodPlugin = NULL; Plugins.GetFirstNethoodPluginFSName(NULL, &nethoodPlugin); int i; diff --git a/src/drivelst.h b/src/drivelst.h index 030f69392..7b0cc4d37 100644 --- a/src/drivelst.h +++ b/src/drivelst.h @@ -49,8 +49,8 @@ int GetOneDriveStorages(); // CDrivesList // -// WARNING: in CDrivesList::BuildData test "DriveType > drvtRAMDisk" is used, so -// it is necessary to bear this in mind when changing the enum !!! +// WARNING: CDrivesList::BuildData uses the test "DriveType > drvtRAMDisk", so +// this must be taken into account when changing the enum. enum CDriveTypeEnum { @@ -106,19 +106,19 @@ class CDrivesList DWORD_PTR* DriveTypeParam; // x64: the referenced value must be able to hold a pointer, so DWORD_PTR int* PostCmd; // post-cmd for context menu of a FS plugin void** PostCmdParam; // post-cmd-parameter for context menu of a FS plugin - BOOL* FromContextMenu; // set to TRUE if the menu was invoked from a context menu + BOOL* FromContextMenu; // set to TRUE if the menu command was triggered by a context menu char CurrentPath[MAX_PATH]; TDirectArray* Drives; CMenuPopup* MenuPopup; int FocusIndex; // what item from the Drives array should be focused - DWORD CachedDrivesMask; // bit array of drives, which we got during the last BuildData() - DWORD CachedCloudStoragesMask; // bit array of cloud storages, which we got during the last BuildData() + DWORD CachedDrivesMask; // bitmask of drives obtained during the last BuildData() + DWORD CachedCloudStoragesMask; // bitmask of cloud storages obtained during the last BuildData() public: // input: - // driveType = dummy - // driveTypeParam = letter of the drive to activate (or 0 (PluginFS) or '\\' (UNC)) + // driveType = dummy + // driveTypeParam = drive letter to activate (or 0 (PluginFS) or '\\' (UNC)) CDrivesList(CFilesWindow* filesWindow, const char* currentPath, CDriveTypeEnum* driveType, DWORD_PTR* driveTypeParam, int* postCmd, void** postCmdParam, BOOL* fromContextMenu); ~CDrivesList() @@ -141,14 +141,17 @@ class CDrivesList // CM_DRIVEBAR_MIN, otherwise from CM_DRIVEBAR2_MIN BOOL FillDriveBar(CDriveBar* driveBar, BOOL bar2); - // here FilesWindows passes information that user right-clicked on item - // 'posByMouse' says whether we should popup the menu at mouse coordinates or under the selected item; - // 'panel' says which panel is active (it can be also inactive panel when there are two DriveBars - from - // Change Drive menu it is always PANEL_SOURCE, from DriveBars it is PANEL_LEFT or PANEL_RIGHT); - // if 'pluginFSDLLName' is not NULL and we are popping up a context menu for a FS item, it returns the - // name of the plugin DLL (or SPL); returns TRUE if we should execute the command on which the context - // menu was popped up (FALSE does nothing); 'itemIndex' says for which item we are popping up the context - // menu, 'posByMouse' must be TRUE; if 'itemIndex' is -1, the item is taken from the menu + // FilesWindow uses this to pass information that the user right-clicked an item. + // 'posByMouse' specifies whether the menu should be opened at the mouse coordinates or + // under the selected item; 'panel' specifies which panel is involved (with two Drive + // bars, this can also be the inactive panel - from the Change Drive menu it is always + // PANEL_SOURCE, from the Drive bars it is PANEL_LEFT or PANEL_RIGHT); if + // 'pluginFSDLLName' is not NULL and a context menu is being opened for an FS item, the + // plugin DLL name (more precisely, the SPL name) is returned through it; returns TRUE + // if the command for which the context menu was opened should be executed (FALSE does + // nothing); 'itemIndex' specifies for which item the context menu should be opened; + // then 'posByMouse' must be TRUE; if 'itemIndex' is -1, the item is obtained from + // the menu BOOL OnContextMenu(BOOL posByMouse, int itemIndex, int panel, const char** pluginFSDLLName); // A new loading of items into the menu is requested here. It is assumed that the menu is displayed @@ -179,14 +182,14 @@ class CDrivesList // 'index' to its index and returns TRUE, otherwise it returns FALSE BOOL FindPanelPathIndex(CFilesWindow* panel, DWORD* index); - // returns bit array of drives, which we got during the last BuildData() - // if BuildDate() has not been called yet, returns 0 - // can be used for quick detection of any change in the drives + // returns the bitmask of drives obtained during the last BuildData() + // if BuildData() has not been called yet, returns 0 + // can be used to quickly detect drive changes DWORD GetCachedDrivesMask(); - // returns bit array of available cloud storages, which we got during the last BuildData() - // if BuildDate() has not been called yet, returns 0 - // can be used for quick detection of any changes in the availability of cloud storages + // returns the bitmask of available cloud storages obtained during the last BuildData() + // if BuildData() has not been called yet, returns 0 + // can be used to quickly detect changes in cloud storage availability DWORD GetCachedCloudStoragesMask(); TDirectArray* GetDrives() { return Drives; } @@ -223,7 +226,7 @@ struct CNBWNetAC3Thread { if (Thread != NULL) { - AddAuxThread(Thread, TRUE); // thread can run only during shutdown, we will kill it by this + AddAuxThread(Thread, TRUE); // the thread may run only during shutdown; this lets it be terminated Thread = NULL; } if (shutdown) diff --git a/src/editwnd.cpp b/src/editwnd.cpp index 2dd4d6796..dcc74e972 100644 --- a/src/editwnd.cpp +++ b/src/editwnd.cpp @@ -193,7 +193,7 @@ BSHandlerSubclassProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) case WM_KEYDOWN: { - // handles Ctrl+Backspace for deleting a word + // handles Ctrl+Backspace to delete a word if (wParam == VK_BACK) { BOOL controlPressed = (GetKeyState(VK_CONTROL) & 0x8000) != 0; @@ -204,13 +204,13 @@ BSHandlerSubclassProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) int iStart, iEnd; SendMessage(hwnd, EM_GETSEL, (WPARAM)&iStart, (LPARAM)&iEnd); - // if a selection exists, cancel it and move the cursor to the end + // if a selection exists, clear it and move the cursor to the end if (iStart != iEnd) { SendMessage(hwnd, EM_SETSEL, iEnd, iEnd); iStart = iEnd; } - // if (iStart == iEnd) // nothing can't be selected + // if (iStart == iEnd) // nothing must be selected // { char buff[10000]; int len = GetWindowTextLength(hwnd); @@ -242,8 +242,8 @@ BSHandlerSubclassProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) return CallWindowProc(OldWndProc, hwnd, message, wParam, lParam); } -// we don't use WinLib's subclass so we don't step on its toes -// (some windows we need to attach may already be or will be under WinLib) +// We do not use WinLib subclassing so that we do not interfere with it +// (some windows we need to attach to are already or will be managed by WinLib) BOOL AttachBackspaceHandler(HWND hwndEdit) { WNDPROC oldWndProc = (WNDPROC)GetWindowLongPtr(hwndEdit, GWLP_WNDPROC); @@ -301,11 +301,11 @@ BOOL IsChangeDirAttempt(const char* text) int GetCmdLineLimit() { /* - Measured limits when launching via COMSPEC: - (4094 + length of the exe string) W2K (not dependent on COMSPEC length) - (8190 + length of the exe string) XP (not dependent on COMSPEC length) - 8156 Vista + Win7 with COMSPEC=C:\Windows\system32\cmd.exe (depends on COMSPEC lenght: longer COMSPEC = smaller limit) -*/ + Measured limits when launching via COMSPEC: + (4094 + length of the exe string) W2K (does not depend on COMSPEC length) + (8190 + length of the exe string) XP (does not depend on COMSPEC length) + 8156 Vista + Win7 with COMSPEC=C:\Windows\system32\cmd.exe (depends on COMSPEC length: longer COMSPEC = smaller limit) + */ #if SALCMDLINE_MAXLEN != 8192 // maximum value that GetCmdLineLimit() can return #pragma message(__FILE__ " ERROR: SALCMDLINE_MAXLEN != 8192. SALCMDLINE_MAXLEN and GetCmdLineLimit() must contain the same maximal value!") @@ -383,7 +383,7 @@ CEditLine::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) BOOL executed = FALSE; CFilesWindow* panel = MainWindow->GetActivePanel(); - if (panel->Is(ptDisk)) // running commands on disk -> executed in DOS Prompt + if (panel->Is(ptDisk)) // running commands on disk -> run in the DOS Prompt { // users coming from TC and other file managers tend to change the panel path via the command line // we'll try to break this habit @@ -447,7 +447,7 @@ CEditLine::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (strlen(cmd) + strlen(cmdLine) + 2 < SALCMDLINE_MAXLEN + MAX_PATH) { strcat(cmd, "\""); - strcat(cmd, cmdLine); // the user's command line must be quoted, otherwise commands containing quotes fail (e.g. >>"C:\APPS\WinRAR\UnRAR.exe" e "test.rar"<< prints >>'C:\APPS\WinRAR\UnRAR.exe" e "test.rar' is not recognized<<) + strcat(cmd, cmdLine); // the user's command line must be enclosed in quotes, otherwise commands containing quotes do not work (e.g. >>"C:\APPS\WinRAR\UnRAR.exe" e "test.rar"<< prints >>'C:\APPS\WinRAR\UnRAR.exe" e "test.rar' is not recognized<<) strcat(cmd, "\""); } else @@ -461,8 +461,8 @@ CEditLine::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) POINT p; if (MultiMonGetDefaultWindowPos(MainWindow->HWindow, &p)) { - // if the main window is on another monitor, we should open - // the created window there as well, ideally at the default position (same as on the primary) + // if the main window is on another monitor, the new window should open there as well, + // ideally at the default position (the same as on the primary monitor) si.dwFlags |= STARTF_USEPOSITION; si.dwX = p.x; si.dwY = p.y; @@ -791,7 +791,7 @@ CEditLine::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) // panel". I am not interested in this special Alt-Ctrl-functionality in // Salamander, I am definitely more interested in being able to type the // mentioned characters on the command line. - if ((controlPressed && !shiftPressed && !altPressed) /* || // Shift+number from the edit line won't work (you need to type '*' and others) + if ((controlPressed && !shiftPressed && !altPressed) /* || // Shift+number does not work in the edit line (you need to type '*' and other characters) (Configuration.ShiftForHotPaths && !controlPressed && shiftPressed) */ ) { @@ -857,7 +857,7 @@ CEditLine::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { case VK_RETURN: { - if (controlPressed && !altPressed) // filename of the selected file to the command line + if (controlPressed && !altPressed) // Insert the selected file name into the command line { SkipCharacter = TRUE; char path[MAX_PATH + 1]; @@ -1024,7 +1024,7 @@ class CEditDropTarget : public IDropTarget private: long RefCount; // object lifetime IDataObject* DataObject; // IDataObject that entered the drag - IDataObject* ForbiddenDataObject; // IDataObject we ignore (we are its source) + IDataObject* ForbiddenDataObject; // IDataObject to ignore (its source is this object) BOOL UseUnicode; // is Unicode text in DataObject? (otherwise we try ANSI text) CEditLine* EditLine; // edit line we operate on int EditWidth; @@ -1139,7 +1139,7 @@ class CEditDropTarget : public IDropTarget char* start = buff; if ((GetKeyState(VK_MENU) & 0x8000) != 0) { - // we do not want the whole path - trim it + // we do not want the full path - trim it int len = lstrlen(buff); if (len > 2) { @@ -1256,7 +1256,7 @@ class CEditDropTarget : public IDropTarget } ReleaseStgMedium(&stgMedium); } - /* removed overly strict check - dropping pagefile.sys failed + /* removed an unnecessarily strict check; pagefile.sys could not be dropped if (ret && path != NULL) { DWORD attrs = SalGetFileAttributes(path); @@ -1268,7 +1268,7 @@ class CEditDropTarget : public IDropTarget } STDMETHOD(QueryInterface) - (REFIID refiid, void FAR* FAR* ppv) + (REFIID refiid, void FAR * FAR * ppv) { if (refiid == IID_IUnknown || refiid == IID_IDropTarget) { @@ -1291,7 +1291,7 @@ class CEditDropTarget : public IDropTarget if (--RefCount == 0) { delete this; - return 0; // must not touch the object, it no longer exists + return 0; // must not access the object; it no longer exists } return RefCount; } @@ -1435,7 +1435,7 @@ class CEditDropTarget : public IDropTarget char* path = (char*)HANDLES(GlobalLock(stgMedium.hGlobal)); if (path != NULL) { - // change the path + // adjust the path if (UseUnicode) path = ConvertAllocU2A((const WCHAR*)path, -1); if (path != NULL) @@ -1450,9 +1450,9 @@ class CEditDropTarget : public IDropTarget else { char path[2 * MAX_PATH]; - if (GetNameFromDataObject(pDataObject, path)) // at most MAX_PATH characters are placed into 'path' + if (GetNameFromDataObject(pDataObject, path)) // at most MAX_PATH characters are written to 'path' { - // change the path + // Adjust the path if (!IsPluginFSPath(path)) { int l = (int)strlen(path); @@ -1867,15 +1867,15 @@ CEditWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (WindowsVistaAndLater) { - // Vista finally fixed the combobox flickering during resize - // so we must manually clear the area between child windows and the - // combobox edge, otherwise garbage remains there + // Vista finally fixed combobox flicker during resizing, + // so we must manually erase the area between the child windows and the + // combobox border; otherwise garbage remains there (HPEN) SelectObject(hDC, WndPen); Rectangle(hDC, cr.left + EL_XBORDER - 1, cr.top + 4 - 1, cr.right - GetSystemMetrics(SM_CXVSCROLL) - 1, cr.bottom - 4 + 1); } - // if a visual style is active, we won't decorate the button + // if a visual style is active, do not draw the button ourselves if (IsAppThemed()) { SelectObject(hDC, hOldPen); diff --git a/src/edtlbwnd.cpp b/src/edtlbwnd.cpp index 1f573779f..314698ca4 100644 --- a/src/edtlbwnd.cpp +++ b/src/edtlbwnd.cpp @@ -139,9 +139,9 @@ CEditListBox::CEditListBox(HWND hDlg, int ctrlID, DWORD flags, CObjectOrigin ori int itemHeight = max(tm.tmHeight + 4, IconSizes[ICONSIZE_16]); SendMessage(HWindow, LB_SETITEMHEIGHT, 0, MAKELPARAM(itemHeight, 0)); - // MakeDragList subclasses the list box and we stop receiving basic messages - // such as WM_LBUTTONDOWN, WM_MOUSEMOVE, ect. That makes this function unusable, - // so we implement drag&drop support ourselves. + // MakeDragList subclasses the list box, and we stop receiving basic messages + // such as WM_LBUTTONDOWN, WM_MOUSEMOVE, etc. This makes this function unusable, + // so drag-and-drop support is implemented directly here. // MakeDragList(HWindow); // DragNotify = RegisterWindowMessage(DRAGLISTMSGSTRING); } @@ -835,7 +835,7 @@ CEditListBox::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_KEYUP: { - if (Dragging) // We don't want the listbox processing this if we are dragging. + if (Dragging) // We do not want the list box to process this while dragging. return 0; break; } @@ -1077,7 +1077,7 @@ CEditListBox::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (Dragging) { LRESULT ret = CWindow::WindowProc(uMsg, wParam, lParam); - return ret | DLGC_WANTMESSAGE; // we want Escape + return ret | DLGC_WANTMESSAGE; // handle Escape } break; } diff --git a/src/edtlbwnd.h b/src/edtlbwnd.h index 40db688f8..8372d0bcd 100644 --- a/src/edtlbwnd.h +++ b/src/edtlbwnd.h @@ -114,7 +114,7 @@ class CEditListBox : public CWindow BOOL SetCurSel(int index); - // returns index of the selected item - for a new item it is one more than + // returns index of the selected item - for a new item it is 1 more than // the number of items BOOL GetCurSel(int& index); // returns -1 for an empty item diff --git a/src/execute.cpp b/src/execute.cpp index a68741043..6d987f8a8 100644 --- a/src/execute.cpp +++ b/src/execute.cpp @@ -57,7 +57,7 @@ void CComboboxEdit::GetSel(DWORD* start, DWORD* end) void CComboboxEdit::ReplaceText(const char* text) { - // we must refresh the selection because the dumb combobox forgot it + // we must restore the selection because the combo box lost it SendMessage(HWindow, EM_SETSEL, SelStart, SelEnd); SendMessage(HWindow, EM_REPLACESEL, TRUE, (LPARAM)text); } @@ -333,7 +333,7 @@ CExecuteItem CommandExecutes[] = // Arguments - External View/Edit -/* used by the export_mnu.py script that generates salmenu.mnu for the Translator +/* used by the export_mnu.py script, which generates salmenu.mnu for Translator keep synchronized with the array below... MENU_TEMPLATE_ITEM ArgumentsExecutes[] = { @@ -389,7 +389,7 @@ CExecuteItem ArgumentsExecutes[] = // Initial directory -/* used by the export_mnu.py script that generates salmenu.mnu for the Translator +/* used by the export_mnu.py script, which generates salmenu.mnu for Translator keep synchronized with the array below... MENU_TEMPLATE_ITEM InitDirExecutes[] = { @@ -580,7 +580,7 @@ struct CExecuteExpData char Buffer[MAX_PATH]; BOOL* FileNameUsed; - CUserMenuAdvancedData* UserMenuAdvancedData; // applies only to User Menu, otherwise NULL here + CUserMenuAdvancedData* UserMenuAdvancedData; // used only for User Menu; otherwise NULL here }; const char* WINAPI ExecuteExpDrive(HWND msgParent, void* param) // drive ("D:", "\\server\share") without backslash @@ -724,7 +724,7 @@ const char* WINAPI ExecuteExpNamePart(HWND msgParent, void* param) strcpy(data->Buffer, s + 1); char* ss = strrchr(data->Buffer, '.'); // if (ss != NULL && ss != data->Buffer) // extension is present ('.' not at the begining of the name, e.g. ".cvspass") - if (ss != NULL) // extension is present (".cvspass" is considered an extension in Windows) + if (ss != NULL) // An extension is present (".cvspass" is considered an extension in Windows) *ss = 0; return data->Buffer; } @@ -743,7 +743,7 @@ const char* WINAPI ExecuteExpExtPart(HWND msgParent, void* param) strcpy(data->Buffer, s + 1); s = strrchr(data->Buffer, '.'); // if (s != NULL && s != data->Buffer) // extension is present ('.' not at the begining of the name, e.g. ".cvspass") - if (s != NULL) // extension is present (".cvspass" is considered an extension in Windows) + if (s != NULL) // An extension is present here (".cvspass" is considered an extension in Windows) return s + 1; return ""; } @@ -762,7 +762,7 @@ const char* WINAPI ExecuteExpDOSNamePart(HWND msgParent, void* param) strcpy(data->Buffer, s + 1); char* ss = strrchr(data->Buffer, '.'); // if (ss != NULL && ss != data->Buffer) // extension is present ('.' not at the begining of the name, e.g. ".cvspass") - if (ss != NULL) // extension is present (".cvspass" is considered an extension in Windows) + if (ss != NULL) // An extension is present (".cvspass" is considered an extension in Windows) *ss = 0; return data->Buffer; } @@ -781,7 +781,7 @@ const char* WINAPI ExecuteExpDOSExtPart(HWND msgParent, void* param) strcpy(data->Buffer, s + 1); s = strrchr(data->Buffer, '.'); // if (s != NULL && s != data->Buffer) // extension is present ('.' not at the begining of the name, e.g. ".cvspass") - if (s != NULL) // extension is present (".cvspass" is considered an extension in Windows) + if (s != NULL) // extension present (".cvspass" is considered an extension in Windows) return s + 1; return ""; } @@ -1647,10 +1647,10 @@ CSalamanderVarStrEntry InitDirExpArray[] = { {EXECUTE_DRIVE, ExecuteExpDrive}, {EXECUTE_PATH, ExecuteExpPath2}, // j.r. I have no idea why the special versions of variables without - {EXECUTE_FULLPATH, ExecuteExpFullPath2}, // trailing backslashes are used; anyway, I added a call to + {EXECUTE_FULLPATH, ExecuteExpFullPath2}, // without trailing backslashes; anyway, I have now added a call to {EXECUTE_WINDIR, ExecuteExpWinDir2}, // RemoveDoubleBackslahesFromPath so we could probably switch to the {EXECUTE_SYSDIR, ExecuteExpSysDir2}, // versions with backslashes at the end -- we would just trim the - {EXECUTE_SALDIR, ExecuteExpSalDir2}, // last backslash in ExpandInitDir() (unless it's the root) + {EXECUTE_SALDIR, ExecuteExpSalDir2}, // remove the last backslash (unless this is the root) {NULL, NULL}}; // !!! do not use InfoLineExpArray directly; use GetInfoLineExpArray() @@ -1834,7 +1834,7 @@ BOOL ValidateInfoLineItems(HWND msgParent, const char* varText, int& errorPos1, { CALL_STACK_MESSAGE2("ValidateInfoLineItems(, %s, ,)", varText); return ValidateVarString(msgParent, varText, errorPos1, errorPos2, - GetInfoLineExpArray(TRUE /* for validation there is no difference between TRUE and FALSE */)); + GetInfoLineExpArray(TRUE /* TRUE and FALSE are equivalent for validation. */)); } BOOL ExpandInfoLineItems(HWND msgParent, const char* varText, CPluginDataInterfaceEncapsulation* pluginData, diff --git a/src/execute.h b/src/execute.h index ff1bf06bb..5c3c0daa8 100644 --- a/src/execute.h +++ b/src/execute.h @@ -101,8 +101,8 @@ struct CUserMenuValidationData // additional data used to validate User Menu: ar BOOL MustHandleItemsAsGroup; // TRUE = items must be processed as a group: ListOfSelectedNames, ListOfSelectedFullNames, FileToCompareXXX, DirToCompareXXX BOOL MustHandleItemsOneByOne; // TRUE = items must be processed individually: FullName, Name, NamePart, ExtPart, DOSFullName, DOSName, DOSNamePart, DOSExtPart int UsedCompareType; // 0 = none yet, 1 = file-left-right, 2 = file-active-inactive, 3 = dir-left-right, 4 = dir-active-inactive, 5 = multiple types (invalid), 6 = file-or-dir-left-right, 7 = file-or-dir-active-inactive - BOOL UsedCompareLeftOrActive; // TRUE = at least one variable compare-left or compare-active is used (we're testing if both parameters are used; otherwise it's nonsense) - BOOL UsedCompareRightOrInactive; // TRUE = at least one variable compare-right or compare-inactive is used (we're testing if both parameters are used; otherwise it's nonsense) + BOOL UsedCompareLeftOrActive; // TRUE = at least one compare-left or compare-active variable is used (we test whether both parameters are used; otherwise it makes no sense) + BOOL UsedCompareRightOrInactive; // TRUE = at least one compare-right or compare-inactive variable is used (we test whether both parameters are used; otherwise it makes no sense) }; struct CUserMenuAdvancedData // additional data used only for the User Menu: array Arguments diff --git a/src/filesbox.h b/src/filesbox.h index d2e7f48cc..bddc8b5f8 100644 --- a/src/filesbox.h +++ b/src/filesbox.h @@ -193,8 +193,8 @@ class CFilesBox : public CWindow // returns the new TopIndex that EnsureItemVisible would set for scroll == FALSE int PredictTopIndex(int index); - // special version: scrolls only the part of the screen that doesn't contain - // the item index, then repaints the remaining items + // special version of the function: scrolls only the part of the screen that does not contain + // item index; then repaints the remaining items void EnsureItemVisible2(int newTopIndex, int index); // returns TRUE if item 'index' is at least partially visible; if 'isFullyVisible' is not NULL, @@ -222,7 +222,7 @@ class CFilesBox : public CWindow void SetupScrollBars(DWORD flags = UPDATE_VERT_SCROLL | UPDATE_HORZ_SCROLL); // updates scrollbar information BOOL ShowHideChilds(); // shows or hides children based on Mode; returns TRUE when a change occurs otherwise returns FALSE void UpdateInternalData(); - void CheckAndCorrectBoundaries(); // ensures scrollbars are in valid ranges, adjusting them if needed + void CheckAndCorrectBoundaries(); // ensures the scrollbars are in valid positions, adjusting them if needed void OnHScroll(int scrollCode, int pos); void OnVScroll(int scrollCode, int pos); diff --git a/src/filesbx1.cpp b/src/filesbx1.cpp index 9f60f86bb..90ee09f00 100644 --- a/src/filesbx1.cpp +++ b/src/filesbx1.cpp @@ -826,7 +826,7 @@ BOOL CFilesBox::IsItemVisible(int index, BOOL* isFullyVisible) break; } } - return TRUE; // it is visible + return TRUE; // visible } // assumes scroll == FALSE - the whole item will be visible @@ -945,7 +945,7 @@ void CFilesBox::EnsureItemVisible2(int newTopIndex, int index) void CFilesBox::OnHScroll(int scrollCode, int pos) { - if (Parent->DragBox && !Parent->ScrollingWindow) // dragging the cage - block mouse wheel scrolling + if (Parent->DragBox && !Parent->ScrollingWindow) // dragging the DragBox - block mouse wheel scrolling return; if (ViewMode == vmDetailed) { @@ -1431,7 +1431,7 @@ CFilesBox::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_MOUSEACTIVATE: { if (MainWindow->HasLockedUI()) - break; // when the UI is locked we want a click on the panel to bring Salamander to front + break; // when the UI is locked, we want a click on the panel to bring Salamander to the front if (LOWORD(lParam) == HTCLIENT) { if (!IsIconic(MainWindow->HWindow) && @@ -1632,7 +1632,7 @@ CFilesBox::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) // therefore we will now also catch the message in individual windows where it can potentially appear (depending on focus) // and then route it so that it is delivered to the window under the cursor, as we always did - // if the message arrived "recently" through the other channel, ignore this one + // if the message was delivered "recently" through the other channel, ignore this one if (MouseWheelMSGThroughHook && MouseWheelMSGTime != 0 && (GetTickCount() - MouseWheelMSGTime < MOUSEWHEELMSG_VALID)) return 0; MouseWheelMSGThroughHook = FALSE; @@ -1699,9 +1699,9 @@ CFilesBox::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) wheelScroll = max(1, min(wheelScroll, si.nPage - 1)); // limit at most to page height } - // wheelScrollLines under WinVista with IntelliMouse Explorer 4.0 and IntelliPoint drivers is 40 at maximum wheel speed - // stepsPerLine would then be 120 / 31 = 3.870967..., after truncation 3, which is a large rounding error - // therefore I multiply values by 1000 to push the error three orders further + // Under WinVista with IntelliMouse Explorer 4.0 and IntelliPoint drivers, wheelScrollLines is 40 at the highest wheel speed + // stepsPerLine would then be 120 / 31 = 3.870967..., which truncates to 3 and causes a large rounding error + // therefore the values are multiplied by 1000 to move the error three orders of magnitude further MouseWheelAccumulator += 1000 * zDelta; int stepsPerLine = max(1, (1000 * WHEEL_DELTA) / wheelScroll); int linesToScroll = MouseWheelAccumulator / stepsPerLine; @@ -2016,7 +2016,7 @@ int CFilesBox::GetIndex(int x, int y, BOOL nearest, RECT* labelRect) SelectObject(hDC, hOldFont); maxWidth += 4; - if (isItemUpDir) // updir is just "..", we must extend it to the displayed size + if (isItemUpDir) // updir is only ".."; we must widen it to the displayed width { // see CFilesWindow::DrawIconThumbnailItem maxWidth = max(maxWidth, (Parent->GetViewMode() == vmThumbnails ? ThumbnailWidth : 32) + 4); @@ -2075,7 +2075,7 @@ int CFilesBox::GetIndex(int x, int y, BOOL nearest, RECT* labelRect) int maxTextWidth = ItemWidth - TILE_LEFT_MARGIN - IconSizes[ICONSIZE_48] - TILE_LEFT_MARGIN - 4; int widthNeeded = 0; - char buff[3 * 512]; // destination buffer for strings + char buff[3 * 512]; // buffer for strings char* out0 = buff; int out0Len; char* out1 = buff + 512; diff --git a/src/filesbx2.cpp b/src/filesbx2.cpp index 27552d6a6..ba22a744d 100644 --- a/src/filesbx2.cpp +++ b/src/filesbx2.cpp @@ -348,8 +348,8 @@ void CHeaderLine::SetMinWidths() if (column->SupportSorting == 1) column->MinWidth += 2 * SORT_BITMAP_W; - // when measuring the "Name" column and the next column isn't "Ext" - // and integration of "Ext" into "Name" is allowed, add the width of "Ext" + // when measuring the "Name" column and integration of "Ext" into "Name" is enabled, + // add the width of "Ext" if (i == 0 && !Parent->Parent->IsExtensionInSeparateColumn() && (Parent->Parent->ValidFileData & VALID_DATA_EXTENSION)) { @@ -380,7 +380,7 @@ CHeaderLine::HitTest(int xPos, int yPos, int& index, BOOL& extInName) right = left + column->Width; if (xPos >= left && xPos < right) { - // test the separators + // check the dividers if (xPos < left + 2 && i > 0 && Columns->At(i - 1).FixedWidth == 1) { index = i - 1; diff --git a/src/filesmap.cpp b/src/filesmap.cpp index 6937e814a..986459295 100644 --- a/src/filesmap.cpp +++ b/src/filesmap.cpp @@ -119,7 +119,7 @@ BOOL CFilesMap::CreateMap() AlterFileName(formatedFileName, f->Name, -1, Configuration.FileNameFormat, 0, isDir); const char* s = formatedFileName; - // skip the ".." + // suppress ".." if (*s == '.' && *(s + 1) == '.' && *(s + 2) == 0) s = NULL; @@ -418,7 +418,7 @@ void CFilesMap::SetPoint(int x, int y) } item = GetMapItem(col, row); - if (item == NULL) // there were several crashes in CFilesMap::SetPoint; cause unknown + if (item == NULL) // Several crashes occurred in CFilesMap::SetPoint; cause unknown continue; // this avoids a crash; at worst, selection will not work BOOL inOld = PointInRect(col, row, oldRect); diff --git a/src/fileswn0.cpp b/src/fileswn0.cpp index 882e101c2..bd62f6227 100644 --- a/src/fileswn0.cpp +++ b/src/fileswn0.cpp @@ -183,7 +183,7 @@ void CFilesWindow::CtrlPageDnOrEnter(WPARAM key) int index = GetCaretIndex(); if (key != VK_NEXT || index >= 0 && index < Dirs->Count || // Enter or directory or index >= Dirs->Count && index < Files->Count + Dirs->Count && - (Files->At(index - Dirs->Count).Archive || IsNethoodFS())) // an archive file or a file in the Nethood FS (it has servers listed as files and Entire Network as a directory, so the panel is sorted correctly -> Ctrl+PageDown must also open servers and their shares, because they are "directories") + (Files->At(index - Dirs->Count).Archive || IsNethoodFS())) // an archive file or a file in the Nethood FS (it lists servers as files and Entire Network as a directory so the panel sorts correctly; Ctrl+PageDown must therefore also open servers and their shares, because they are "directories") { Execute(index); } @@ -223,8 +223,8 @@ void CFilesWindow::FocusShortcutTarget(CFilesWindow* panel) return; } - //!!! ATTENTION, Resolve may display a dialog and messages will start to be dispatched - // the panel can be refreshed, so from this moment on it is not possible to access + //!!! WARNING: Resolve may display a dialog and messages may start to be dispatched + // the panel may be refreshed, so from this point on it is no longer possible to access // the file pointer BOOL invalid = FALSE; @@ -235,7 +235,7 @@ void CFilesWindow::FocusShortcutTarget(CFilesWindow* panel) strcpy(junctionOrSymlinkTgt, fullName); if (GetReparsePointDestination(junctionOrSymlinkTgt, junctionOrSymlinkTgt, MAX_PATH, &repPointType, FALSE)) { - // MOUNT POINT: I can't get this path in the panel (e.g., \??\Volume{98c0ba30-71ff-11e1-9099-005056c00008}\) + // MOUNT POINT: this path cannot be shown in the panel (e.g., \\??\\Volume{98c0ba30-71ff-11e1-9099-005056c00008}\\) if (repPointType == 1 /* MOUNT POINT */) mountPoint = TRUE; else @@ -282,7 +282,7 @@ void CFilesWindow::FocusShortcutTarget(CFilesWindow* panel) fullName[0] = 0; ITEMIDLIST* pidl; if (link->GetIDList(&pidl) == S_OK && pidl != NULL) - { // we get the ID-list and ask for the name of the last ID in the list, we expect "\\\\server" + { // get the ID list and ask for the name of its last ID; we expect "\\server" IMalloc* alloc; if (SUCCEEDED(CoGetMalloc(1, &alloc))) { @@ -403,7 +403,7 @@ void CFilesWindow::SelectFocusedIndex() { int index = GetCaretIndex(); SetSel(!GetSel(index), index); - if (index + 1 >= 0 && index + 1 < Dirs->Count + Files->Count) // a move + if (index + 1 >= 0 && index + 1 < Dirs->Count + Files->Count) // move SetCaretIndex(index + 1, FALSE); else RedrawIndex(index); @@ -666,7 +666,7 @@ int CFilesWindow::GetSelItems(int itemsCountMax, int* items, BOOL /*focusedItemF } } // we fill the second part of the list: from the first selected item towards firstItem - for (i = 0; i < firstItem; i++) // this is executed only if focusedItemFirst==TRUE is set + for (i = 0; i < firstItem; i++) // executed only if focusedItemFirst==TRUE { CFileData* item = (i < Dirs->Count) ? &Dirs->At(i) : &Files->At(i - Dirs->Count); if (item->Selected == 1) @@ -887,8 +887,8 @@ BOOL CFilesWindow::OnChar(WPARAM wParam, LPARAM lParam, LRESULT* lResult) BOOL controlPressed = (GetKeyState(VK_CONTROL) & 0x8000) != 0; BOOL altPressed = (GetKeyState(VK_MENU) & 0x8000) != 0; - // if we are in QuickSearchEnterAlt mode, we must set the focus to - // the command line and buffer the letter there + // If we are in QuickSearchEnterAlt mode, we must give focus to + // the command line and buffer the character there if (!controlPressed && !altPressed && !QuickSearchMode && wParam > 32 && wParam < 256 && @@ -905,23 +905,23 @@ BOOL CFilesWindow::OnChar(WPARAM wParam, LPARAM lParam, LRESULT* lResult) return FALSE; } - if (wParam > 31 && wParam < 256 && // only normal characters + if (wParam > 31 && wParam < 256 && // only printable characters Dirs->Count + Files->Count > 0) // at least 1 item { int index = FocusedIndex; - // On a German keyboard, the slash is on Shift+7, so it conflicts with HotPaths - // therefore, for * in QS, we will use backslash in addition to slash and sacrifice this + // On a German keyboard, slash is on Shift+7, so it conflicts with HotPaths + // therefore, for * in QS, we will use backslash in addition to slash and give up this // infrequently used function // // 8/2006: German users continue to complain that entering QS is - // difficult for them because with German layout enabled they have to press AltGr+\ - // however, they have the '<' key free, which by the way, when switching to an English - // keyboard means a backslash, so we will start catching the '<' character in addition to '\\' and '/' + // difficult for them because with the German layout enabled they have to press AltGr+\ + // however, they have a free '<' key, which maps to a backslash when the layout is switched + // to English, so we will also start catching the '<' character in addition to '\\' and '/' // the '<' character is also not allowed in a file name // //if (QuickSearchMode && (char)wParam == '\\') //{ - // // when the '\\' character is pressed during QS, we jump to the first item that matches QuickSearchMask + // // when the '\\' character is pressed during QS, jump to the first item that matches QuickSearchMask // if (!QSFindNext(GetCaretIndex(), TRUE, FALSE, TRUE, (char)0, index)) // QSFindNext(GetCaretIndex(), FALSE, TRUE, TRUE, (char)0, index); //} @@ -931,7 +931,7 @@ BOOL CFilesWindow::OnChar(WPARAM wParam, LPARAM lParam, LRESULT* lResult) QSFindNext(GetCaretIndex(), FALSE, TRUE, FALSE, (char)wParam, index); //} - if (!QuickSearchMode) // initialization of search + if (!QuickSearchMode) // Initialize quick search { if (GetViewMode() == vmDetailed) ListBox->OnHScroll(SB_THUMBPOSITION, 0); @@ -1056,8 +1056,8 @@ BOOL CFilesWindow::OnSysKeyDown(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT return TRUE; if (wParam == VK_SPACE && !shiftPressed && !controlPressed && !altPressed) - { // spacebar will be used for selection (names usually don't start with ' ') - if (!QuickSearchMode) // it can be in the middle of a name + { // spacebar toggles selection (names usually don't start with a space) + if (!QuickSearchMode) // ' ' can be in the middle of a name { SkipCharacter = TRUE; int index = GetCaretIndex(); @@ -1087,7 +1087,7 @@ BOOL CFilesWindow::OnSysKeyDown(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT } } } - if (index + 1 >= 0 && index + 1 < Dirs->Count + Files->Count) // a move + if (index + 1 >= 0 && index + 1 < Dirs->Count + Files->Count) // move SetCaretIndex(index + 1, FALSE); else RedrawIndex(index); @@ -1368,7 +1368,7 @@ BOOL CFilesWindow::OnSysKeyDown(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT return TRUE; } - case VK_ESCAPE: // end quick search mode via ESC + case VK_ESCAPE: // end quick search mode with Esc { EndQuickSearch(); return TRUE; @@ -1425,7 +1425,7 @@ BOOL CFilesWindow::OnSysKeyDown(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT strcmp(name, "..") != 0) && name[len] != 0) { - // if there is still another one + // if there is another one QuickSearch[len] = name[len]; QuickSearch[len + 1] = 0; int len2 = (int)strlen(QuickSearchMask); @@ -1632,7 +1632,7 @@ BOOL CFilesWindow::OnSysKeyDown(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT { case VK_SPACE: { - return TRUE; // I don't want space + return TRUE; // ignore Space } case VK_INSERT: // selection / deselection of a listbox item + move to the next one @@ -1690,7 +1690,7 @@ BOOL CFilesWindow::OnSysKeyDown(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT else if (GetViewMode() == vmDetailed) { int i; - for (i = 0; i < 5; i++) // let's do some macro programming + for (i = 0; i < 5; i++) // a bit of macro programming SendMessage(ListBox->HWindow, WM_HSCROLL, SB_LINEUP, 0); } break; @@ -1703,7 +1703,7 @@ BOOL CFilesWindow::OnSysKeyDown(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT else if (GetViewMode() == vmDetailed) { int i; - for (i = 0; i < 5; i++) // let's do some macro programming + for (i = 0; i < 5; i++) // repeat the scroll message several times SendMessage(ListBox->HWindow, WM_HSCROLL, SB_LINEDOWN, 0); } break; @@ -1738,7 +1738,7 @@ BOOL CFilesWindow::OnSysKeyDown(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT { if (newFocusedIndex > 0) { - if (altPressed) // Petr: in all modes, we go to the previous selected item (it might seem strange with icons/thumbnails/tiles, but it doesn't seem useful to me to search for a selected item only in the current column) + if (altPressed) // Petr: in all modes, go to the previous selected item (this may look odd in icons/thumbnails/tiles mode, but it does not seem useful to search for a selected item only in the current column) { int index; BOOL found = SelectFindNext(GetCaretIndex(), FALSE, TRUE, index); @@ -1780,7 +1780,7 @@ BOOL CFilesWindow::OnSysKeyDown(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT { if (newFocusedIndex < Dirs->Count + Files->Count - 1) { - if (altPressed) // Petr: in all modes, we go to the next selected item (it might seem strange with icons/thumbnails/tiles, but it doesn't seem useful to me to search for a selected item only in the current column) + if (altPressed) // Petr: in all modes, go to the next selected item (this may seem odd for icons/thumbnails/tiles, but searching for a selected item only in the current column does not seem useful) { int index; BOOL found = SelectFindNext(GetCaretIndex(), TRUE, TRUE, index); @@ -1976,7 +1976,7 @@ BOOL CFilesWindow::OnSysKeyDown(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT if (newFocusedIndex != FocusedIndex || forceSelect) { - if (shiftPressed) // shift+movement selecting + if (shiftPressed) // Shift+movement selection { BOOL select = SelectItems; // we'll get the state that the item had when Shift was pressed int targetIndex = newFocusedIndex; @@ -2047,7 +2047,7 @@ void CFilesWindow::OnSetFocus(BOOL focusVisible) // change: instead of immediate redrawing, we only invalidate the area; // the focus will not be so aggressive when switching to Salamander and will wait // until other items are drawn. - if (Dirs->Count + Files->Count == 0) // we ensure that the text about an empty panel is drawn + if (Dirs->Count + Files->Count == 0) // ensure the empty-panel text is drawn InvalidateRect(ListBox->HWindow, &ListBox->FilesRect, FALSE); else { @@ -2079,7 +2079,7 @@ void CFilesWindow::OnKillFocus(HWND hwndGetFocus) // change: instead of immediate redrawing, we only invalidate the area; // the focus will not be so aggressive when switching to Salamander and will wait // until other items are drawn. - if (Dirs->Count + Files->Count == 0) // we ensure that the text about an empty panel is drawn + if (Dirs->Count + Files->Count == 0) // ensure the empty panel text is redrawn InvalidateRect(ListBox->HWindow, &ListBox->FilesRect, FALSE); else { @@ -2113,7 +2113,7 @@ void ReleaseListingBody(CPanelType oldPanelType, CSalamanderDirectory*& oldArchi } if (oldPluginData.NotEmpty()) { - // we release plug-in data for individual files and directories + // we release plugin data for individual files and directories BOOL releaseFiles = oldPluginData.CallReleaseForFiles(); BOOL releaseDirs = oldPluginData.CallReleaseForDirs(); if (releaseFiles || releaseDirs) @@ -2186,7 +2186,7 @@ BOOL AreTheSameDirs(DWORD validFileData, CPluginDataInterfaceEncapsulation* plug SYSTEMTIME st2; BOOL validDate2, validTime2; GetFileDateAndTimeFromPanel(validFileData, pluginData2, f2, TRUE, &st2, &validDate2, &validTime2); - if (validDate1 == validDate2 && validTime1 == validTime2 && // The same parts of the structures must be valid. + if (validDate1 == validDate2 && validTime1 == validTime2 && // The same parts of both structures must be valid. (!validDate1 || st1.wYear == st2.wYear && st1.wMonth == st2.wMonth && @@ -2272,14 +2272,14 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa BOOL focusFirstNewItem = FocusFirstNewItem; // the first ReadDirectory resets it, so we make a backup BOOL cutToClipChanged = CutToClipChanged; // the first ReadDirectory resets it, so we make a backup - // we'll save the top-index and xoffset so that there won't be unnecessary "jumps" in the panel content + // save the top index and xoffset to avoid unnecessary "jumps" in the panel contents int topIndex = ListBox->GetTopIndex(); int xOffset = ListBox->GetXOffset(); // we'll remember if the old listing is an FS with custom icons (pitFromPlugin) BOOL pluginFSIconsFromPlugin = Is(ptPluginFS) && GetPluginIconsType() == pitFromPlugin; - // we'll save the focus item data - we'll look for it later (and focus it) + // save the focused item's data; we will look for it later (and focus it) BOOL ensureFocusIndexVisible = FALSE; BOOL wholeItemVisible = FALSE; // partial item visibility is enough for us int focusIndex = GetCaretIndex(); @@ -2302,7 +2302,7 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa CIconCache* oldIconCache = NULL; if (UseSystemIcons || UseThumbnails) SleepIconCacheThread(); // we'll stop the icon-reader (IconCache/Files/Dirs might change) - if (!TemporarilySimpleIcons && // if we shouldn't use the IconCache, we won't transfer anything from it to the new cache (e.g. when switching views to/from Thumbnails) + if (!TemporarilySimpleIcons && // if we should not use IconCache, we will not transfer anything from it to the new cache (e.g. when switching to or from Thumbnails view) (UseSystemIcons || UseThumbnails)) { oldIconCache = IconCache; @@ -2484,14 +2484,14 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa EndStopRefresh(); if (setWait) SetCursor(oldCur); - return; // exit without performing a refresh (error exit) + return; // return without refreshing (error exit) } int oldSelectedCount = SelectedCount; BOOL clearWMUpdatePanel = FALSE; if (!OnlyDetachFSListing) { - // we secure the listbox against errors arising from a request to redraw (we have just cut the data) + // protect the list box against errors caused by redraw requests (we have just cut off its data) ListBox->SetItemsCount(0, 0, 0, TRUE); // TRUE - we disable setting the scrollbar SelectedCount = 0; @@ -2506,18 +2506,18 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa BOOL oldCanAddToDirHistory = MainWindow->CanAddToDirHistory; MainWindow->CanAddToDirHistory = FALSE; - // a real mess: we have to postpone the start of reading icons in the icon-reader (this is started inside ChangePathToDisk, etc.), - // so that we have time to stop reading icons a few lines below (partly so we can take over old versions of icons+thumbnails - // and partly so that we can completely skip reading icons (icons loaded in the previous round will be used) in case - // 'probablyUselessRefresh' is TRUE and we don't recognize any changes in the directory); another place where this mess - // is used is when 'isInactiveRefresh' is TRUE, InactWinOptimizedReading is set to TRUE; a cleaner solution - // would be to not start reading icons at all in this case (not execute WakeupIconCacheThread()), but that seems quite - // non-trivial, so we are handling it like this via Sleep in the icon-reader + // Temporary workaround: postpone the start of icon loading in the icon reader (started inside ChangePathToDisk, etc.) + // so it can be stopped a few lines below. This lets us reuse previous icon and thumbnail versions, + // and also skip icon loading entirely (reusing icons loaded in the previous pass) when + // 'probablyUselessRefresh' is TRUE and no directory changes are detected; the same workaround + // is also used when 'isInactiveRefresh' is TRUE, by setting InactWinOptimizedReading to TRUE. A cleaner solution + // would be to avoid starting icon loading at all in this case (do not call WakeupIconCacheThread()), but that appears + // to be nontrivial, so this is handled via Sleep in the icon reader // - // ATTENTION: before leaving this function, we must put zero back into WaitBeforeReadingIcons !!! + // WARNING: before leaving this function, WaitBeforeReadingIcons must be reset to zero. WaitBeforeReadingIcons = 30; - // refresh of the path (change to the same one with forceUpdate TRUE) + // refresh the path (switching to the same path with forceUpdate TRUE) BOOL noChange; BOOL result; char buf1[MAX_PATH]; @@ -2544,8 +2544,8 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa oldPluginData.GetVersion(), oldPluginData.GetPluginInterface(), oldPluginData.GetBuiltForVersion()); SetValidFileData(GetArchiveDir()->GetValidData()); - // We'll keep the new IconCache so we don't lose the old one with loaded icons - // We'll keep Files and Dirs new so that synchronization can be performed (select and cut-to-clip) + // Keep the new IconCache so we do not lose the old one with loaded icons + // Keep the new Files and Dirs so synchronization can be performed (selection and cut-to-clipboard) CommonRefresh(HWindow, -1, NULL, FALSE, TRUE, TRUE); // without listbox refresh noChange = FALSE; // change in Files+Dirs @@ -2564,7 +2564,7 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa result = ChangePathToPluginFS(GetPluginFS()->GetPluginFSName(), buf1, -1, NULL, TRUE, 1 /*refresh*/, &noChange, FALSE, NULL, TRUE); } - else // should not happen if the plug-in is written intelligently + else // should not happen if the plugin is written intelligently { ChangeToFixedDrive(HWindow, &noChange, FALSE); // we can safely end quick-search, it would end anyway result = FALSE; @@ -2591,9 +2591,9 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa PeekMessage(&msg2, HWindow, WM_USER_UPDATEPANEL, WM_USER_UPDATEPANEL, PM_REMOVE); } - if (!result || noChange) // refresh failed or is useless + if (!result || noChange) // refresh failed or is unnecessary { - if (noChange) // we'll return the old listing (no replacement was created), we perform cleanup (sort-dir, etc.) + if (noChange) // restore the old listing (no replacement was created), perform cleanup (sort-dir, etc.) { if (!OnlyDetachFSListing) { @@ -2631,7 +2631,7 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa if (oldIconCache != NULL) { delete oldIconCache; - oldIconCache = NULL; // so we don't perform a useless wake-up of the icon-reader + oldIconCache = NULL; // to avoid an unnecessary wake-up of the icon reader } topIndex = -1; // different listing -> ignore @@ -2680,7 +2680,7 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa iconReaderIsSleeping = TRUE; BOOL newPluginFSIconsFromPlugin = Is(ptPluginFS) && GetPluginIconsType() == pitFromPlugin; if (pluginFSIconsFromPlugin && newPluginFSIconsFromPlugin) - { // both the old and new listing are FS with custom icons -> transferring old icons makes sense + we must pass 'dataIface' + { // both the old and new listings are FS listings with custom icons, so transferring the old icons makes sense and we must pass 'dataIface' IconCache->GetIconsAndThumbsFrom(oldIconCache, &PluginData); // we load the old versions of icons and thumbnails into it } else @@ -2727,7 +2727,7 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa int oldCount = oldDirs->Count + oldFiles->Count; int count = Dirs->Count + Files->Count; if (count != oldCount + 1 && focusFirstNewItem) - focusFirstNewItem = FALSE; // one item wasn't added + focusFirstNewItem = FALSE; // no single item was added // if 'caseSensitive' is TRUE, we require exact (case sensitive) matching of name // during the following flag synchronization @@ -2748,7 +2748,7 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa if (oldData->NameLen == 2 && oldData->Name[0] == '.' && oldData->Name[1] == '.') j++; } - for (; j < oldDirs->Count; j++) // first directories + for (; j < oldDirs->Count; j++) // directories first { CFileData* oldData = &oldDirs->At(j); if (focusFirstNewItem || oldData->Selected || oldData->SizeValid || oldData->CutToClip || @@ -2774,7 +2774,7 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa if (!LessNameExt(*oldData, *newData2, FALSE)) // old == new (exact) - we prefer exact match over case insensitive match { exactMatch = TRUE; - if (ii > i) // we skipped at least one item (it was smaller than the searched old item) + if (ii > i) // we skipped at least one item (it was smaller than the old item being searched for) { if (focusFirstNewItem) // found a new item { @@ -2786,7 +2786,7 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa newData = newData2; } } - break; // in any case, we end the search for exact match + break; // in any case, we stop searching for an exact match } ii++; } @@ -2821,7 +2821,7 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa break; // end of searching for selected items } } - if (focusFirstNewItem && i == Dirs->Count - 1) // found a new item + if (focusFirstNewItem && i == Dirs->Count - 1) // new item found { strcpy(NextFocusName, Dirs->At(i).Name); firstNewItemIsDir = 1 /* is directory */; @@ -2829,7 +2829,7 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa } i = 0; - for (j = 0; j < oldFiles->Count; j++) // after directories also files + for (j = 0; j < oldFiles->Count; j++) // after the directories, also files { CFileData* oldData = &oldFiles->At(j); if (focusFirstNewItem || oldData->Selected || oldData->CutToClip || @@ -2855,11 +2855,11 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa if (!LessNameExt(*oldData, *newData2, FALSE)) // old == new (exact) - we prefer exact match over case insensitive match { exactMatch = TRUE; - if (ii > i) // we skipped at least one item (it was smaller than the searched old item) + if (ii > i) // we skipped at least one item (it was smaller than the old item being searched for) { if (focusFirstNewItem) // found a new item { - if (!Is(ptDisk) || (newData->Attr & FILE_ATTRIBUTE_TEMPORARY) == 0) // on disk, we ignore tmp files (they disappear immediately), see https://forum.altap.cz/viewtopic.php?t=2496 + if (!Is(ptDisk) || (newData->Attr & FILE_ATTRIBUTE_TEMPORARY) == 0) // on disk, we ignore temporary files (they disappear immediately), see https://forum.altap.cz/viewtopic.php?t=2496 { strcpy(NextFocusName, newData->Name); firstNewItemIsDir = 0 /* is file */; @@ -2891,7 +2891,7 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa { if (focusFirstNewItem) // found a new item { - if (!Is(ptDisk) || (newData->Attr & FILE_ATTRIBUTE_TEMPORARY) == 0) // on disk, we ignore tmp files (they disappear immediately), see https://forum.altap.cz/viewtopic.php?t=2496 + if (!Is(ptDisk) || (newData->Attr & FILE_ATTRIBUTE_TEMPORARY) == 0) // on disk, we ignore temporary files (they disappear again immediately), see https://forum.altap.cz/viewtopic.php?t=2496 { strcpy(NextFocusName, newData->Name); firstNewItemIsDir = 0 /* is file */; @@ -2907,7 +2907,7 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa } if (focusFirstNewItem && i == Files->Count - 1) // found a new item { - if (!Is(ptDisk) || (Files->At(i).Attr & FILE_ATTRIBUTE_TEMPORARY) == 0) // on disk, we ignore tmp files (they disappear immediately), see https://forum.altap.cz/viewtopic.php?t=2496 + if (!Is(ptDisk) || (Files->At(i).Attr & FILE_ATTRIBUTE_TEMPORARY) == 0) // on disk, we ignore temporary files (they disappear again immediately), see https://forum.altap.cz/viewtopic.php?t=2496 { strcpy(NextFocusName, Files->At(i).Name); firstNewItemIsDir = 0 /* is file */; @@ -2929,14 +2929,14 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa if (iconCacheBackuped && (UseSystemIcons || UseThumbnails)) // wake-up after SortDirectory() { - if (!oldIconCacheValid || // if the icon reading didn't finish + if (!oldIconCacheValid || // if icon reading did not finish oldInactWinOptimizedReading || // if only icons from the visible part of the panel were read !transferIconsAndThumbnailsAsNew) // if the listing has changed { WakeupIconCacheThread(); // we'll let it read all icons again (we'll show old versions in the meantime) } else - IconCacheValid = TRUE; // we won't start the icon-reader, the icons/thumbnails/overlays are loaded, nothing to do (avoids an infinite refresh cycle in case of a network drive, where at least one icon can't be read - if we start the icon-reader, it will try to read it, which will trigger a refresh and we'll cycle) + IconCacheValid = TRUE; // do not start the icon reader; the icons/thumbnails/overlays are already loaded, so there is nothing to do (this prevents an infinite refresh cycle on a network drive when at least one icon cannot be loaded - starting the icon reader would make it try again, trigger another refresh, and loop) } // we find the index of the focus item @@ -2961,14 +2961,14 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa CFileData* f = (i < Dirs->Count) ? &Dirs->At(i) : &Files->At(i - Dirs->Count); if (f->NameLen == (unsigned)l && StrICmpEx(f->Name, f->NameLen, NextFocusName, l) == 0 && - (firstNewItemIsDir == -1 /* we don't know what it is */ || + (firstNewItemIsDir == -1 /* type unknown */ || firstNewItemIsDir == 0 /* is file */ && i >= Dirs->Count || firstNewItemIsDir == 1 /* is directory */ && i < Dirs->Count)) { foundFocus = TRUE; ensureFocusIndexVisible = TRUE; wholeItemVisible = TRUE; // we want complete visibility of the new item - if (StrCmpEx(f->Name, f->NameLen, NextFocusName, l) == 0) // found: exact + if (StrCmpEx(f->Name, f->NameLen, NextFocusName, l) == 0) // found: exact match { focusIndex = i; break; @@ -2978,11 +2978,11 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa } } if (i == count && found != -1) - focusIndex = found; // found: ignore-case + focusIndex = found; // found: case-insensitive match NextFocusName[0] = 0; } - // first, we search for the old focus in the new listing (according to the case-sensitivity of the current listing) + // first, we look up the old focus in the new listing according to the current listing's case sensitivity if (!foundFocus && focusData.Name != NULL) { if (focusIsDir) @@ -3049,7 +3049,7 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa break; } - if (focusData.Name != NULL) // we should search for the focus + if (focusData.Name != NULL) // look for the focused item { if (focusIsDir) { @@ -3060,7 +3060,7 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa for (; i < count; i++) { CFileData* d2 = &Dirs->At(i); - if (!lessDirs(*d2, focusData, ReverseSort)) // due to sorting, it will be TRUE only on the first larger item + if (!lessDirs(*d2, focusData, ReverseSort)) // due to sorting, this becomes TRUE at the first item that is not smaller { focusIndex = i; break; @@ -3073,7 +3073,7 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa for (i = 0; i < count; i++) { CFileData* d2 = &Files->At(i); - if (!lessFiles(*d2, focusData, ReverseSort)) // due to sorting, it will be TRUE only on the first larger item + if (!lessFiles(*d2, focusData, ReverseSort)) // due to sorting, this becomes TRUE at the first larger item { focusIndex = Dirs->Count + i; break; @@ -3087,7 +3087,7 @@ void CFilesWindow::RefreshDirectory(BOOL probablyUselessRefresh, BOOL forceReloa focusIndex = max(0, count - 1); } - // release the backup of the old listing + // release the saved old listing ReleaseListingBody(oldPanelType, oldArchiveDir, oldPluginFSDir, oldPluginData, oldFiles, oldDirs, TRUE); @@ -3189,8 +3189,8 @@ void CFilesWindow::SetQuickSearchCaretPos() { x = r.left + 3 + IconSizes[ICONSIZE_16] + s.cx + offset; y = r.top + 2; - // if the column width is manually limited, we ensure that - // the caret doesn't go beyond the limit; otherwise, it would spill into other columns + // if the Name column width is manually limited, ensure that + // the caret stops at the maximum width; otherwise it would extend into the next columns if (GetViewMode() == vmDetailed && !ext && x >= (int)Columns[0].Width) x = Columns[0].Width - 3; x -= ListBox->XOffset; diff --git a/src/fileswn1.cpp b/src/fileswn1.cpp index 1b504d80c..d4da1ba08 100644 --- a/src/fileswn1.cpp +++ b/src/fileswn1.cpp @@ -124,7 +124,7 @@ BOOL CFilesWindowAncestor::IsPathFromActiveFS(const char* fsName, char* fsUserPa fsNameIndex = -1; if (Is(ptPluginFS) && PluginFS.NotEmpty()) { - if (Plugins.AreFSNamesFromSamePlugin(PluginFS.GetPluginFSName(), fsName, fsNameIndex)) // we compare whether the file systems are from the same plug-in + if (Plugins.AreFSNamesFromSamePlugin(PluginFS.GetPluginFSName(), fsName, fsNameIndex)) // Check whether the file systems are from the same plugin { if (convertPathToInternal) { @@ -291,7 +291,7 @@ void CFilesWindowAncestor::SetPath(const char* path) ((CFilesWindow*)this)->SetAutomaticRefresh(FALSE, TRUE); } } - else // ptPluginFS - do not perform any refreshes; the plug-in manages them itself + else // ptPluginFS - do not perform any refreshes; the plugin manages them itself { ((CFilesWindow*)this)->SetAutomaticRefresh(TRUE, TRUE); } @@ -525,7 +525,7 @@ unsigned IconThreadThreadFBody(void* parameter) else TRACE_E("Unexpected situation."); } - // before starting set "ReadingDone" of all icon-cache items and "IconOverlayDone" of all panel items to FALSE + // Before starting, set "ReadingDone" to FALSE for all icon-cache items and "IconOverlayDone" to FALSE for all items in the panel int x; if (!repeatedRound) for (x = 0; x < window->IconCache->Count; x++) @@ -543,12 +543,12 @@ unsigned IconThreadThreadFBody(void* parameter) int selectMode = 1; // 1 = sequential traversal (VisibleItemsArray.IsArrValid() == FALSE), - // 2 = traversal according to VisibleItemsArray, - // 3 = traversal according to VisibleItemsArraySurround, + // 2 = traversal using VisibleItemsArray, + // 3 = traversal using VisibleItemsArraySurround, // 4 = sequential traversal (VisibleItemsArray.IsArrValid() == TRUE) BOOL canReadIconOverlays = firstRound && window->Is(ptDisk) && iconReadersIconOverlayIds != NULL; - BOOL readIconOverlaysNow = FALSE; // TRUE = reading overlays now, FALSE = reading icons + thumbnails + BOOL readIconOverlaysNow = FALSE; // TRUE = reading overlays now, FALSE = reading icons and thumbnails // TRACE_I("wanted=" << wanted << ", selectMode=" << selectMode); @@ -559,7 +559,7 @@ unsigned IconThreadThreadFBody(void* parameter) while (1) { BOOL callWaitForObjects = TRUE; // optimization only - while searching for an item (takes almost no time) WaitForMultipleObjects is not called - if (i < (readIconOverlaysNow ? window->Files->Count + window->Dirs->Count : window->IconCache->Count)) // loading an icon from a file/directory or retrieving icon overlay for a file/directory + if (i < (readIconOverlaysNow ? window->Files->Count + window->Dirs->Count : window->IconCache->Count)) // load an icon from a file/directory or retrieve the icon overlay for a file/directory { CIconData* iconData = readIconOverlaysNow ? NULL : &window->IconCache->At(i); @@ -716,9 +716,9 @@ unsigned IconThreadThreadFBody(void* parameter) iconData->GetFlag() == wanted) { iconData->SetReadingDone(1); // mark that we have already worked with this icon so we do not try again during this cycle - if (wanted == 0 || wanted == 2) // loading icons directly from a file or from a plug-in + if (wanted == 0 || wanted == 2) // loading icons directly from a file or from a plugin { - if (!pluginFSIconsFromPlugin) // icon on disk + if (!pluginFSIconsFromPlugin) // icon from disk { if (strlen(iconData->NameAndData) + (name - path) < MAX_PATH) { @@ -761,7 +761,7 @@ unsigned IconThreadThreadFBody(void* parameter) TRACE_I("Too long filename to get icon from: " << path << iconData->NameAndData); } } - else // icon in a plug-in FS - reading cannot be interrupted (risk of PluginData being destroyed) + else // icon in a plugin FS - loading cannot be interrupted (risk of PluginData being destroyed) { const CFileData* f = iconData->GetFSFileData(); if (f != NULL) @@ -783,12 +783,12 @@ unsigned IconThreadThreadFBody(void* parameter) } else { - if (wanted == 3) // loading icons from the icon-location + if (wanted == 3) // loading icons from icon-location { shi.hIcon = NULL; char* nameAndData = iconData->NameAndData; int size = (int)strlen(nameAndData) + 4; - size -= (size & 0x3); // size % 4 (alignment to four bytes) + size -= (size & 0x3); // size % 4 (4-byte alignment) char* s = nameAndData + size; // skip the alignment zeros BOOL doExtractIcons = FALSE; BOOL doLoadImage = FALSE; @@ -870,14 +870,14 @@ unsigned IconThreadThreadFBody(void* parameter) HANDLES(EnterCriticalSection(&window->ICSleepSection)); } - else // wanted == 4 or 6; loading thumbnails from a plug-in ("thumbnail loader") + else // wanted == 4 or 6; loading thumbnails from a plugin ("thumbnail loader") { shi.hIcon = NULL; // precaution against incorrect icon deallocation (none is created here) char* s = iconData->NameAndData; int len = (int)strlen(s); int size = len + 4; - size -= (size & 0x3); // size % 4 (alignment to four bytes) + size -= (size & 0x3); // size % 4 (4-byte alignment) if (strlen(s) + (name - path) < MAX_PATH) { strcpy(name, s); @@ -894,9 +894,9 @@ unsigned IconThreadThreadFBody(void* parameter) { thumbnailFlag = wanted == 4 /* first thumbnail loading round */ ? (thumbMaker.IsOnlyPreview() ? 6 /* low-quality/smaller */ : 5 /* quality */) : 5 /* in the second round all obtained thumbnails are quality */; thumbMaker.HandleIncompleteImages(); - break; // the thumbnail may be loaded; do not try another plug-in + break; // the thumbnail may be loaded; do not try another plugin } - loader++; // try the next plug-in in line, it might load the thumbnail + loader++; // try the next plugin in line, it might load the thumbnail } if (*loader == NULL) thumbMaker.Clear(); // failed thumbnail -> clean it up @@ -915,7 +915,7 @@ unsigned IconThreadThreadFBody(void* parameter) { thumbMaker.Clear(); // the thumbnail will no longer be needed - // if this is not an icon from a plug-in that forbids icon destruction, destroy it + // if this is not an icon from a plugin that forbids icon destruction, destroy it if (shi.hIcon != NULL && (!pluginFSIconsFromPlugin || destroyPluginIcon)) { ::NOHANDLES(DestroyIcon(shi.hIcon)); @@ -939,9 +939,9 @@ unsigned IconThreadThreadFBody(void* parameter) HANDLES(LeaveCriticalSection(&window->ICSectionUsingIcon)); - // find the index of the item for which we loaded the icon + // find the index of the item whose icon we loaded - if (pluginFSIconsFromPlugin) // pitFromPlugin: let the plug-in compare items itself (must compare with no duplicates) + if (pluginFSIconsFromPlugin) // pitFromPlugin: let the plugin compare the items itself (the comparison must not treat any two items in the listing as equal) { const CFileData* file = iconData->GetFSFileData(); if (file != NULL) @@ -973,7 +973,7 @@ unsigned IconThreadThreadFBody(void* parameter) } } } - else // duplicate names are not a problem (e.g., archives where identical names cannot have different icons) + else // duplicate names are not a problem (or are not an obstacle, as for example in an archive, where { char* name2 = iconData->NameAndData; CFilesArray* arr = window->Dirs; @@ -1024,7 +1024,7 @@ unsigned IconThreadThreadFBody(void* parameter) if (thumbMaker.RenderToThumbnailData(thumbnailData)) { iconData->SetFlag(thumbnailFlag); // already loaded - if (thumbnailFlag == 6 /* low-quality/smaller thumbnail in the first loading round */) + if (thumbnailFlag == 6 /* lower-quality/smaller thumbnail in the first thumbnail-loading pass */) iconData->SetReadingDone(0); // another round will follow, so mark as not "done" thumbnailCreated = TRUE; } @@ -1032,7 +1032,7 @@ unsigned IconThreadThreadFBody(void* parameter) if (thumbnailCreated) { - // find the index of the file (directories have no thumbnails) for which we loaded the thumbnail + // find the index of the file (directories have no thumbnails) whose thumbnail we loaded char* name2 = iconData->NameAndData; int z; for (z = 0; z < window->Files->Count; z++) @@ -1087,13 +1087,13 @@ unsigned IconThreadThreadFBody(void* parameter) canReadIconOverlays = FALSE; // loading order: new icons, new thumbnails, old icons, old thumbnails - BOOL done = FALSE; // TRUE == break, everything is loaded + BOOL done = FALSE; // TRUE = stop, everything has already been loaded switch (wanted) { case 0: // new icons have already been loaded { - // if thumbnails should be read and this is the first round (plug-ins do not work - // randomly like the system, so if they fail the first time they will never load), read + // if thumbnails should be loaded and this is the first loading pass (plugins do not behave + // nondeterministically like the system, so if they do not load the first time, they will never load), load // new thumbnails (wanted == 4) if (readThumbnails && firstRound) wanted = 4; @@ -1187,7 +1187,7 @@ unsigned IconThreadThreadFBody(void* parameter) } } } - if (wait == WAIT_TIMEOUT) // reason to retry reading icons (visible area change or usermenu icons finished) + if (wait == WAIT_TIMEOUT) // reason to retry reading icons (visible area changed or user-menu icon reading finished) { if (!UserMenuIconBkgndReader.IsReadingIcons()) // if usermenu icons are done, read icons outside the visible area { @@ -1212,7 +1212,7 @@ unsigned IconThreadThreadFBody(void* parameter) if (window->Is(ptDisk) && failed && firstRound) { // try again (not all icons were loaded) firstRound = FALSE; // only one extra round - waitBeforeFirstReadIcon = TRUE; // prevent immediate rereading (low chance of success) + waitBeforeFirstReadIcon = TRUE; // avoid reading the icon again immediately (low chance of success) // TRACE_I("Going to second round of reading (some icons have not been read in the first round)."); goto SECOND_ROUND; // postRefresh = TRUE; @@ -1291,7 +1291,7 @@ unsigned IconThreadThreadFEH(void* param) { TRACE_I("Thread IconReader: calling ExitProcess(1)."); // ExitProcess(1); - TerminateProcess(GetCurrentProcess(), 1); // harder exit (this call still performs some operations) + TerminateProcess(GetCurrentProcess(), 1); // harder exit (the referent of "this one" is unclear here) return 1; } #endif // CALLSTK_DISABLE @@ -1526,7 +1526,7 @@ void CFilesWindow::WakeupIconCacheThread() CALL_STACK_MESSAGE_NONE ICStopWork = FALSE; // so that the work is not interrupted right from the start SetEvent(ICEventWork); // switch to work mode without waiting for a response - MSG msg; // remove any WM_USER_ICONREADING_END that would set IconCacheValid = TRUE + MSG msg; // remove any pending WM_USER_ICONREADING_END that would set IconCacheValid = TRUE while (PeekMessage(&msg, HWindow, WM_USER_ICONREADING_END, WM_USER_ICONREADING_END, PM_REMOVE)) ; } @@ -1565,7 +1565,7 @@ BOOL CFilesWindow::CanUnloadPlugin(HWND parent, CPluginInterfaceAbstract* plugin HANDLES(EnterCriticalSection(&TimeCounterSection)); int t1 = MyTimeCounter++; HANDLES(LeaveCriticalSection(&TimeCounterSection)); - PostMessage(HWindow, WM_USER_REFRESH_DIR, 0, t1); // ensure the icon cache is refilled (ideally after the plug-in unload/remove) + PostMessage(HWindow, WM_USER_REFRESH_DIR, 0, t1); // ensure the icon cache is refilled (ideally after the plugin unload/remove) } } } @@ -1587,27 +1587,27 @@ BOOL CFilesWindow::CanUnloadPlugin(HWND parent, CPluginInterfaceAbstract* plugin else { if (Is(ptZIPArchive)) - { // an archive may not use PluginData, therefore we must also test archive associations - // this part matters only when shutting Salamander down—otherwise the plug-in - // could unload while the archiver is still in use (each archiver function loads the plug-in) - // NOTE: icon overlays from the plug-in are an exception; after unload they would stop drawing - // (the plug-in's overlay table is released during unload) + { // an archive may not use PluginData, so we must also check archive associations + // this part matters only when Salamander is shutting down; otherwise the plugin + // could be unloaded while the archiver is still in use (each archiver function loads the plugin) + // NOTE: icon overlays from the plugin are an exception; after the plugin is unloaded, they stop being drawn + // (the plugin's icon-overlay array is released during unload) int format = PackerFormatConfig.PackIsArchive(GetZIPArchive()); if (format != 0) // found a supported archive { format--; CPluginData* data; int index = PackerFormatConfig.GetUnpackerIndex(format); - if (index < 0) // view: is this internal processing (plug-in)? + if (index < 0) // is this handled internally by a plugin? { data = Plugins.Get(-index - 1); if (data != NULL && data->GetPluginInterface()->GetInterface() == plugin) used = TRUE; } - if (PackerFormatConfig.GetUsePacker(format)) // has an editor? + if (PackerFormatConfig.GetUsePacker(format)) // supports editing? { index = PackerFormatConfig.GetPackerIndex(format); - if (index < 0) // is this internal processing (plug-in)? + if (index < 0) // handled by a plugin? { data = Plugins.Get(-index - 1); if (data != NULL && data->GetPluginInterface()->GetInterface() == plugin) @@ -1620,7 +1620,7 @@ BOOL CFilesWindow::CanUnloadPlugin(HWND parent, CPluginInterfaceAbstract* plugin } if (used) { - if (Is(ptZIPArchive) || Is(ptPluginFS)) // archive -> just leave it; plug-in FS -> return to the last disk path + if (Is(ptZIPArchive) || Is(ptPluginFS)) // archive -> just leave it; plugin FS -> return to the last disk path { char path[MAX_PATH]; strcpy(path, GetPath()); @@ -1878,7 +1878,7 @@ void CFilesWindow::StoreGlobalSelection() int totalCount = Dirs->Count + Files->Count; if (clipboard) { - // we should put the list on the clipboard + // put the list on the clipboard // compute the required buffer size (name1CRLFname2CRLF...nameNCRLF) DWORD size = 0; @@ -2140,11 +2140,11 @@ void CFilesWindow::SetAutomaticRefresh(BOOL value, BOOL force) if (force || AutomaticRefresh != value) { AutomaticRefresh = value; - /* // "throwing away" the refresh mark from the directory line - // it crashed here; a destroyed object was called - if (DirectoryLine != NULL) - DirectoryLine->SetAutomatic(AutomaticRefresh); -*/ + /* // removing the refresh flag from the directory line + // it crashed here; a method was called on a destroyed object + if (DirectoryLine != NULL) + DirectoryLine->SetAutomatic(AutomaticRefresh); + */ } } @@ -2244,9 +2244,9 @@ void CFilesWindow::OpenActiveFolder() #ifndef _WIN64 // replace "C:\\Windows\\sysnative\\*" with "C:\\Windows\\system32\\*" on 64-bit systems - // the Explorer process knows nothing about "sysnative", so let's not bother users with it, + // the 64-bit Explorer process knows nothing about "sysnative", so minimize user disruption, // also replace "C:\\Windows\\system32\\*" with "C:\\Windows\\SysWOW64\\*" - // (except for a group of directories excluded from the redirector that thus point back to System32) + // (except for a group of directories excluded from the redirector that thus point back to System32) char dirName[MAX_PATH]; dirName[0] = 0; if (Windows64Bit && WindowsDirectory[0] != 0) diff --git a/src/fileswn2.cpp b/src/fileswn2.cpp index 823328a09..133f775cb 100644 --- a/src/fileswn2.cpp +++ b/src/fileswn2.cpp @@ -100,7 +100,7 @@ void CFilesWindow::Execute(int index) BOOL linkIsFile = FALSE; // TRUE -> shortcut to file -> test archive BOOL linkIsNet = FALSE; // TRUE -> shortcut to network -> ChangePathToPluginFS DWORD err = ERROR_SUCCESS; - if (StrICmp(file->Ext, "lnk") == 0) // is it not a directory shortcut? + if (StrICmp(file->Ext, "lnk") == 0) // is this a directory shortcut? { strcpy(fullName, GetPath()); if (!SalPathAppend(fullName, fileName, MAX_PATH)) @@ -129,7 +129,7 @@ void CFilesWindow::Execute(int index) if (link->GetPath(fullName, MAX_PATH, &data, SLGP_UNCPRIORITY) == NOERROR) { // the obtained path will be used for accessibility test, after Resolve it may change err = CheckPath(FALSE, fullName); // fullName is a full path (shortcuts support no other) - if (err != ERROR_USER_TERMINATED) // if user didn't press ESC, ignore the error + if (err != ERROR_USER_TERMINATED) // If the user did not press Esc, ignore the error. { err = ERROR_SUCCESS; // Resolve may change the path, then we check again } @@ -202,7 +202,7 @@ void CFilesWindow::Execute(int index) if (err != ERROR_SUCCESS) { EndStopRefresh(); - return; // path error or aborted + return; // path error or interruption } if (linkIsDir || linkIsNet) // link points to network or directory, path is OK, we switch to it { @@ -236,7 +236,7 @@ void CFilesWindow::Execute(int index) } } BOOL noChange; - if (ChangePathToArchive(fullName, "", -1, NULL, FALSE, &noChange)) // entering the archive successfully + if (ChangePathToArchive(fullName, "", -1, NULL, FALSE, &noChange)) // successfully entered the archive { if (linkIsFile) TopIndexMem.Clear(); // long jump @@ -369,7 +369,7 @@ void CFilesWindow::Execute(int index) } else // failure { - if (!IsTheSamePath(path, GetPath())) // we're not on the original path -> long jump + if (!IsTheSamePath(path, GetPath())) // no longer on the original path -> long jump { // the condition "!noChange" is not enough - it signals "path change or reload - access-denied-dir" TopIndexMem.Clear(); } @@ -430,7 +430,7 @@ void CFilesWindow::Execute(int index) } } } - else // we're shortening path inside archive + else // shorten the path inside the archive { // we split zip-path into new zip-path and prev-dir strcpy(path, GetZIPPath()); @@ -589,7 +589,7 @@ void CFilesWindow::ChangeSortType(CSortType newType, BOOL reverse, BOOL force) } else { - i = Dirs->Count; // we're searching for a file + i = Dirs->Count; // searching for a file count = Dirs->Count + Files->Count; // there was a bug here; count wasn't initialized } @@ -610,7 +610,7 @@ void CFilesWindow::ChangeSortType(CSortType newType, BOOL reverse, BOOL force) if (i < Dirs->Count) { CFileData* d2 = &Dirs->At(i); - if (!lessDirs(*d2, d1, ReverseSort)) // due to sorting this becomes TRUE only at the searched item + if (!lessDirs(*d2, d1, ReverseSort)) // due to sorting, this becomes TRUE at the sought item { if (!lessDirs(d1, *d2, ReverseSort)) focusIndex = i; // condition unnecessary; should be "always true" @@ -623,7 +623,7 @@ void CFilesWindow::ChangeSortType(CSortType newType, BOOL reverse, BOOL force) if (!lessFiles(*d2, d1, ReverseSort)) // due to sorting this becomes TRUE only at the searched item { if (!lessFiles(d1, *d2, ReverseSort)) - focusIndex = i; // condition unnecessary; should be "always true" + focusIndex = i; // unnecessary condition; should always be TRUE break; } } @@ -665,7 +665,7 @@ BOOL CFilesWindow::ChangeToRescuePathOrFixedDrive(HWND parent, BOOL* noChange, B { if (failReason != NULL) *failReason = failReasonInt; - return FALSE; // the issue "cannot close the current path in the panel" won't be solved by switching to a fixed drive (we would just ask about disconnect twice) + return FALSE; // the issue "cannot close the current path in the panel" will not be resolved by switching to a fixed drive (it would only prompt for disconnect twice in a row) } noChangeUsed = TRUE; } @@ -829,8 +829,8 @@ void CFilesWindow::DisconnectNet() if (releaseRight) MainWindow->RightPanel->HandsOff(TRUE); - // Under Windows XP the WNetDisconnectDialog is modeless. Users lost it behind Salamander - // and wondered why accelerators didn't work. When closing Salamander it crashed here + // Under Windows XP, WNetDisconnectDialog is modeless. It could end up behind Salamander, + // and users then wondered why accelerators did not work. When Salamander was closing, it crashed in this method // because MainWindow was NULL; // WNetDisconnectDialog(HWindow, RESOURCETYPE_DISK); @@ -1030,7 +1030,7 @@ BOOL CFilesWindow::SelectViewTemplate(int templateIndex, BOOL canRefreshPath, CViewTemplate* newTemplate = &Parent->ViewTemplates.Items[templateIndex]; if (lstrlen(newTemplate->Name) == 0) { - // undefined view is not desired - we force the detailed view which always exists + // Do not allow an undefined view; force Detailed, which is guaranteed to exist templateIndex = 2; newTemplate = &Parent->ViewTemplates.Items[templateIndex]; } @@ -1066,7 +1066,7 @@ BOOL CFilesWindow::SelectViewTemplate(int templateIndex, BOOL canRefreshPath, ListBox->SetMode(newViewMode, headerLine); } - // we build new columns + // build new columns BuildColumnsTemplate(); CopyColumnsTemplateToColumns(); DeleteColumnsWithoutData(columnValidMask); @@ -1091,7 +1091,7 @@ BOOL CFilesWindow::SelectViewTemplate(int templateIndex, BOOL canRefreshPath, // until ReadDirectory we work with simple icons because the icon geometry changes TemporarilySimpleIcons = TRUE; - // let it compute item sizes and ensure the focused item is visible + // compute item sizes and ensure the focused item is visible RefreshListBox(0, -1, FocusedIndex, FALSE, FALSE); // perform a hard refresh @@ -1212,7 +1212,7 @@ BOOL CFilesWindow::PrepareCloseCurrentPath(HWND parent, BOOL canForce, BOOL canD BOOL someFilesChanged = FALSE; if (AssocUsed) { - // if the user didn't suppress it, we show info about closing an archive that contains edited files + // if the user did not suppress it, show information about closing an archive that contains edited files if (Configuration.CnfrmCloseArchive && !CriticalShutdown) { char title[100]; @@ -1237,10 +1237,10 @@ BOOL CFilesWindow::PrepareCloseCurrentPath(HWND parent, BOOL canForce, BOOL canD } // pack modified files again (only if it's not a critical shutdown) we prepare them for next use UnpackedAssocFiles.CheckAndPackAndClear(parent, &someFilesChanged); - // during critical shutdown we pretend updated files don't exist because there is no time to pack - // them back to the archive. We must not delete them so the user can manually repack them after restart, - // exception is when nothing was edited then everything may be deleted even during - // critical shutdown (it's fast and not confusing for the user with unnecessary questions) + // during critical shutdown, treat updated files as if they did not exist: there is no time to pack + // them back into the archive, but they must not be deleted, so the user still has a chance to pack them + // back into the archive manually after restart; the exception is when nothing was edited, in which case + // everything may be deleted even during critical shutdown (it is fast and minimizes unnecessary prompts) if (!someFilesChanged || !CriticalShutdown) { SetEvent(ExecuteAssocEvent); // start file cleanup @@ -1269,7 +1269,7 @@ BOOL CFilesWindow::PrepareCloseCurrentPath(HWND parent, BOOL canForce, BOOL canD BOOL userAsked = FALSE; CPluginData* plugin = NULL; int index = PackerFormatConfig.GetUnpackerIndex(format); - if (index < 0) // view: is it internal processing (plugin)? + if (index < 0) // note: is this internal processing (plugin)? { plugin = Plugins.Get(-index - 1); if (plugin != NULL) @@ -1292,7 +1292,7 @@ BOOL CFilesWindow::PrepareCloseCurrentPath(HWND parent, BOOL canForce, BOOL canD } } } - if (PackerFormatConfig.GetUsePacker(format)) // supports editing? + if (PackerFormatConfig.GetUsePacker(format)) // does it have an editor? { index = PackerFormatConfig.GetPackerIndex(format); if (index < 0) // is it internal processing (plugin)? @@ -1302,7 +1302,7 @@ BOOL CFilesWindow::PrepareCloseCurrentPath(HWND parent, BOOL canForce, BOOL canD plugin = Plugins.Get(-index - 1); if (plugin != NULL) { - if (!plugin->CanCloseArchive(this, GetZIPArchive(), userForce || CriticalShutdown)) // it refuses to close + if (!plugin->CanCloseArchive(this, GetZIPArchive(), userForce || CriticalShutdown)) // cannot be closed { canclose = FALSE; if (canForce && !userAsked) // we can ask the user whether to force it @@ -1328,7 +1328,7 @@ BOOL CFilesWindow::PrepareCloseCurrentPath(HWND parent, BOOL canForce, BOOL canD { if (Is(ptPluginFS)) { - if (!canForce && !CriticalShutdown) // we can't ask the user about forcing + if (!canForce && !CriticalShutdown) // we cannot ask the user whether to force it { detachFS = FALSE; // to ensure a known value in case the plugin doesn't modify it BOOL r = GetPluginFS()->TryCloseOrDetach(FALSE, canDetach, detachFS, tryCloseReason); @@ -1336,7 +1336,7 @@ BOOL CFilesWindow::PrepareCloseCurrentPath(HWND parent, BOOL canForce, BOOL canD detachFS = FALSE; // verification/correction of the output value return r; } - else // forcing is allowed -> we must close, detaching isn't permitted + else // force-closing is allowed -> we must close; detaching is not permitted { if (GetPluginFS()->TryCloseOrDetach(CriticalShutdown, FALSE, detachFS, tryCloseReason) || // try closing without forceClose==TRUE (except during critical shutdown) CriticalShutdown) @@ -1344,7 +1344,7 @@ BOOL CFilesWindow::PrepareCloseCurrentPath(HWND parent, BOOL canForce, BOOL canD detachFS = FALSE; return TRUE; // closed successfully } - else // ask the user whether to close it against the FS's will + else // ask the user whether to force-close it despite the FS { char path[2 * MAX_PATH]; GetGeneralPath(path, 2 * MAX_PATH); @@ -1500,7 +1500,7 @@ void CFilesWindow::CloseCurrentPath(HWND parent, BOOL cancel, BOOL detachFS, BOO sendDetachEvent = TRUE; // the call mustn't happen here because the FS isn't detached yet (it's still in the panel) } - if (!detachFS) // we're closing the FS; let it deallocate and display final messageboxes + if (!detachFS) // closing the FS; let it deallocate and display the final message boxes { GetPluginFS()->ReleaseObject(parent); } @@ -1519,7 +1519,7 @@ void CFilesWindow::CloseCurrentPath(HWND parent, BOOL cancel, BOOL detachFS, BOO SimplePluginIcons = NULL; } - if (!detachFS) // we're closing the FS + if (!detachFS) // closing the FS { CPluginInterfaceForFSEncapsulation plugin(GetPluginFS()->GetPluginInterfaceForFS()->GetInterface(), GetPluginFS()->GetPluginInterfaceForFS()->GetBuiltForVersion()); @@ -1551,7 +1551,7 @@ void CFilesWindow::RefreshPathHistoryData() CALL_STACK_MESSAGE1("CFilesWindow::RefreshPathHistoryData()"); int index = GetCaretIndex(); - if (index >= 0 && index < Files->Count + Dirs->Count) // bounds check to prevent data inconsistency + if (index >= 0 && index < Files->Count + Dirs->Count) // if the data are still in sync { int topIndex = ListBox->GetTopIndex(); CFileData* file = index < Dirs->Count ? &Dirs->At(index) : &Files->At(index - Dirs->Count); @@ -1681,7 +1681,7 @@ BOOL CFilesWindow::ChangePathToDisk(HWND parent, const char* path, int suggested int errTextID; // if (!SalGetFullName(backup, &errTextID, MainWindow->GetActivePanel()->Is(ptDisk) ? // MainWindow->GetActivePanel()->GetPath() : NULL)) - if (!SalGetFullName(backup, &errTextID, Is(ptDisk) ? GetPath() : NULL)) // for the FTP plugin - relative path in "target panel path" during connect + if (!SalGetFullName(backup, &errTextID, Is(ptDisk) ? GetPath() : NULL)) // because of the FTP plugin: a relative path in "target panel path" when connecting { SalMessageBox(parent, LoadStr(errTextID), LoadStr(IDS_ERRORCHANGINGDIR), MB_OK | MB_ICONEXCLAMATION); @@ -1698,7 +1698,7 @@ BOOL CFilesWindow::ChangePathToDisk(HWND parent, const char* path, int suggested oldCur = SetCursor(LoadCursor(NULL, IDC_WAIT)); BeginStopRefresh(); // no refreshes please -> they would cause recursion - // BOOL firstRun = TRUE; // commented out because forceUpdate is disabled + // BOOL firstRun = TRUE; // commented out because `forceUpdate` is commented out BOOL fixedDrive = FALSE; BOOL canTryUserRescuePath = FALSE; // allows using Configuration.IfPathIsInaccessibleGoTo right before the fixed-drive path BOOL openIfPathIsInaccessibleGoToCfg = FALSE; @@ -1727,33 +1727,33 @@ BOOL CFilesWindow::ChangePathToDisk(HWND parent, const char* path, int suggested BOOL pathInvalid, cut; SalCheckAndRestorePathWithCut(parent, changedPath, tryNet, err, lastErr, pathInvalid, cut, FALSE); if (cut) - { // invalidate proposed listbox settings (we'll list a different path) + { // invalidate the proposed list box settings (we will list a different path) suggestedTopIndex = -1; suggestedFocusName = NULL; } if (!pathInvalid && err == ERROR_SUCCESS) { - /* // commented optimization for cases when the new path matches the old one -> unusual for disks... - if (!forceUpdate && firstRun && Is(ptDisk) && IsTheSamePath(changedPath, GetPath())) - { // no reason to change the path - CloseCurrentPath(parent, TRUE, detachFS, FALSE, isRefresh, FALSE); // "cancel" - remain on the current path - EndStopRefresh(); - if (setWait) SetCursor(oldCur); - if (IsTheSamePath(path, GetPath())) - { - return TRUE; // the new path matches the current path, nothing to do - } - else - { - // shortened path matches the current path - // occurs for example when attempting to enter an inaccessible directory (immediate return) - CheckPath(TRUE, path, lastErr, TRUE, parent); // report the error that caused path shortening - return FALSE; // the requested path is not accessible - } - } - firstRun = FALSE; -*/ + /* // disabled optimization for the case when the new path matches the old one; for drives this was unusual... + if (!forceUpdate && firstRun && Is(ptDisk) && IsTheSamePath(changedPath, GetPath())) + { // no reason to change the path + CloseCurrentPath(parent, TRUE, detachFS, FALSE, isRefresh, FALSE); // "cancel" - stay on the current path + EndStopRefresh(); + if (setWait) SetCursor(oldCur); + if (IsTheSamePath(path, GetPath())) + { + return TRUE; // the new path matches the current path, nothing to do + } + else + { + // the shortened path matches the current path + // this occurs, for example, when trying to enter an inaccessible directory (immediate return) + CheckPath(TRUE, path, lastErr, TRUE, parent); // report the error that caused the path to be shortened + return FALSE; // the requested path is not accessible + } + } + firstRun = FALSE; + */ BOOL updateIcon; updateIcon = !Is(ptDisk) || // simple because forceUpdate is commented out !HasTheSameRootPath(changedPath, GetPath()); @@ -1781,7 +1781,7 @@ BOOL CFilesWindow::ChangePathToDisk(HWND parent, const char* path, int suggested MainWindow->CanAddToDirHistory = oldCanAddToDirHistory; } - // we hide the throbber and security icon; we don't need them on a disk + // hide the throbber and security icon; they are not needed on a disk path if (DirectoryLine != NULL) DirectoryLine->HideThrobberAndSecurityIcon(); @@ -1791,7 +1791,7 @@ BOOL CFilesWindow::ChangePathToDisk(HWND parent, const char* path, int suggested SetPanelType(ptDisk); SetPath(changedPath); if (updateIcon || - !GetNetworkDrive()) // to ensure icons display correctly when switching to a mounted-volume (doesn't slow on local, so hoppefully no issues) + !GetNetworkDrive()) // to ensure the icons display correctly when switching to a mounted volume (it does not slow local access, so it should not cause problems) { UpdateDriveIcon(FALSE); } @@ -1804,7 +1804,7 @@ BOOL CFilesWindow::ChangePathToDisk(HWND parent, const char* path, int suggested cannotList = !CommonRefresh(parent, suggestedTopIndex, suggestedFocusName, refreshListBox, TRUE, isRefresh); if (isRefresh && !cannotList && GetMonitorChanges() && !AutomaticRefresh) { // auto-refresh failure; we verify whether the directory displayed in the panel is being deleted (happened to me while deleting through the network from another machine) ... If ignored, the panel will never refresh (because auto-refresh is broken) - Sleep(400); // we take a break, so the deletion can proceed (so the directory becomes deleted enough to become unlistable) + Sleep(400); // pause briefly so the directory deletion can proceed far enough for listing to fail // TRACE_I("Calling CommonRefresh again... (unable to receive change notifications, first listing was OK, but maybe current directory is being deleted)"); cannotList = !CommonRefresh(parent, suggestedTopIndex, suggestedFocusName, refreshListBox, TRUE, isRefresh); // repeat the listing; this one should fail } @@ -1851,7 +1851,7 @@ BOOL CFilesWindow::ChangePathToDisk(HWND parent, const char* path, int suggested { root[0] = d; if (GetDriveType(root) == DRIVE_FIXED) - break; // we have our "escape drive" + break; // we found our "escape drive" } disks >>= 1; d++; @@ -1861,7 +1861,7 @@ BOOL CFilesWindow::ChangePathToDisk(HWND parent, const char* path, int suggested } if (done) { - if (LowerCase[root[0]] != LowerCase[changedPath[0]]) // prevention againts an infinite loop + if (LowerCase[root[0]] != LowerCase[changedPath[0]]) // guard against an infinite loop { // UNC or another disk (like "c:\") strcpy(changedPath, root); // we'll try our "escape drive" change = TRUE; @@ -1892,7 +1892,7 @@ BOOL CFilesWindow::ChangePathToDisk(HWND parent, const char* path, int suggested if (lastErr != ERROR_SUCCESS && (!isRefresh || openIfPathIsInaccessibleGoToCfg) && shorterPathWarning) { // if it's not a refresh and messages about path-shortening are supposed to be shown ... - if (!refreshListBox) // we'll display a message; we must perform refresh-list-box + if (!refreshListBox) // we are about to display a message, so we must refresh the list box { RefreshListBox(0, -1, -1, FALSE, FALSE); } @@ -1956,7 +1956,7 @@ BOOL CFilesWindow::ChangePathToDisk(HWND parent, const char* path, int suggested } else { - if (!pathInvalid && // the user already knows the UNC path couldn't be revived + if (!pathInvalid && // the user already knows that restoring the UNC path failed err != ERROR_USER_TERMINATED) // the user also knows about the abort (ESC) { CheckPath(TRUE, changedPath, err, TRUE, parent); // other errors - just display the message @@ -2059,7 +2059,7 @@ BOOL CFilesWindow::ChangePathToArchive(const char* archive, const char* archiveP BOOL checkPath = TRUE; BOOL forceUpdateInt = FALSE; // is path change required? (possibly even to disk) BOOL tryPathWithArchiveOnError = isHistory; - if (!Is(ptZIPArchive) || StrICmp(GetZIPArchive(), archive) != 0) // not the archive or a different archive + if (!Is(ptZIPArchive) || StrICmp(GetZIPArchive(), archive) != 0) // not an archive or a different archive { _REOPEN_ARCHIVE: @@ -2082,7 +2082,7 @@ BOOL CFilesWindow::ChangePathToArchive(const char* archive, const char* archiveP CloseCurrentPath(HWindow, TRUE, detachFS, FALSE, isRefresh, FALSE); // failure, stay on the original path if (forceUpdateInt) // a path change is required; opening the archive failed, go back to disk - { // we're certainly in an archive (it's a panel refresh of an archive) + { // we are certainly in an archive (this is a refresh of an archive in the panel) // if possible, exit the archive (possibly all the way to the "fixed-drive") ChangePathToDisk(HWindow, GetPath(), -1, NULL, noChange, refreshListBox, FALSE, isRefresh); } @@ -2109,8 +2109,8 @@ BOOL CFilesWindow::ChangePathToArchive(const char* archive, const char* archiveP if (failReason != NULL) *failReason = CHPPFR_INVALIDPATH; if (tryPathWithArchiveOnError) - tryPathWithArchiveOnError = (err == ERROR_SUCCESS && !pathInvalid); // shorter path is accessible, we'll try it - if (!isRefresh) // during refresh path-shortening messages are not displayed + tryPathWithArchiveOnError = (err == ERROR_SUCCESS && !pathInvalid); // the shorter path is accessible; we will try it + if (!isRefresh) // path-shortening messages are not displayed during refresh { sprintf(text, LoadStr(IDS_FILEERRORFORMAT), archive, GetErrorText(lastErr)); SalMessageBox(HWindow, text, LoadStr(IDS_ERRORTITLE), MB_OK | MB_ICONEXCLAMATION); @@ -2120,7 +2120,7 @@ BOOL CFilesWindow::ChangePathToArchive(const char* archive, const char* archiveP if (PackerFormatConfig.PackIsArchive(archive)) // is it an archive? { - // retrieve file info (does it exist?, size, date & time) + // determine file information (exists?, size, date & time) DWORD err2 = NO_ERROR; HANDLE file = HANDLES_Q(CreateFile(archive, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)); @@ -2178,9 +2178,9 @@ BOOL CFilesWindow::ChangePathToArchive(const char* archive, const char* archiveP isTheSamePath = TRUE; } - // success, switch to the new path - because listing the archive can be time-consuming - // the path changes even if the target path doesn't exist - applies to - // Change Directory (Shift+F7) which otherwise wouldn't change it + // success, switch to the new path; because listing an archive can be time-consuming, + // the path is changed even if the target path does not exist; this applies to the + // Change Directory (Shift+F7) command, which otherwise would not change the path in this situation CloseCurrentPath(HWindow, FALSE, detachFS, isTheSamePath, isRefresh, !isTheSamePath); // we just received a new listing; if there are any reported panel changes, we cancel them @@ -2242,7 +2242,7 @@ BOOL CFilesWindow::ChangePathToArchive(const char* archive, const char* archiveP return FALSE; } } - else // already opened archive + else // archive already open { if (forceUpdate) // should we check whether the archive changed? { @@ -2278,7 +2278,7 @@ BOOL CFilesWindow::ChangePathToArchive(const char* archive, const char* archiveP else { err = GetLastError(); // unable to open the archive file - if (!isRefresh) // during refresh missing-path messages are not displayed + if (!isRefresh) // during refresh, messages about a nonexistent path are not displayed { sprintf(text, LoadStr(IDS_FILEERRORFORMAT), archive, GetErrorText(err)); SalMessageBox(HWindow, text, LoadStr(IDS_ERRORTITLE), MB_OK | MB_ICONEXCLAMATION); @@ -2384,7 +2384,7 @@ BOOL CFilesWindow::ChangePathToArchive(const char* archive, const char* archiveP refreshListBox, TRUE, isRefresh); if (refreshListBox && !ok && useFileName && GetCaretIndex() == 0) - { // attempt to focus a file name failed -> it wasn't a file name + { // Attempt to focus the file name failed; it was not a file name. if (failReason != NULL) *failReason = CHPPFR_SHORTERPATH; } @@ -2425,9 +2425,9 @@ BOOL CFilesWindow::ChangeAndListPathOnFS(const char* fsName, int fsNameIndex, co if (cutFileName != NULL) *cutFileName = 0; char bufFSUserPart[MAX_PATH]; - const char* origUserPart; // user-part to which we switch the path to + const char* origUserPart; // user part to which the path should be changed int origFSNameIndex; - if (fsUserPart == NULL) // detached FS, restoration of the listing... + if (fsUserPart == NULL) // detached FS, restore the listing... { if (!pluginFS.GetCurrentPath(bufFSUserPart)) { @@ -2504,7 +2504,7 @@ BOOL CFilesWindow::ChangeAndListPathOnFS(const char* fsName, int fsNameIndex, co forceUpdate, mode); if (changePathRet) // ChangePath doesn't return an error { - if (StrICmp(newFSName, fsName) != 0) // fs-name change, verify the new fs-name + if (StrICmp(newFSName, fsName) != 0) // FS name changed; verify the new FS name { BOOL ok2 = FALSE; int index; @@ -2535,7 +2535,7 @@ BOOL CFilesWindow::ChangeAndListPathOnFS(const char* fsName, int fsNameIndex, co fsNameIndex = newFSNameIndex; } } - if (changePathRet) // store the used fs-name in 'pluginFS' + if (changePathRet) // store the fs-name in 'pluginFS' pluginFS.SetPluginFS(fsName, fsNameIndex); } @@ -2557,7 +2557,7 @@ BOOL CFilesWindow::ChangeAndListPathOnFS(const char* fsName, int fsNameIndex, co break; } - if (keepOldListing == NULL || !*keepOldListing) // not dead-code (used when allocating workDir fails) + if (keepOldListing == NULL || !*keepOldListing) // not dead code (used when workDir allocation fails) { // release listing data in the panel if (UseSystemIcons || UseThumbnails) @@ -2578,7 +2578,7 @@ BOOL CFilesWindow::ChangeAndListPathOnFS(const char* fsName, int fsNameIndex, co } // attempt to list files and directories from the current path - if (pluginFS.ListCurrentPath(workDir, pluginData, pluginIconsType, forceUpdate)) // succeeded ... + if (pluginFS.ListCurrentPath(workDir, pluginData, pluginIconsType, forceUpdate)) // completed successfully... { if (keepOldListing != NULL && *keepOldListing) // we already have the new listing; discard the old one { @@ -2609,7 +2609,7 @@ BOOL CFilesWindow::ChangeAndListPathOnFS(const char* fsName, int fsNameIndex, co TRACE_E("Invalid plugin-icons-type!"); pluginIconsType = pitSimple; } - if (pluginIconsType == pitFromPlugin && pluginData == NULL) // not allowed, degrade the type + if (pluginIconsType == pitFromPlugin && pluginData == NULL) // this would not work; fall back to a simpler type { TRACE_E("Plugin-icons-type is pitFromPlugin and plugin-data is NULL!"); pluginIconsType = pitSimple; @@ -2620,7 +2620,7 @@ BOOL CFilesWindow::ChangeAndListPathOnFS(const char* fsName, int fsNameIndex, co } // we prepare dir for further use (release leftovers if the plugin left any) workDir->Clear(NULL); - // path isn't o.k.; we'll try shortening it in the next cycle pass + // the path is not OK; we will try to shorten it in the next loop iteration if (!pluginFS.GetCurrentPath(user)) { TRACE_E("Unexpected situation in CFilesWindow::ChangeAndListPathOnFS()"); @@ -2631,7 +2631,7 @@ BOOL CFilesWindow::ChangeAndListPathOnFS(const char* fsName, int fsNameIndex, co { TRACE_I("Unable to open FS path " << fsName << ":" << origUserPart); - if (firstCall && (keepOldListing == NULL || !*keepOldListing)) // not dead-code (used when allocating workDir fails) + if (firstCall && (keepOldListing == NULL || !*keepOldListing)) // not dead code (used when workDir allocation fails) { // release listing data in the panel if (UseSystemIcons || UseThumbnails) @@ -2656,11 +2656,11 @@ BOOL CFilesWindow::ChangeAndListPathOnFS(const char* fsName, int fsNameIndex, co if (dir != workDir) delete workDir; // 'workDir' wasn't used, free it - // we try to find a file to focus in the FS listing - not perfect when the file is hidden - // from the panel listing (e.g., "don't show hidden files" or filters) because it cannot - // be focused and the user won't know about this "error" - but it's probably - // not really an error if the file does exist, so we ignore it (same as with - // disk paths)... + // Attempts to find the file to focus in the FS listing; this is not perfect if the file is hidden + // from the panel listing (for example by "don't show hidden files" or by filters), because then it + // cannot be focused in the panel and the user will not learn about this "error"; however, it is + // probably not possible to report it as an error when the file actually exists, so it is ignored + // (as with disk paths)... if (ok && useCutFileName && cutFileName != NULL && *cutFileName != 0) { CFilesArray* files = dir->GetFiles(""); @@ -2748,7 +2748,7 @@ BOOL CFilesWindow::ChangePathToPluginFS(const char* fsName, const char* fsUserPa char cutFileNameBuf[MAX_PATH]; int fsNameIndex; if (!Is(ptPluginFS) || !IsPathFromActiveFS(fsName, fsUserPart2, fsNameIndex, convertPathToInternal)) - { // is not FS or the path is from a different FS (even within a single plug-in - one FS name) + { // is not FS or the path is from a different FS (even within a single plugin - one FS name) BOOL detachFS; if (PrepareCloseCurrentPath(HWindow, FALSE, TRUE, detachFS, FSTRYCLOSE_CHANGEPATH)) { // the current path can be closed, attempt to open the new path @@ -2757,12 +2757,12 @@ BOOL CFilesWindow::ChangePathToPluginFS(const char* fsName, const char* fsUserPa *failReason = CHPPFR_INVALIDPATH; if (Plugins.IsPluginFS(fsName, index, fsNameIndex)) // find the plugin index { - // obtain the plug-in containing the FS + // obtain the plugin containing the FS CPluginData* plugin = Plugins.Get(index); if (plugin != NULL) { // open the new FS - // load the plug-in before obtaining DLLName, Version, and plugin interfaces + // load the plugin before obtaining DLLName, Version, and plugin interfaces CPluginFSInterfaceAbstract* auxFS = plugin->OpenFS(fsName, fsNameIndex); CPluginFSInterfaceEncapsulation pluginFS(auxFS, plugin->DLLName, plugin->Version, plugin->GetPluginInterfaceForFS()->GetInterface(), @@ -2980,8 +2980,8 @@ BOOL CFilesWindow::ChangePathToPluginFS(const char* fsName, const char* fsUserPa { suggestedFocusName = NULL; - // the new path shortened back to the original ("unlistable subdirectory"), - // keep topIndex and focusName from before the operation starts (so the user doesn't lose focus) + // the new path shortened back to the original path ("unlistable subdirectory"); preserve + // topIndex and focusName from before the operation so the user does not lose focus if (currentPathOK && GetPluginFS()->IsCurrentPath(GetPluginFS()->GetPluginFSNameIndex(), currentPathFSNameIndex, currentPath)) @@ -3022,7 +3022,7 @@ BOOL CFilesWindow::ChangePathToPluginFS(const char* fsName, const char* fsUserPa } else { - if (shorterPath && cutFileName != NULL && *cutFileName != 0 && refreshListBox) // the file needs to be focused + if (shorterPath && cutFileName != NULL && *cutFileName != 0 && refreshListBox) // focus the file { int focusIndexCase = -1; int focusIndexIgnCase = -1; @@ -3058,7 +3058,7 @@ BOOL CFilesWindow::ChangePathToPluginFS(const char* fsName, const char* fsUserPa } } - if (focusIndexIgnCase != -1) // at least one file was found with potencial case difference + if (focusIndexIgnCase != -1) // at least one file with a possible case difference was found { SetCaretIndex(focusIndexCase != -1 ? focusIndexCase : focusIndexIgnCase, FALSE); } @@ -3067,7 +3067,7 @@ BOOL CFilesWindow::ChangePathToPluginFS(const char* fsName, const char* fsUserPa ok = TRUE; } - else // requested path is not accessible, try returning to the original path + else // requested path is not accessible, try to return to the original path { if (noChange != NULL) *noChange = FALSE; // the listing will be cleared or changed @@ -3077,8 +3077,8 @@ BOOL CFilesWindow::ChangePathToPluginFS(const char* fsName, const char* fsUserPa *GetPluginFS(), GetPluginFSDir(), pluginData, shorterPath, pluginIconsType, mode, FALSE, NULL, NULL, -1, FALSE, NULL, &keepOldListing)) - { // success, the original path (or its subpath) was listed - // invalidate proposed listbox settings (we'll list a different path) + { // success, the original path (or one of its subpaths) was listed + // invalidate the proposed list box settings (we will list a different path) suggestedTopIndex = -1; suggestedFocusName = NULL; @@ -3092,7 +3092,7 @@ BOOL CFilesWindow::ChangePathToPluginFS(const char* fsName, const char* fsUserPa // add the path we just left (paths inside the FS remain open, // so DirHistoryAddPathUnique hasn't been called yet) - if (currentPathOK && shorterPath) // if shorterPath is FALSE, the path didn't change... + if (currentPathOK && shorterPath) // if shorterPath is FALSE, the path did not change... { if (UserWorkedOnThisPath) { @@ -3140,7 +3140,7 @@ BOOL CFilesWindow::ChangePathToPluginFS(const char* fsName, const char* fsUserPa // notify the FS that the path changed GetPluginFS()->Event(FSE_PATHCHANGED, GetPanelCode()); } - else // show an empty panel, nothing can be read from the FS, switch to the fixed drive + else // show an empty panel; nothing can be loaded from the FS, switch to the fixed drive { if (keepOldListing) { @@ -3152,14 +3152,14 @@ BOOL CFilesWindow::ChangePathToPluginFS(const char* fsName, const char* fsUserPa ListBox->SetItemsCount(0, 0, 0, TRUE); SelectedCount = 0; } - else // not dead-code, see 'workDir' allocation error in ChangeAndListPathOnFS() + else // not dead code; see the 'workDir' allocation error in ChangeAndListPathOnFS() { // clean the message queue from buffered WM_USER_UPDATEPANEL MSG msg2; PeekMessage(&msg2, HWindow, WM_USER_UPDATEPANEL, WM_USER_UPDATEPANEL, PM_REMOVE); } - // we hide the throbber and security icon; because we're leaving the FS... + // hide the throbber and security icon because we are leaving the FS... if (DirectoryLine != NULL) DirectoryLine->HideThrobberAndSecurityIcon(); @@ -3397,7 +3397,7 @@ BOOL CFilesWindow::ChangePathToDetachedFS(int fsIndex, int suggestedTopIndex, } else { - if (closeDetachedFS) // no path can be opened on the FS anymore, close it + if (closeDetachedFS) // No path can be opened in this FS anymore; close it { BOOL dummy; if (pluginFS->TryCloseOrDetach(FALSE, FALSE, dummy, FSTRYCLOSE_ATTACHFAILURE)) @@ -3438,10 +3438,10 @@ void CFilesWindow::RefreshDiskFreeSpace(BOOL check, BOOL doNotRefreshOtherPanel) if (!doNotRefreshOtherPanel) { - // if the other panel uses a path with the same root, we refresh - // disk-free-space there as well (it is not perfect - ideally we would - // test whether both paths are on the same volume, but that would be too slow; - // this simplification should be more than enough for normal use) + // if the path in the other panel has the same root, refresh the + // disk free space there as well (this is not perfect; ideally we would + // test whether the paths are on the same volume, but that would be too slow; + // this simplification is more than sufficient for normal use) CFilesWindow* otherPanel = (MainWindow->LeftPanel == this) ? MainWindow->RightPanel : MainWindow->LeftPanel; if (otherPanel->Is(ptDisk) && HasTheSameRootPath(GetPath(), otherPanel->GetPath())) otherPanel->RefreshDiskFreeSpace(TRUE, TRUE /* otherwise we'd recurse endlessly */); @@ -3491,7 +3491,7 @@ void GetCommonFileTypeStr(char* buf, int* resLen, const char* ext) *d++ = UpperCase[*ext++]; *d = 0; if (*ext == 0 && uppercaseExt[0] != 0) - { // we have the entire extension in uppercase (no spaces and shorter than MAX_PATH) + it is not empty + { // we have the entire extension in uppercase (it contains no spaces, is shorter than MAX_PATH, and is not empty) *resLen = _snprintf_s(buf, TRANSFER_BUFFER_MAX, _TRUNCATE, CommonFileTypeName2, uppercaseExt); if (*resLen < 0) *resLen = TRANSFER_BUFFER_MAX - 1; // _snprintf_s reports truncation to the buffer size @@ -3816,7 +3816,7 @@ void CFilesWindow::RefreshListBox(int suggestedXOffset, if (autoWidthColumns & VIEW_SHOW_TYPE) { //--- file-type - if (!isDir) // it is a file + if (!isDir) // file { char buf[TRANSFER_BUFFER_MAX]; BOOL commonFileType = TRUE; @@ -3831,7 +3831,7 @@ void CFilesWindow::RefreshListBox(int suggestedXOffset, if (Associations.GetIndex(buf, index)) { src = Associations[index].Type; - if (src != NULL) // if it is not an empty string + if (src != NULL) // if the string is not empty { commonFileType = FALSE; GetTextExtentPoint32(dc, src, (int)strlen(src), &act); @@ -3851,7 +3851,7 @@ void CFilesWindow::RefreshListBox(int suggestedXOffset, columnWidthType = act.cx; } } - else // it is a directory + else // directory { if (!dirTypeDone) // only if we have not computed it yet { @@ -4069,11 +4069,11 @@ void CFilesWindow::RefreshListBox(int suggestedXOffset, if (suggestedFocusIndex != -1) { FocusedIndex = suggestedFocusIndex; - // if no TopIndex is suggested or focus visibility - // is required, compute a new TopIndex + // if no TopIndex is suggested or focus visibility is required, + // compute a new TopIndex // -- clearer version with support for vmIcons and vmThumbnails - // -- change for partially visible items: previously TopIndex was recalculated - // and causing unnecessary jumps; now we keep TopIndex unchanged + // -- change for partially visible items: TopIndex used to be recalculated + // and caused unnecessary jumps; now we leave TopIndex unchanged BOOL findTopIndex = TRUE; // TRUE - search for TopIndex; FALSE - keep the current one if (suggestedTopIndex != -1) @@ -4106,7 +4106,7 @@ void CFilesWindow::RefreshListBox(int suggestedXOffset, { if (suggestedTopIndex + cols * ListBox->EntireItemsInColumn <= suggestedFocusIndex) - break; // focus lies past the panel, must find a better TopIndex + break; // focus lies past the panel; we must find a better TopIndex } // focus is at least partially visible, skip TopIndex search @@ -4128,12 +4128,12 @@ void CFilesWindow::RefreshListBox(int suggestedXOffset, if (wholeItemVisible) { if (suggestedTopIndex + rows <= suggestedFocusIndex + 1) // avoid partial visibility, hence the +1 - break; // focus lies below the panel, we must find a better TopIndex + break; // focused item lies below the panel; we need to find a better TopIndex } else { if (suggestedTopIndex + rows <= suggestedFocusIndex) - break; // focus lies below the panel, we must find a better TopIndex + break; // the focus is below the panel; we need to find a better TopIndex } // focus is fully visible, skip TopIndex search @@ -4153,7 +4153,7 @@ void CFilesWindow::RefreshListBox(int suggestedXOffset, if (wholeItemVisible) { if (suggestedTop < suggestedTopIndex) - break; // focus is above the panel; we must find a better TopIndex + break; // focus lies above the panel, we must find a better TopIndex if (suggestedBottom > suggestedTopIndex + ListBox->FilesRect.bottom - ListBox->FilesRect.top) @@ -4162,7 +4162,7 @@ void CFilesWindow::RefreshListBox(int suggestedXOffset, else { if (suggestedBottom <= suggestedTopIndex) - break; // focus is above the panel; we must find a better TopIndex + break; // focus lies above the panel, we must find a better TopIndex if (suggestedTop >= suggestedTopIndex + ListBox->FilesRect.bottom - ListBox->FilesRect.top) @@ -4208,7 +4208,7 @@ void CFilesWindow::RefreshListBox(int suggestedXOffset, // (e.g., Back in history to a place where the previously focused file no longer exists) if (ensureFocusIndexVisible && suggestedTopIndex != -1) // focus must be visible { - suggestedTopIndex = -1; // cannot set top-index (the focus wouldn't be visible) + suggestedTopIndex = -1; // cannot set the top index (the focus would not be visible) } } diff --git a/src/fileswn3.cpp b/src/fileswn3.cpp index 445563ce5..4e8387c64 100644 --- a/src/fileswn3.cpp +++ b/src/fileswn3.cpp @@ -131,8 +131,8 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) Files->SetDeleteData(TRUE); Dirs->SetDeleteData(TRUE); - if (WaitForESCReleaseBeforeTestingESC) // waiting for ESC release (so that listing is not interrupted - // immediately - this ESC probably ended modal dialog/messagebox) + if (WaitForESCReleaseBeforeTestingESC) // wait for ESC to be released (so that listing is not interrupted + // immediately; this ESC probably closed a modal dialog/message box) { WaitForESCRelease(); WaitForESCReleaseBeforeTestingESC = FALSE; // another waiting makes no sense @@ -154,7 +154,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) { BOOL isDriveFloppy = FALSE; // floppies have their own configuration beside other removable drives int drv = UpperCase[fileName[0]] - 'A' + 1; - if (drv >= 1 && drv <= 26) // doing "range-check" for sure + if (drv >= 1 && drv <= 26) // perform a range check just to be safe { DWORD medium = GetDriveFormFactor(drv); if (medium == 350 || medium == 525 || medium == 800 || medium == 1) @@ -192,7 +192,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) SetCurrentDirectoryToSystem(); DirectoryLine->SetHidden(HiddenFilesCount, HiddenDirsCount); // TRACE_I("ReadDirectory: end"); - return FALSE; // empty string on input + return FALSE; // empty input string } if (*(st - 1) != '\\') *st++ = '\\'; @@ -202,7 +202,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) if (UseSystemIcons) { IconCacheValid = FALSE; - MSG msg; // we must destroy possible WM_USER_ICONREADING_END which would set IconCacheValid = TRUE + MSG msg; // we must remove any pending WM_USER_ICONREADING_END that would set IconCacheValid = TRUE while (PeekMessage(&msg, HWindow, WM_USER_ICONREADING_END, WM_USER_ICONREADING_END, PM_REMOVE)) ; @@ -218,7 +218,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) if (UseThumbnails) { IconCacheValid = FALSE; - MSG msg; // we must destroy possible WM_USER_ICONREADING_END which would set IconCacheValid = TRUE + MSG msg; // we must remove any pending WM_USER_ICONREADING_END that would set IconCacheValid = TRUE while (PeekMessage(&msg, HWindow, WM_USER_ICONREADING_END, WM_USER_ICONREADING_END, PM_REMOVE)) ; } @@ -228,7 +228,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) BOOL UNCRootUpDir = FALSE; if (GetPath()[0] == '\\' && GetPath()[1] == '\\') { - if (GetPath()[2] == '.' && GetPath()[3] == '\\' && GetPath()[4] != 0 && GetPath()[5] == ':') // "\\.\C:\" type path + if (GetPath()[2] == '.' && GetPath()[3] == '\\' && GetPath()[4] != 0 && GetPath()[5] == ':') // path of the "\\.\C:\" type { upDir = strlen(GetPath()) > 7; } @@ -282,12 +282,12 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) DWORD lastEscCheckTime; //lastEscCheckTime = GetTickCount() - 200; // the first ESC will go immediately - lastEscCheckTime = GetTickCount(); // the first ESC will go after 200 ms -- it's a protection + lastEscCheckTime = GetTickCount(); // the first ESC will only be accepted after 200 ms; this protects // against the cancel prompt for listing after the user - // has closed a dialog (e.g. Files/Security/*) by Esc and - // in the panel there was a network drive (and during the - // opened dialog the user switched to Salamander and back, - // so that there was a refresh of the directory) + // has closed a dialog (e.g. Files/Security/*) with Esc and + // there was a network drive in the panel (and during the + // open dialog the user switched to Salamander and back, + // causing a directory refresh) BOOL isUpDir = FALSE; WIN32_FIND_DATA fileData; @@ -369,7 +369,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) if (isRefresh && (err == ERROR_ACCESS_DENIED || err == ERROR_PATH_NOT_FOUND || err == ERROR_BAD_PATHNAME || err == ERROR_FILE_NOT_FOUND)) - { // when deleting a path shown in the panel, these errors are shown, which we don't want, we just silently shorten the path to the first existing one (unfortunately it's not caught earlier, because the path exists for some time after its deletion, something in Windows just didn't work out again) + { // when a path displayed in the panel is deleted, these errors appear, which we do not want, so just silently shorten the path to the first existing one (unfortunately this is not caught earlier because the path still exists for some time after deletion due to Windows behavior) // TRACE_I("ReadDirectory(): silently ignoring FindFirstFile failure: " << GetErrorText(err)); showErr = FALSE; } @@ -387,7 +387,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) { NumberOfItemsInCurDir++; - // test ESC - doesn't user want to interrupt reading? + // test ESC: does the user want to interrupt reading? if (GetTickCount() - lastEscCheckTime >= 200) // 5 times per second { if (UserWantsToCancelSafeWaitWindow()) @@ -410,13 +410,13 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) if (resBut == IDYES) { testFindNextErr = FALSE; - break; // finish reading + break; // stop loading } else { if (resBut == IDNO) { - if (GetMonitorChanges()) // need to suppress monitoring of changes (autorefresh) + if (GetMonitorChanges()) // suppress change monitoring (auto-refresh) { DetachDirectory((CFilesWindow*)this); SetMonitorChanges(FALSE); // the changes won't be monitored anymore @@ -507,7 +507,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) memmove(file.Name, st, len + 1); // copy of text file.NameLen = len; //--- extension - if (!Configuration.SortDirsByExt && (fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) // this is ptDisk + if (!Configuration.SortDirsByExt && (fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) // ptDisk only { file.Ext = file.Name + file.NameLen; // directories have no extension } @@ -530,7 +530,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) file.Hidden = (file.Attr & FILE_ATTRIBUTE_HIDDEN) && !IsFilePlaceholder(&fileData) ? 1 : 0; file.IsOffline = !isUpDir && (file.Attr & FILE_ATTRIBUTE_OFFLINE) ? 1 : 0; - if (testShares && (file.Attr & FILE_ATTRIBUTE_DIRECTORY)) // this is ptDisk + if (testShares && (file.Attr & FILE_ATTRIBUTE_DIRECTORY)) // ptDisk { file.Shared = Shares.Search(file.Name); } @@ -563,12 +563,12 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) } else file.DosName = NULL; - if (file.Attr & FILE_ATTRIBUTE_DIRECTORY) // this is ptDisk + if (file.Attr & FILE_ATTRIBUTE_DIRECTORY) // ptDisk { file.Association = 0; file.Archive = 0; #ifndef _WIN64 - file.IsLink = (isWin64RedirectedDir || (fileData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) || // CAUTION: pseudo-directory must have IsLink set, otherwise ContainsWin64RedirectedDir must be changed + file.IsLink = (isWin64RedirectedDir || (fileData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) || // CAUTION: pseudo-directories must have IsLink set; otherwise, ContainsWin64RedirectedDir must be changed isWindows64BitDir && file.NameLen == 8 && StrICmp(file.Name, "system32") == 0) ? 1 : 0; // system32 directory in 32-bit Salamander is link to SysWOW64 + win64 redirected-dir + volume mount point or junction point = show directory with link overlay @@ -617,7 +617,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) } else { - if (s >= st) // an extension exists + if (s >= st) // extension exists { while (*++s != 0) *st++ = LowerCase[*s]; @@ -635,7 +635,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) : 0; } - if (PackerFormatConfig.PackIsArchive(file.Name, file.NameLen)) // is it an archive which we can process? + if (PackerFormatConfig.PackIsArchive(file.Name, file.NameLen)) // is this an archive format we can handle? { file.Association = 1; file.Archive = 1; @@ -645,22 +645,22 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) { file.Association = Associations.IsAssociated(st, addtoIconCache, iconSize); file.Archive = 0; - if (*(DWORD*)st == *(DWORD*)"scr" || // few exceptions + if (*(DWORD*)st == *(DWORD*)"scr" || // a few exceptions *(DWORD*)st == *(DWORD*)"pif") { addtoIconCache = TRUE; } else { - if (*(DWORD*)st == *(DWORD*)"lnk") // icons via link + if (*(DWORD*)st == *(DWORD*)"lnk") // icons via shortcut { strcpy(fileData.cFileName, file.Name); char* ext2 = strrchr(fileData.cFileName, '.'); - if (ext2 != NULL) // ".cvspass" in Windows is an extesion + if (ext2 != NULL) // ".cvspass" is treated as an extension in Windows // if (ext2 != NULL && ext2 != fileData.cFileName) { *ext2 = 0; - if (PackerFormatConfig.PackIsArchive(fileData.cFileName)) // is it a link to archive which we can process? + if (PackerFormatConfig.PackIsArchive(fileData.cFileName)) // is it a link to an archive that we can process? { file.Association = 1; file.Archive = 1; @@ -701,7 +701,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) } // at the file, we will check if it's necessary to load its thumbnail - if (readThumbnails && // thumbnail should be loaded + if (readThumbnails && // load thumbnails (file.Attr & FILE_ATTRIBUTE_DIRECTORY) == 0 && // (it is ptDisk, so using FILE_ATTRIBUTE_DIRECTORY is o.k.) file.Archive == 0) // archive icon is preferred before thumbnail { @@ -713,30 +713,30 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) if (p->ThumbnailMasks.AgreeMasks(file.Name, file.Ext) && !p->ThumbnailMasksDisabled) // its unload/remove is not in progress { - if (!p->GetLoaded()) // plugin needs to be loaded (possible change of mask for "thumbnail loader") + if (!p->GetLoaded()) // plugin needs to be loaded (the "thumbnail loader" mask may change) { // RefreshListBox(0, -1, -1, FALSE, FALSE); // replaced with ListBox->SetItemsCound + WM_USER_UPDATEPANEL, because it was blinking e.g. when adding the first *.doc file to a directory with images (Eroiica is loaded (for thumbnail *.doc)) // displaying "PictureView is not registered" dialog may occur -> in that case it's necessary // to refresh listbox (otherwise we don't do any refresh, so that it doesn't blink with the panel) // we protect listbox against errors caused by request for refresh (data is just being read from disk) - ListBox->SetItemsCount(0, 0, 0, TRUE); // TRUE - we will disable setting scrollbar - // If WM_USER_UPDATEPANEL is delivered, the panel will be redrawn and scrollbar will be set. - // Message loop can deliver it when message box (or dialog) is created. - // Otherwise the panel will behave as unchanged and the message will be removed from queue. + ListBox->SetItemsCount(0, 0, 0, TRUE); // TRUE - disable scrollbar updates + // If WM_USER_UPDATEPANEL is delivered, the panel contents will be redrawn and the scrollbar will be updated. + // The message loop can deliver it when a message box (or dialog) is created. + // Otherwise, the panel will appear unchanged and the message will be removed from the queue. PostMessage(HWindow, WM_USER_UPDATEPANEL, 0, 0); BOOL cont = FALSE; if (p->InitDLL(HWindow, FALSE, TRUE, FALSE) && // plugin loaded successfully p->ThumbnailMasks.GetMasksString()[0] != 0) // plugin is still "thumbnail loader" { - if (!p->ThumbnailMasks.AgreeMasks(file.Name, file.Ext) || // it can't do thumbnail for this file anymore + if (!p->ThumbnailMasks.AgreeMasks(file.Name, file.Ext) || // it can no longer generate thumbnails for this file p->ThumbnailMasksDisabled) // its unload/remove is in progress { cont = TRUE; } } - else // can't load -> we will remove it from the list of probed plugins (prevent from repeating error messages) + else // cannot load -> remove it from the list of tried plugins (to prevent repeated error messages) { TRACE_I("Unable to use plugin " << p->Name << " as thumbnail loader."); thumbLoaderPlugins.Delete(i); @@ -764,10 +764,10 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) if (foundThumbLoaderPlugins.Count > 0) { int size = len + 4; - size -= (size & 0x3); // size % 4 (alignment per four bytes) + size -= (size & 0x3); // size % 4 (4-byte alignment) int nameSize = size; size += sizeof(CQuadWord) + sizeof(FILETIME); - size += (foundThumbLoaderPlugins.Count + 1) * sizeof(void*); // space for pointers to plugin interfaces + NULL at the end + size += (foundThumbLoaderPlugins.Count + 1) * sizeof(void*); // space for pointers to plugin interfaces and NULL at the end iconData.NameAndData = (char*)malloc(size); if (iconData.NameAndData != NULL) { @@ -786,7 +786,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) *ifaces = NULL; // the end of list of plugin interfaces iconData.SetFlag(4); // so far no unread thumbnail - // we have to allocate space for thumbnail, because it can't be done in the thread + // we must allocate space for the thumbnail here; it cannot be done in the thread iconData.SetIndex(IconCache->AllocThumbnail()); if (iconData.GetIndex() != -1) @@ -798,7 +798,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) IconCache->ResetState(); } else - addtoIconCache = FALSE; // it's a thumbnail, it can't be an icon at the same time + addtoIconCache = FALSE; // this is a thumbnail, so it cannot be an icon at the same time } else free(iconData.NameAndData); @@ -813,14 +813,14 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) if (UseSystemIcons && addtoIconCache) { int size = len + 4; - size -= (size & 0x3); // size % 4 (alignment per four bytes) + size -= (size & 0x3); // size % 4 (4-byte alignment) iconData.NameAndData = (char*)malloc(size); if (iconData.NameAndData != NULL) { memmove(iconData.NameAndData, file.Name, len); memset(iconData.NameAndData + len, 0, size - len); // end of name is zeroed - iconData.SetFlag(0); // no not-loaded icon yet - // need to allocate space for bitmaps, can't be done in thread + iconData.SetFlag(0); // icon not loaded yet + // bitmap storage must be allocated here; it cannot be done in the worker thread iconData.SetIndex(IconCache->AllocIcon(NULL, NULL)); if (iconData.GetIndex() != -1) { @@ -841,7 +841,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) #ifndef _WIN64 isWin64RedirectedDir = FALSE; #endif // _WIN64 - break; // the second pass (adding ".." or win64 redirected-dir) + break; // second pass (adding ".." or the Win64-redirected directory) } } while (FindNextFile(search, &fileData)); DWORD err = GetLastError(); @@ -913,7 +913,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) if (foundWin64RedirectedDirs < 10 && AddWin64RedirectedDir(GetPath(), Dirs, &fileData, &foundWin64RedirectedDirs, &dirWithSameNameExists)) { - foundWin64RedirectedDirs++; // e.g. under system32 there can be 5, I've added some reserve to 10... + foundWin64RedirectedDirs++; // e.g. there can be 5 of them under system32; some reserve was added up to 10... if (Configuration.NotHiddenSystemFiles && (fileData.dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM))) @@ -998,7 +998,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) { CFileData* f = &ZIPFiles->At(i); if (Configuration.NotHiddenSystemFiles && - (f->Hidden || // both Hidden and Attr are nulled if they are invalid -> tests fail + (f->Hidden || // Hidden and Attr are zeroed when invalid; otherwise tests fail (f->Attr & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)))) { // skip hidden file/directory HiddenFilesCount++; @@ -1025,13 +1025,13 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) } CFileData upDir; static char buffUp[] = ".."; - upDir.Name = buffUp; // free() won't be called, we can afford ".." + upDir.Name = buffUp; // free() will not be called, so ".." can be used directly upDir.Ext = upDir.Name + 2; upDir.Size = CQuadWord(0, 0); upDir.Attr = 0; upDir.LastWrite = GetZIPArchiveDate(); upDir.DosName = NULL; - upDir.PluginData = 0; // 0 just like that, plug-in will overwrite it with its value + upDir.PluginData = 0; // 0 just like that, plugin will overwrite it with its value upDir.NameLen = 2; upDir.Hidden = 0; upDir.IsLink = 0; @@ -1054,7 +1054,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) { CFileData* f = &ZIPDirs->At(i); if (Configuration.NotHiddenSystemFiles && - (f->Hidden || // both Hidden and Attr are nulled if they are invalid -> tests fail + (f->Hidden || // Hidden and Attr are zeroed if they are invalid -> tests fail (f->Attr & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)))) { // skip hidden file/directory HiddenDirsCount++; @@ -1087,7 +1087,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) { DirectoryLine->SetHidden(HiddenFilesCount, HiddenDirsCount); // TRACE_I("ReadDirectory: end"); - return FALSE; // the directory has ceased to exist ... + return FALSE; // the directory no longer exists ... } // sorting of Files and Dirs according to the current sorting method @@ -1098,7 +1098,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) { // preparing for loading of icons IconCacheValid = FALSE; - MSG msg; // need to remove any WM_USER_ICONREADING_END, which would set IconCacheValid = TRUE + MSG msg; // remove any pending WM_USER_ICONREADING_END that would set IconCacheValid = TRUE while (PeekMessage(&msg, HWindow, WM_USER_ICONREADING_END, WM_USER_ICONREADING_END, PM_REMOVE)) ; @@ -1115,10 +1115,10 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) const char* iconLocation = NULL; CFileData* f = &Files->At(i); - if (*f->Ext != 0) // an extension exists + if (*f->Ext != 0) // file has an extension { /* - if (PackerFormatConfig.PackIsArchive(f->Name)) // is it an archive which we can process? + if (PackerFormatConfig.PackIsArchive(f->Name)) // is it an archive that we can process? { f->Association = TRUE; f->Archive = TRUE; @@ -1151,13 +1151,13 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) iconData.FSFileData = NULL; iconData.SetReadingDone(0); // just for form int size = (int)strlen(iconLocation) + 4; - size -= (size & 0x3); // size % 4 (alignment per four bytes) + size -= (size & 0x3); // size % 4 (4-byte alignment) const char* s = iconLocation + size; // skip alignment from zeros int len = (int)strlen(s); - if (len > 0) // icon-location is not empty + if (len > 0) // icon location is not empty { int nameLen = f->NameLen + 4; - nameLen -= (nameLen & 0x3); // nameLen % 4 (alignment per four bytes) + nameLen -= (nameLen & 0x3); // nameLen % 4 (four-byte alignment) iconData.NameAndData = (char*)malloc(nameLen + len + 1); if (iconData.NameAndData != NULL) { @@ -1165,8 +1165,8 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) memset(iconData.NameAndData + f->NameLen, 0, nameLen - f->NameLen); // zeroes alignment + memcpy(iconData.NameAndData + nameLen, s, len + 1); // icon-location + '\0' - iconData.SetFlag(3); // not-loaded icon given by icon-location only - // we need to allocate space for bitmaps, can't be done in thread + iconData.SetFlag(3); // icon not loaded yet; only the icon location is known + // we need to allocate space for the bitmaps, which cannot be done in this thread iconData.SetIndex(IconCache->AllocIcon(NULL, NULL)); if (iconData.GetIndex() != -1) { @@ -1196,10 +1196,10 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) { CFileData* f = &Files->At(i); - if (*f->Ext != 0) // an extension exists + if (*f->Ext != 0) // has an extension { /* - if (PackerFormatConfig.PackIsArchive(f->Name)) // is it an archive which we can process? + if (PackerFormatConfig.PackIsArchive(f->Name)) // is it an archive that we can process? { f->Association = TRUE; f->Archive = TRUE; @@ -1265,7 +1265,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) CFileData* f = &FSFiles->At(i); if (Configuration.NotHiddenSystemFiles && - (f->Hidden || // both Hidden and Attr are nulled if they are invalid -> tests fail + (f->Hidden || // Hidden and Attr are zeroed when invalid; otherwise the tests fail (f->Attr & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)))) { // skip hidden file/directory HiddenFilesCount++; @@ -1295,7 +1295,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) { CFileData* f = &FSDirs->At(i); if (Configuration.NotHiddenSystemFiles && - (f->Hidden || // both Hidden and Attr are nulled if they are invalid -> tests fail + (f->Hidden || // both Hidden and Attr are zeroed if they are invalid -> tests fail (f->Attr & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)))) { // skip hidden file/directory HiddenDirsCount++; @@ -1329,7 +1329,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) { DirectoryLine->SetHidden(HiddenFilesCount, HiddenDirsCount); // TRACE_I("ReadDirectory: end"); - return FALSE; // the directory has ceased to exist ... + return FALSE; // the directory no longer exists ... } // if the panel is empty, we will set infoline to "No files found" @@ -1359,7 +1359,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) // preparing for loading of icons IconCacheValid = FALSE; - MSG msg; // need to remove any WM_USER_ICONREADING_END, which would set IconCacheValid = TRUE + MSG msg; // need to remove any pending WM_USER_ICONREADING_END message that would set IconCacheValid = TRUE while (PeekMessage(&msg, HWindow, WM_USER_ICONREADING_END, WM_USER_ICONREADING_END, PM_REMOVE)) ; @@ -1379,7 +1379,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) if (*f->Ext != 0) // an extension exists { /* - if (PackerFormatConfig.PackIsArchive(f->Name)) // is it an archive which we can process? + if (PackerFormatConfig.PackIsArchive(f->Name)) // is it an archive that we can process? { f->Association = TRUE; f->Archive = TRUE; @@ -1412,13 +1412,13 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) iconData.FSFileData = NULL; iconData.SetReadingDone(0); // just for form int size = (int)strlen(iconLocation) + 4; - size -= (size & 0x3); // size % 4 (alignment per four bytes) + size -= (size & 0x3); // size % 4 (4-byte alignment) const char* s = iconLocation + size; // skip alignment from zeros int len = (int)strlen(s); - if (len > 0) // icon-location is not empty + if (len > 0) // icon location is not empty { int nameLen = f->NameLen + 4; - nameLen -= (nameLen & 0x3); // nameLen % 4 (alignment per four bytes) + nameLen -= (nameLen & 0x3); // nameLen % 4 (aligned to four bytes) iconData.NameAndData = (char*)malloc(nameLen + len + 1); if (iconData.NameAndData != NULL) { @@ -1426,8 +1426,8 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) memset(iconData.NameAndData + f->NameLen, 0, nameLen - f->NameLen); // zeroes alignment + memcpy(iconData.NameAndData + nameLen, s, len + 1); // icon-location + '\0' - iconData.SetFlag(3); // not-loaded icon given by icon-location only - // we need to allocate space for bitmaps, can't be done in thread + iconData.SetFlag(3); // icon not yet loaded, specified only by icon-location + // we need to allocate space for the bitmaps; this cannot be done in the worker thread iconData.SetIndex(IconCache->AllocIcon(NULL, NULL)); if (iconData.GetIndex() != -1) { @@ -1459,7 +1459,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) TRACE_E("SimplePluginIcons is not NULL before GetSimplePluginIcons()."); #endif // _DEBUG SimplePluginIcons = PluginData.GetSimplePluginIcons(iconSize); - if (SimplePluginIcons == NULL) // not a success -> degradation to pitSimple + if (SimplePluginIcons == NULL) // failure -> fall back to pitSimple { SetPluginIconsType(pitSimple); } @@ -1477,7 +1477,7 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) if (*f->Ext != 0) // an extension exists { /* - if (PackerFormatConfig.PackIsArchive(f->Name)) // is it an archive which we can process? + if (PackerFormatConfig.PackIsArchive(f->Name)) // is it an archive that we can process? { f->Association = TRUE; f->Archive = TRUE; @@ -1516,11 +1516,11 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) // preparing for loading of icons IconCacheValid = FALSE; - MSG msg; // need to remove any WM_USER_ICONREADING_END, which would set IconCacheValid = TRUE + MSG msg; // remove any pending WM_USER_ICONREADING_END that would set IconCacheValid = TRUE while (PeekMessage(&msg, HWindow, WM_USER_ICONREADING_END, WM_USER_ICONREADING_END, PM_REMOVE)) ; - // file/directories which don't have a simple icon will be addeed to icon-cache + // add files/directories without a simple icon to the icon cache { CALL_STACK_MESSAGE1("CFilesWindow::ReadDirectory::FS-icons-from-plugin"); @@ -1532,10 +1532,10 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) BOOL isDir = i < FSDirs->Count; CFileData* f = (isDir ? &FSDirs->At(i) : &FSFiles->At(i - FSDirs->Count)); - // need a pointer to CFileData for PluginFSDir, because moving occurs in Files and Dirs - // e.g. when sorting (Files and Dirs are arrays of CFileData, not (CFileData *), that's why these problems exist) + // a pointer to CFileData is needed for PluginFSDir, because items in Files and Dirs can move + // for example when sorting (Files and Dirs are arrays of CFileData, not `CFileData*`, which causes these problems) if (Configuration.NotHiddenSystemFiles && - (f->Hidden || //both Hidden a Attr jsou nulovane pokud jsou neplatne -> testy failnou + (f->Hidden || // both Hidden and Attr are zeroed when invalid -> tests fail (f->Attr & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)))) { // skip hidden file/directory continue; @@ -1564,8 +1564,8 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) memcpy(iconData.NameAndData, f->Name, f->NameLen); // name + memset(iconData.NameAndData + f->NameLen, 0, nameLen - f->NameLen); // zeroes alignment - iconData.SetFlag(0); // so far not loaded icon (plugin-icon) - // need to allocate space for bitmaps, can't be done in thread + iconData.SetFlag(0); // icon not loaded yet (plugin icon) + // bitmap storage must be allocated outside the thread iconData.SetIndex(IconCache->AllocIcon(NULL, NULL)); if (iconData.GetIndex() != -1) { @@ -1620,19 +1620,19 @@ BOOL CFilesWindow::ReadDirectory(HWND parent, BOOL isRefresh) return TRUE; } -// sorts array Dirs and Files independently on global variables +// sorts the Dirs and Files arrays independently of global variables void SortFilesAndDirectories(CFilesArray* files, CFilesArray* dirs, CSortType sortType, BOOL reverseSort, BOOL sortDirsByName) { CALL_STACK_MESSAGE1("SortDirectoryAux()"); - // CAUTION: must correspond to sort-code in RefreshDirectory, ChangeSortType and CompareDirectories !!! + // CAUTION: must match the sort code in RefreshDirectory, ChangeSortType, and CompareDirectories !! if (dirs->Count > 0) { BOOL hasRoot = (dirs->At(0).NameLen == 2 && dirs->At(0).Name[0] == '.' && dirs->At(0).Name[1] == '.'); // root directory int firstIndex = hasRoot ? 1 : 0; - if (dirs->Count - firstIndex > 1) // if there's one item only, there's nothing to sort + if (dirs->Count - firstIndex > 1) // if there is only one item, there is nothing to sort { switch (sortType) { @@ -1717,7 +1717,7 @@ BOOL IsWin64RedirectedDirAux(const char* subDir, const char* redirectedDir, cons if (h != INVALID_HANDLE_VALUE) { HANDLES(FindClose(h)); - return FALSE; // this is not just a pseudo-directory, there is a directory with the same name, which means that e.g. context menu will work more or less normally + return FALSE; // this is not just a pseudo-directory; a directory with the same name exists there, which means that, for example, the context menu will work almost normally } } @@ -1806,7 +1806,7 @@ BOOL AddWin64RedirectedDirAux(const char* path, const char* subDir, const char* if (StrICmp(dirs->At(i).Name, redirectedDirLastComp) == 0) { if (dirs->At(i).IsLink) - return FALSE; // this redirected-dir is already added + return FALSE; // this redirected directory has already been added deleteIndex = i; break; } @@ -1838,7 +1838,7 @@ BOOL AddWin64RedirectedDirAux(const char* path, const char* subDir, const char* lstrcpyn(fileData->cFileName, redirectedDirLastComp, MAX_PATH); fileData->cAlternateFileName[0] = 0; - if (CutDirectory(findPath)) // find out if there's a directory with the same name as redirected-dir on the disk (it does not need to be in the 'dirs' array, e.g. because of the command "Hide Selected Names") + if (CutDirectory(findPath)) // Check whether a directory with the same name as redirected-dir exists on disk (it may not be in the 'dirs' array, e.g. due to the "Hide Selected Names" command) { WIN32_FIND_DATA fd; h = HANDLES_Q(FindFirstFile(findPath, &fd)); @@ -1942,7 +1942,7 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch UpdateWindow(MainWindow->HWindow); if (newDir != NULL) lstrcpyn(path, newDir, 2 * MAX_PATH); - else // focus and top-index setting won't be done for path from dialog + else // do not set focus and top-index for a path from the dialog { suggestedTopIndex = -1; suggestedFocusName = NULL; @@ -1952,7 +1952,7 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch char* fsUserPart; if (!sendDirectlyToPluginLocal && IsPluginFSPath(path, fsName, (const char**)&fsUserPart)) { - if (strlen(fsUserPart) >= MAX_PATH) // plugins do not count with longer path + if (strlen(fsUserPart) >= MAX_PATH) // plugins do not support longer paths { sprintf(errBuf, LoadStr(IDS_PATHERRORFORMAT), path, LoadStr(IDS_TOOLONGPATH)); SalMessageBox(HWindow, errBuf, LoadStr(IDS_ERRORCHANGINGDIR), @@ -1963,7 +1963,7 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch EndStopRefresh(); // snooper will be started again if (failReason != NULL) *failReason = CHPPFR_INVALIDPATH; - return FALSE; // we're finished, it can't be repeated + return FALSE; // cannot retry, returning failure } goto CHANGE_AGAIN; } @@ -1996,7 +1996,7 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch // which would be able to list the path (so that a new FS is not opened unnecessarily) int fsNameIndexDummy; BOOL convertPathToInternalDummy = FALSE; - if (!Is(ptPluginFS) || // FS interface in the panel cannot list the path (ChangePathToPluginFS opens a new FS) + if (!Is(ptPluginFS) || // the panel's FS interface cannot display this path (ChangePathToPluginFS opens a new FS) !IsPathFromActiveFS(fsName, fsUserPart, fsNameIndexDummy, convertPathToInternalDummy)) { CDetachedFSList* list = MainWindow->DetachedFSList; @@ -2059,7 +2059,7 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch EndStopRefresh(); // snooper will be started again if (failReason != NULL) *failReason = CHPPFR_INVALIDPATH; - return FALSE; // finished, cannot be repeated + return FALSE; // Cannot continue; retry is not possible } goto CHANGE_AGAIN; } @@ -2070,13 +2070,13 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch (path[0] != 0 && path[1] == ':' || // X: type paths (path[0] == '/' || path[0] == '\\') && (path[1] == '/' || path[1] == '\\') || // UNC paths Is(ptDisk) || Is(ptZIPArchive))) // disk+archive of the relative path - { // this is a disk path (absolute or relative) - turn all '/' to '\\' + remove duplicated '\\' + { // disk path (absolute or relative): convert all '/' to '\\' and remove duplicate '\\' SlashesToBackslashesAndRemoveDups(path); } int errTextID; const char* text = NULL; // caution: textFailReason must be set - int textFailReason = CHPPFR_INVALIDPATH; // if text != NULL, it contains the code of error which occurred + int textFailReason = CHPPFR_INVALIDPATH; // if text != NULL, textFailReason contains the error code char curPath[2 * MAX_PATH]; curPath[0] = 0; if (sendDirectlyToPluginLocal) @@ -2155,7 +2155,7 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch EndStopRefresh(); // snooper will be started again if (failReason != NULL) *failReason = CHPPFR_INVALIDPATH; - return FALSE; // finished, cannot be repeated + return FALSE; // done, cannot retry } goto CHANGE_AGAIN; // show the path in dialog again, so that the user can correct it } @@ -2181,7 +2181,7 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch EndStopRefresh(); // snooper will be started again if (failReason != NULL) *failReason = CHPPFR_INVALIDPATH; - return FALSE; // finished, cannot be repeated + return FALSE; // stop here, cannot retry } goto CHANGE_AGAIN; } @@ -2207,7 +2207,7 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch copyLen = (int)strlen(copy); if (copyLen >= MAX_PATH) { - if (*end != 0 && !SalPathAppend(copy, end + 1, 2 * MAX_PATH)) // if the so far processed part of the path is enlengthened and the rest of the path does not fit, we will use the original form of the path + if (*end != 0 && !SalPathAppend(copy, end + 1, 2 * MAX_PATH)) // if extending the part of the path processed so far leaves no room for the rest, use the original form of the path strcpy(copy, path); text = LoadStr(IDS_TOOLONGPATH); textFailReason = CHPPFR_INVALIDPATH; @@ -2235,7 +2235,7 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch err = GetLastError(); if (err != ERROR_FILE_NOT_FOUND && err != ERROR_PATH_NOT_FOUND && err != ERROR_BAD_PATHNAME && err != ERROR_INVALID_NAME) - { // if there's chance that the path contains a directory to which we don't have access (we will try if there are other components of the path accessible) + { // If the path may contain a directory we cannot access (try whether later path components are accessible) DWORD firstErr = err; char* firstCopyEnd = st + strlen(st); while (*end != 0) @@ -2246,7 +2246,7 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch memcpy(st, s, end - s); st[end - s] = 0; s = end; - if ((int)strlen(copy) >= MAX_PATH) // too long path, we're finished... + if ((int)strlen(copy) >= MAX_PATH) // Path is too long, abort. { h = INVALID_HANDLE_VALUE; break; @@ -2255,14 +2255,14 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch { h = HANDLES_Q(FindFirstFile(copy, &find)); if (h != INVALID_HANDLE_VALUE) - break; // we've found an accessible component, continuing... + break; // found an accessible component, continue err = GetLastError(); if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND || err == ERROR_BAD_PATHNAME || err == ERROR_INVALID_NAME) - break; // an error in the path, we're finished... + break; // path error, stopping... } } - if (*end == 0 && h == INVALID_HANDLE_VALUE) // another accessible component not found, we will try if the current path can be listed + if (*end == 0 && h == INVALID_HANDLE_VALUE) // no other accessible component found; try listing the current path { if ((int)strlen(copy) < MAX_PATH && SalPathAppend(copy, "*.*", MAX_PATH + 10)) { @@ -2281,7 +2281,7 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch } } } - if (h == INVALID_HANDLE_VALUE) // accessible part of the path not found, we will report the first found error + if (h == INVALID_HANDLE_VALUE) // no accessible part of the path was found; report the first error encountered { err = firstErr; *firstCopyEnd = 0; @@ -2307,7 +2307,7 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch { HANDLES(FindClose(h)); int len2 = (int)strlen(find.cFileName); // must fit (only the size of letters is changed - result of FindFirstFile) - if ((int)strlen(st + 1) != len2) // it does e.g. for "aaa " returns "aaa", reproduce: Paste (text without quotes): " " %TEMP%\aaa " " + if ((int)strlen(st + 1) != len2) // for example, for "aaa " it returns "aaa"; reproduce: Paste (text without outer quotes): " " %TEMP%\aaa " " { TRACE_E("CFilesWindow::ChangeDir(): unexpected situation: FindFirstFile returned name with " "different length: \"" @@ -2327,9 +2327,9 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch { // file -> is it an archive? if (PackerFormatConfig.PackIsArchive(copy)) { - if ((int)strlen(*end != 0 ? end + 1 : end) >= MAX_PATH) // too long path in archive + if ((int)strlen(*end != 0 ? end + 1 : end) >= MAX_PATH) // path in the archive is too long { - if (!SalPathAppend(copy, end + 1, 2 * MAX_PATH)) // if the archive name is enlengthened and the rest of the path does not fit, we will use the original form of the path + if (!SalPathAppend(copy, end + 1, 2 * MAX_PATH)) // if extending the archive name would leave no room for the path inside the archive, use the original form of the path strcpy(copy, path); text = LoadStr(IDS_TOOLONGPATH); textFailReason = CHPPFR_INVALIDPATH; @@ -2361,7 +2361,7 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch char* name; char shortenedPath[MAX_PATH]; strcpy(shortenedPath, copy); - if (*end == 0 && CutDirectory(shortenedPath, &name)) // when the path does not end with '\\' (path to file) + if (*end == 0 && CutDirectory(shortenedPath, &name)) // if the path does not end with '\\' (it is a file path) { // change of the path to absolute windows path + focus to the file ChangePathToDisk(HWindow, shortenedPath, -1, name, NULL, TRUE, FALSE, FALSE, failReason); @@ -2369,7 +2369,7 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch EndStopRefresh(); // snooper will be started again if (failReason != NULL && *failReason == CHPPFR_SUCCESS) *failReason = CHPPFR_FILENAMEFOCUSED; - return FALSE; // listing another path (file name is cut) + return FALSE; // browse a different path (without the file name) } else { @@ -2458,7 +2458,7 @@ BOOL CFilesWindow::ChangeDir(const char* newDir, int suggestedTopIndex, const ch EndStopRefresh(); // snopper will be started again if (failReason != NULL) *failReason = textFailReason; - return FALSE; // finished, cannot be repeated + return FALSE; // Stop here; cannot retry. } goto CHANGE_AGAIN; } @@ -2633,7 +2633,7 @@ void CFilesWindow::ChangeDrive(char drive) } } - if (ifaceForFS != NULL) // post-cmd from context menu of active/detached FS + if (ifaceForFS != NULL) // post-cmd from the context menu of the active or detached FS { ifaceForFS->ExecuteChangeDrivePostCommand(PANEL_SOURCE, postCmd, postCmdParam); } @@ -2641,19 +2641,19 @@ void CFilesWindow::ChangeDrive(char drive) } case drvtPluginFSInOtherPanel: - return; // illegal action (FS from other panel cannot be given to active panel) + return; // invalid action (an FS from the other panel cannot be assigned to the active panel) case drvtPluginCmd: { const char* dllName = (const char*)driveTypeParam; CPluginData* data = Plugins.GetPluginData(dllName); - if (data != NULL) // plugin exists, we can execute the command + if (data != NULL) // plugin exists, execute the command { - if (!fromContextMenu) // FS item command + if (!fromContextMenu) // command for an FS item { data->ExecuteChangeDriveMenuItem(PANEL_SOURCE); } - else // post-cmd from context menu of FS item + else // post-command from the context menu of an FS item { data->GetPluginInterfaceForFS()->ExecuteChangeDrivePostCommand(PANEL_SOURCE, postCmd, postCmdParam); } @@ -2720,13 +2720,13 @@ void CFilesWindow::UpdateDriveIcon(BOOL check) { BOOL destroyIcon; HICON icon = GetPluginFS()->GetFSIcon(destroyIcon); - if (icon != NULL) // defined by plugin + if (icon != NULL) // defined by the plugin { DirectoryLine->SetDriveIcon(icon); if (destroyIcon) HANDLES(DestroyIcon(icon)); } - else // standard + else // default { icon = SalLoadIcon(HInstance, IDI_PLUGINFS, IconSizes[ICONSIZE_16]); DirectoryLine->SetDriveIcon(icon); diff --git a/src/fileswn4.cpp b/src/fileswn4.cpp index a28d08622..d501a5720 100644 --- a/src/fileswn4.cpp +++ b/src/fileswn4.cpp @@ -238,17 +238,17 @@ void CFilesWindow::DrawIcon(HDC hDC, CFileData* f, BOOL isDir, BOOL isItemUpDir, } } } - else // it's a file + else // file { int index; BOOL exceptions = *(DWORD*)lowerExtension == *(DWORD*)"scr" || // icons in the file, - *(DWORD*)lowerExtension == *(DWORD*)"pif" || // even though it isn't visible + *(DWORD*)lowerExtension == *(DWORD*)"pif" || // even though it is not visible in the Registry *(DWORD*)lowerExtension == *(DWORD*)"lnk"; // in the Registry - if (exceptions || Associations.GetIndex(lowerExtension, index)) // the extension has an icon (association) + if (exceptions || Associations.GetIndex(lowerExtension, index)) // the extension has an associated icon { if (!exceptions) - TransferAssocIndex = index; // remember the valid index in Associations + TransferAssocIndex = index; // store the valid index in Associations if (exceptions || Associations[index].GetIndex(iconSize) < 0) // dynamic icon (from the file) or a loaded static icon { // icon in the file int icon; @@ -316,7 +316,7 @@ void CFilesWindow::DrawIcon(HDC hDC, CFileData* f, BOOL isDir, BOOL isItemUpDir, if (!IconCache->GetIndex(NULL /*fileName*/, icon, &PluginData, f) || // the icon-thread isn't loading it IconCache->At(icon).GetFlag() != 1 && IconCache->At(icon).GetFlag() != 2 || // neither new nor old icon is loaded !IconCache->GetIcon(IconCache->At(icon).GetIndex(), &iconList, &iconListIndex)) // failed to obtain its icon - { // we will display a simple symbol from the plug-in + { // we will display a simple symbol from the plugin // the simple icon index will be obtained via the GetPluginIconIndex callback TransferFileData = f; TransferIsDir = isDir ? (isItemUpDir ? 2 : 1) : 0; @@ -495,9 +495,9 @@ void CFilesWindow::DrawBriefDetailedItem(HDC hTgtDC, int itemIndex, RECT* itemRe // TRACE_I("DrawingSmall itemIndex="<Ext[0] == 0 || f->Ext <= f->Name + 1) // empty value in the Ext column (exception for names like ".htaccess", which are shown in the Name column even though they look like extensions) TransferLen = 0; else { @@ -850,7 +850,7 @@ void CFilesWindow::DrawBriefDetailedItem(HDC hTgtDC, int itemIndex, RECT* itemRe ExtTextOut(hDC, r.left, y, ETO_OPAQUE, &adjR, "", 0, NULL); // just clearing else { - if (column->FixedWidth == 1) // NarrowedNameColumn does not apply here (not Name column) + if (column->FixedWidth == 1) // NarrowedNameColumn does not apply here (this is not the Name column) { int fitChars; // for fixed-width columns we must check whether the entire text fits @@ -954,7 +954,7 @@ void CFilesWindow::DrawBriefDetailedItem(HDC hTgtDC, int itemIndex, RECT* itemRe DrawFocusRect(hDC, &r, (f->Selected == 1), Parent->EditMode); /* - // for debugging the dual cursor issue we need to distinguish normal focus and drop target + // to debug the two-cursor bug, we need to distinguish normal focus from the drop target if (itemIndex == DropTargetIndex) { MoveToEx(hDC, r.left, r.top + 3, NULL); @@ -1002,7 +1002,7 @@ void SplitText(HDC hDC, const char* text, int textLen, int* maxWidth, char* out2, int* out2Len, int* out2Width) { SIZE sz; - // measure the width of every character + // measure the widths of all characters GetTextExtentExPoint(hDC, text, textLen, 0, NULL, DrawItemAlpDx, &sz); if (sz.cx > *maxWidth) @@ -1017,7 +1017,7 @@ void SplitText(HDC hDC, const char* text, int textLen, int* maxWidth, int maxW = *maxWidth; int w = 0; int index = 0; - while (index < maxW) // this condition should not be applied + while (index < maxW) // this condition should not apply { if (text[index] == ' ') lastSpaceIndex = index; @@ -1061,7 +1061,7 @@ void SplitText(HDC hDC, const char* text, int textLen, int* maxWidth, if (*out1Len >= 3) memmove(out1 + *out1Len - 3, "...", 3); - // look for a space where we can continue to the next line + // look for a space where we can break to the next line while (index < textLen) { if (text[index++] == ' ') @@ -1180,7 +1180,7 @@ void CFilesWindow::DrawIconThumbnailItem(HDC hTgtDC, int itemIndex, RECT* itemRe BOOL isItemFocusedOrEditMode = FALSE; if (FocusedIndex == itemIndex) // drawing the cursor { - if (FocusVisible || Parent->EditMode && Parent->GetActivePanel() == this) // switched in the command-line + if (FocusVisible || Parent->EditMode && Parent->GetActivePanel() == this) // switched to the command line isItemFocusedOrEditMode = TRUE; } @@ -1295,7 +1295,7 @@ void CFilesWindow::DrawIconThumbnailItem(HDC hTgtDC, int itemIndex, RECT* itemRe // outer rectangle from which we clear towards the inner one RECT outerRect = rect; - // rectangle we will clear to + // rectangle towards which we will clear RECT innerRect; BOOL thickFrame = FALSE; // for Thumbnails only -- should the frame be doubled? if (GetViewMode() == vmThumbnails) @@ -1485,7 +1485,7 @@ void CFilesWindow::DrawIconThumbnailItem(HDC hTgtDC, int itemIndex, RECT* itemRe y = outerRect.top + 4; } - // inner rectangle we clear towards + // inner rectangle towards which we clear RECT r; r.left = rect.left + (itemWidth - maxWidth) / 2 - 2; r.top = y - 2; @@ -1495,10 +1495,10 @@ void CFilesWindow::DrawIconThumbnailItem(HDC hTgtDC, int itemIndex, RECT* itemRe r.bottom += FontCharHeight; // clear the background around the text - if ((drawFlags & DRAWFLAG_MASK) == 0) // when drawing the mask (b&w), the background color must not be painted + if ((drawFlags & DRAWFLAG_MASK) == 0) // When drawing the mask (B&W), do not draw the background color FillIntersectionRegion(hDC, &outerRect, &r); - if (drawFocusFrame) // if there won't be a frame displayed, reduce the area by it + if (drawFocusFrame) // if the focus frame will be drawn, shrink the area for it InflateRect(&r, -1, -1); int oldRTop = r.top; @@ -1556,7 +1556,7 @@ void TruncateSringToFitWidth(HDC hDC, char* buffer, int* bufferLen, int maxTextW // search from the end for the character after which we can copy "..." and it fits in the column while (fitChars > 0 && DrawItemAlpDx[fitChars - 1] + TextEllipsisWidth > maxTextWidth) fitChars--; - // copy part of the original string to another buffer + // copy part of the original string within the buffer if (fitChars > 0) { // and append "..." @@ -1739,9 +1739,9 @@ void CFilesWindow::DrawTileItem(HDC hTgtDC, int itemIndex, RECT* itemRect, DWORD // TRACE_I("DrawTileItem itemIndex="<Count; i++) // ".." cannot be selected, so the check would be unnecessary { if (Dirs->At(i).Selected) selectedDirs++; @@ -651,7 +651,7 @@ void CFilesWindow::ChangeAttr(BOOL setCompress, BOOL compressed, BOOL setEncrypt // raise the thread priority again, the operation has finished SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); - if (success) // success -> unselect + if (success) // On success, clear the selection { SetSel(FALSE, -1, TRUE); // explicit repaint PostMessage(HWindow, WM_USER_SELCHANGED, 0, 0); // selection change notify @@ -728,7 +728,7 @@ void CFilesWindow::ViewFile(char* name, BOOL altView, DWORD handlerID, int enumF BOOL addToHistory = name != NULL; // if viewing/editing from the panel, obtain the full long name - BOOL useDiskCache = FALSE; // TRUE only for ZIP - uses disk-cache + BOOL useDiskCache = FALSE; // TRUE only for ZIP; uses the disk cache BOOL arcCacheCacheCopies = TRUE; // cache copies in disk-cache unless the archiver plugin requests otherwise char dcFileName[3 * MAX_PATH + 50]; // ZIP: name for disk-cache if (name == NULL) @@ -768,7 +768,7 @@ void CFilesWindow::ViewFile(char* name, BOOL altView, DWORD handlerID, int enumF if (strlen(f->DosName) + (s - path) < MAX_PATH) { strcpy(s, f->DosName); - if (SalGetFileAttributes(path) == 0xffffffff) // still error -> revert to the long name + if (SalGetFileAttributes(path) == 0xffffffff) // still an error -> revert to the long name { if ((s - path) + f->NameLen < MAX_PATH) strcpy(s, f->Name); @@ -805,7 +805,7 @@ void CFilesWindow::ViewFile(char* name, BOOL altView, DWORD handlerID, int enumF { format--; int index = PackerFormatConfig.GetUnpackerIndex(format); - if (index < 0) // view: is the processing internal (plugin)? + if (index < 0) // view: is this handled internally by a plugin? { CPluginData* data = Plugins.Get(-index - 1); if (data != NULL) @@ -909,7 +909,7 @@ void CFilesWindow::ViewFile(char* name, BOOL altView, DWORD handlerID, int enumF { if (Is(ptPluginFS)) { - if (GetPluginFS()->NotEmpty() && // FS is fine and supports view-file + if (GetPluginFS()->NotEmpty() && // FS is valid and supports ViewFile GetPluginFS()->IsServiceSupported(FS_SERVICE_VIEWFILE)) { // lower the thread priority to "normal" (so the operations don't overload the machine) @@ -921,7 +921,7 @@ void CFilesWindow::ViewFile(char* name, BOOL altView, DWORD handlerID, int enumF // raise the thread priority again, the operation has finished SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); } - return; // view on the FS is already done + return; // viewing on the FS is already handled } else { @@ -948,7 +948,7 @@ void CFilesWindow::ViewFile(char* name, BOOL altView, DWORD handlerID, int enumF { DiskCache.AssignName(dcFileName, lock, lockOwner, arcCacheCacheCopies ? crtCache : crtDirect); } - else // viewer didn't open or has no "lock" object - try leaving the file in disk-cache + else // viewer did not open or has no "lock" object; try to at least keep the file in the disk cache { DiskCache.ReleaseName(dcFileName, arcCacheCacheCopies); } @@ -1038,17 +1038,17 @@ BOOL ViewFileInt(HWND parent, const char* name, BOOL altView, DWORD handlerID, B if (viewer != NULL && viewer->ViewerType != VIEWER_EXTERNAL && viewer->ViewerType != VIEWER_INTERNAL) - { // plug-in viewers only + { // plugin viewers only CPluginData* plugin = Plugins.Get(-viewer->ViewerType - 1); if (plugin != NULL && plugin->SupportViewer) { if (!plugin->CanViewFile(name)) - continue; // try to find another viewer, this one won't do it + continue; // try to find another viewer; this one cannot view the file } else TRACE_E("Unexpected error (before CanViewFile) in (Alt)ViewerMasks (invalid ViewerType)."); } - break; // everything is fine, open the viewer + break; // Everything is OK, proceed to open the viewer } } else @@ -1186,7 +1186,7 @@ BOOL ViewFileInt(HWND parent, const char* name, BOOL altView, DWORD handlerID, B break; } - default: // plug-ins + default: // plugins { HANDLE lockAux = NULL; BOOL lockOwnerAux = FALSE; @@ -1292,7 +1292,7 @@ void CFilesWindow::EditFile(char* name, DWORD handlerID) if (strlen(f->DosName) + (s - path) < MAX_PATH) { strcpy(s, f->DosName); - if (SalGetFileAttributes(path) == 0xffffffff) // still error -> revert to the long name + if (SalGetFileAttributes(path) == 0xffffffff) // still an error -> revert to the long name { if ((s - path) + f->NameLen < MAX_PATH) strcpy(s, f->Name); @@ -1508,8 +1508,8 @@ void CFilesWindow::EditNewFile() if (first) { const char* dot = strrchr(path, '.'); - if (dot != NULL && dot > path) // although ".cvspass" is an extension in Windows, Explorer selects the entire name, so we do the same - // if (dot != NULL) + if (dot != NULL && dot > path) // although ".cvspass" counts as an extension in Windows, Explorer selects the whole name, so we do the same +// if (dot != NULL) selectionEnd = (int)(dot - path); dlg.SetSelectionEnd(selectionEnd); first = FALSE; // after an error we get the full file name, so we select it all @@ -1585,7 +1585,7 @@ void CFilesWindow::EditNewFile() else break; } - EndStopRefresh(); // snooper will start again now + EndStopRefresh(); // resume refresh monitoring } // fills the popup based on available viewers @@ -1706,7 +1706,7 @@ BOOL CFilesWindow::FillViewWithData(TDirectArray* items) void CFilesWindow::OnViewFileWith(int index) { - BeginStopRefresh(); // snooper takes a break + BeginStopRefresh(); // suspend refresh monitoring // get the list of viewer indexes TDirectArray items(50, 10); @@ -1869,7 +1869,7 @@ void CFilesWindow::EditFileWith(char* name, HWND hMenuParent, const POINT* menuP *handlerID = masks->At(index)->HandlerID; } - EndStopRefresh(); // snooper will start again now + EndStopRefresh(); // refresh watching resumes now } BOOL FileNameInvalidForManualCreate(const char* path) @@ -1956,7 +1956,7 @@ void CFilesWindow::CreateDir(CFilesWindow* target) // restore DefaultDir MainWindow->UpdateDefaultDir(MainWindow->GetActivePanel() == this); - if (Is(ptDisk)) // create directory on disk + if (Is(ptDisk)) // create a directory on disk { CTruncatedString subject; subject.Set(LoadStr(IDS_CREATEDIRECTORY_TEXT), NULL); @@ -1974,10 +1974,10 @@ void CFilesWindow::CreateDir(CFilesWindow* target) // for disk paths we flip '/' to '\\' and eliminate duplicate backslashes SlashesToBackslashesAndRemoveDups(path); - // clean the name from undesirable characters at the beginning and end - // we do this only for the last component; the previous ones already exist and it doesn't matter - // (the system handles it) or they are checked during creation and an error is shown - // (we don't clean them, we let the user do some work, it's easy enough) + // clean invalid characters from the beginning and end of the name + // only for the last component; the previous ones either already exist and are handled + // by the system, or they are checked during creation and an error is shown if needed + // (we do not sanitize them on our side, so the user still has to correct them) char* lastCompName = strrchr(path, '\\'); MakeValidFileName(lastCompName != NULL ? lastCompName + 1 : path); @@ -2061,7 +2061,7 @@ void CFilesWindow::CreateDir(CFilesWindow* target) newName[0] = 0; BOOL cancel = FALSE; BOOL ret = GetPluginFS()->CreateDir(GetPluginFS()->GetPluginFSName(), 1, HWindow, newName, cancel); - if (!cancel) // not a cancel of the operation + if (!cancel) // the operation was not canceled { if (!ret) { @@ -2186,7 +2186,7 @@ void CFilesWindow::RenameFileInternal(CFileData* f, const char* formatedFileName } else { - if (StrICmp(path, tgtPath) != 0 && // if it isn't just change-case + if (StrICmp(path, tgtPath) != 0 && // if this is not just a case change (err == ERROR_FILE_EXISTS || // check whether it's only rewriting the DOS name of the file err == ERROR_ALREADY_EXISTS)) { @@ -2196,7 +2196,7 @@ void CFilesWindow::RenameFileInternal(CFileData* f, const char* formatedFileName { HANDLES(FindClose(find)); const char* tgtName = SalPathFindFileName(tgtPath); - if (StrICmp(tgtName, data.cAlternateFileName) == 0 && // match only for DOS name + if (StrICmp(tgtName, data.cAlternateFileName) == 0 && // match only for the DOS name StrICmp(tgtName, data.cFileName) != 0) // (full name differs) { // rename ("clean up") the file/directory with the conflicting DOS name to a temporary 8.3 name (no extra DOS name needed) @@ -2362,7 +2362,7 @@ void CFilesWindow::RenameFile(int specialIndex) &subject, IDD_RENAMEDIALOG, Configuration.QuickRenameHistory, QUICKRENAME_HISTORY_SIZE, FALSE); - if (Is(ptDisk)) // rename on disk + if (Is(ptDisk)) // renaming on disk { #ifndef _WIN64 if (Windows64Bit && isDir) @@ -2454,7 +2454,7 @@ void CFilesWindow::RenameFile(int specialIndex) // if we selected an item, we deselect it again UnselectItemWithName(temporarySelected); - if (!cancel) // not a cancel of the operation + if (!cancel) // the operation was not canceled { if (!ret) { @@ -2625,7 +2625,7 @@ void CFilesWindow::QuickRenameBegin(int index, const RECT* labelRect) else subDir = FALSE; if (index == 0 && subDir) - return; // we do not work with ".." + return; // skip ".." CFileData* f = NULL; BOOL isDir = index < Dirs->Count; @@ -2762,18 +2762,18 @@ BOOL CFilesWindow::HandeQuickRenameWindowKey(WPARAM wParam) char newName[MAX_PATH]; GetWindowText(hWnd, newName, MAX_PATH); - // lower the thread priority to "normal" (so operations don't overload the machine) + // lower the current thread priority to "normal" (so the operation does not put too much load on the machine) SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); BOOL tryAgain = FALSE; BOOL mayChange = FALSE; if (Is(ptDisk)) { - // If this is an in-place rename and the user didn't change the name, we shouldn't - // attempt to rename it because the user might be on a CD-ROM or other read-only disk - // and we would display the "Access is denied" error. The user has no mouse option - // to cancel the operation, so they would have to press Escape. - // Explorer behaves this way now. + // If this is an in-place rename and the user did not change the name, we should not + // attempt to rename it because the user may be on a CD-ROM or another read-only disk, + // and we would then display an "Access is denied" error. The user cannot cancel the + // operation with the mouse, so they would have to press Escape. + // Explorer behaves this way as well. if (strcmp(f->Name, newName) != 0) RenameFileInternal(f, newName, &mayChange, &tryAgain); } diff --git a/src/fileswn6.cpp b/src/fileswn6.cpp index 7c6173976..968c965fb 100644 --- a/src/fileswn6.cpp +++ b/src/fileswn6.cpp @@ -80,7 +80,7 @@ void CFilesWindow::Activate(BOOL shares) else // path appears to be OK { if (!AutomaticRefresh && !GetNetworkDrive() || // manual disk refresh (excluding network drives) - GetNetworkDrive() && // for network drives, we refresh on every + GetNetworkDrive() && // for network drives, refresh every time !Configuration.DrvSpecRemoteDoNotRefreshOnAct || // activation unless explicitly disabled (used to handle Samba behavior) shares && !GetNetworkDrive() || // restore shares (not relevant for network drives) InactiveRefreshTimerSet) // delayed refresh in inactive window must be executed immediately upon activation @@ -106,7 +106,7 @@ void CFilesWindow::Activate(BOOL shares) } else { - if (Is(ptPluginFS)) // plug-in FS: send FSE_ACTIVATEREFRESH so the plug-in can refresh itself + if (Is(ptPluginFS)) // plugin FS: dispatch FSE_ACTIVATEREFRESH so the plugin can refresh itself { if (!SkipOneActivateRefresh) PostMessage(HWindow, WM_USER_REFRESH_PLUGINFS, 0, 0); @@ -236,7 +236,7 @@ DWORD GetPathFlagsForCopyOp(const char* path, DWORD netFlag, DWORD fixedFlag) else if (drvType == DRIVE_REMOVABLE && UpperCase[path[0]] >= 'A' && UpperCase[path[0]] <= 'Z' && path[1] == ':' && GetDriveFormFactor(UpperCase[path[0]] - 'A' + 1) == 0 /* not a floppy */) { - return fixedFlag; // removable but not a floppy, e.g. USB stick or a camera via USB (e.g. FZ45) - we treat them as fixed, they're fast enough + return fixedFlag; // removable but not a floppy, e.g. a USB stick or a camera over USB (e.g. FZ45) - treated as fixed because they are fast enough } } return 0; @@ -296,7 +296,7 @@ BOOL CFilesWindow::MoveFiles(const char* source, const char* target, const char* HasTheSameRootPath(source, target)) // + within the same drive { UINT sourceType = DRIVE_REMOTE; - if (source[0] != '\\') // not a UNC path (that is always "remote") + if (source[0] != '\\') // not a UNC path (UNC is always "remote") { char root[4] = " :\\"; root[0] = source[0]; @@ -304,7 +304,7 @@ BOOL CFilesWindow::MoveFiles(const char* source, const char* target, const char* } if (sourceType == DRIVE_REMOTE) // network drive - { // detect Novell disks - fast-directory-move doesn't work on them + { // Detect Novell network drives - fast directory moves do not work on them if (IsNOVELLDrive(source)) fastDirectoryMove = Configuration.NetwareFastDirMove; } @@ -660,7 +660,7 @@ BOOL CFilesWindow::BuildScriptMain2(COperations* script, BOOL copy, char* target srcAndTgtPathsFlags |= GetPathFlagsForCopyOp(lastSourcePath, OPFL_SRCPATH_IS_NET, OPFL_SRCPATH_IS_FAST); lastSourcePath[s - fileName] = 0; } - if (IsTheSamePath(sourcePath, targetPath) && // "Copy of..." is done only if paths match + if (IsTheSamePath(sourcePath, targetPath) && // "Copy of..." is used only when the paths match makeCopyOfName) // check if we will need a "Copy of..." name { strcpy(targetName, s + 1); // copy the proposed full target name into targetPath @@ -711,7 +711,7 @@ BOOL CFilesWindow::BuildScriptMain2(COperations* script, BOOL copy, char* target else { numBeg = NULL; - break; // "(number)" not present + break; // "(number)" not found } } @@ -1045,9 +1045,9 @@ void CFilesWindow::DropCopyMove(BOOL copy, char* targetPath, CCopyMoveData* data EnableWindow(MainWindow->HWindow, TRUE); DestroySafeWaitWindow(); - // if Salamander is active, call SetFocus on the remembered window (SetFocus doesn't work - // when the main window is disabled - after reactivation/activation of the disabled main window - // the active panel lacks focus) + // if Salamander is active, call SetFocus on the remembered window (SetFocus does not work + // when the main window is disabled; after deactivation and reactivation of the disabled main window, + // the active panel does not have focus) HWND hwnd = GetForegroundWindow(); while (hwnd != NULL && hwnd != MainWindow->HWindow) hwnd = GetParent(hwnd); @@ -1062,7 +1062,7 @@ void CFilesWindow::DropCopyMove(BOOL copy, char* targetPath, CCopyMoveData* data BOOL occupiedSpTooBig = script->OccupiedSpace != CQuadWord(0, 0) && script->BytesPerCluster != 0 && // we have disk information script->OccupiedSpace > script->FreeSpace && - !IsSambaDrivePath(targetPath); // Samba returns an invalid cluster size, so we can rely only on TotalFileSize + !IsSambaDrivePath(targetPath); // Samba returns a bogus cluster size, so we can only rely on TotalFileSize if (occupiedSpTooBig || script->BytesPerCluster != 0 && // we have disk information script->TotalFileSize > script->FreeSpace) @@ -1242,7 +1242,7 @@ BOOL CFilesWindow::BuildScriptMain(COperations* script, CActionType type, BOOL targetIsFAT32 = FALSE; CTargetPathState targetPathState = tpsUnknown; DWORD srcAndTgtPathsFlags = 0; // flags only for Copy and Move - if (type == atMove || type == atCopy) // outside Copy and Move it makes no sense to check + if (type == atMove || type == atCopy) // It makes no sense to check this outside Copy and Move { sourceSupADS = (filterCriteria == NULL || !filterCriteria->IgnoreADS) && IsPathOnVolumeSupADS(sourcePath, NULL); @@ -1269,7 +1269,7 @@ BOOL CFilesWindow::BuildScriptMain(COperations* script, CActionType type, char dummy2[MAX_PATH]; if (MyGetVolumeInformation(targetPath, NULL, NULL, NULL, NULL, 0, NULL, &dummy1, &flags, dummy2, MAX_PATH) && (flags & FS_PERSISTENT_ACLS) == 0) - { // wants to copy permissions, but the target path doesn't support them, so we inform the user (the API function for setting security doesn't report any errors — which is poor design) + { // permissions are to be copied, but the target path does not support them, so inform the user (the API function for setting security reports no errors) int res = SalMessageBox(HWindow, LoadStr(IDS_ACLNOTSUPPORTEDONTGTPATH), LoadStr(IDS_QUESTION), MB_YESNO | MB_ICONQUESTION | MSGBOXEX_ESCAPEENABLED); UpdateWindow(MainWindow->HWindow); @@ -1313,7 +1313,7 @@ BOOL CFilesWindow::BuildScriptMain(COperations* script, CActionType type, if (selCount > 0 || oneFile != NULL) { - if (type == atMove || type == atCopy) // outside Copy and Move it makes no sense to check + if (type == atMove || type == atCopy) // checking this only makes sense for Copy and Move { DWORD d1, d2, d3, d4; if (MyGetDiskFreeSpace(targetPath, &d1, &d2, &d3, &d4)) @@ -1335,7 +1335,7 @@ BOOL CFilesWindow::BuildScriptMain(COperations* script, CActionType type, } i++; // oneFile points to the selected or caret item in the filebox - if (oneFile->Attr & FILE_ATTRIBUTE_DIRECTORY) // jde o ptDisk + if (oneFile->Attr & FILE_ATTRIBUTE_DIRECTORY) // this is ptDisk { if (subDirectories) { @@ -1380,7 +1380,7 @@ BOOL CFilesWindow::BuildScriptMain(COperations* script, CActionType type, } else { - if ((op.TargetName = BuildName(sourcePath, oneFile->Name)) == NULL) // too long name already handled by previous condition + if ((op.TargetName = BuildName(sourcePath, oneFile->Name)) == NULL) // the previous condition already handles names that are too long { free(op.SourceName); SetCurrentDirectoryToSystem(); @@ -1492,7 +1492,7 @@ void GetADSStreamsNames(char* listBuf, int bufSize, char* fileName, BOOL isDir) free(streamNames); } - if (bufSize > 0 && (StrICmp(listBuf, "Zone.Identifier") == 0 || // this stream is automatically created by XP SP2 and should be ignored, so we won't bother the user with it + if (bufSize > 0 && (StrICmp(listBuf, "Zone.Identifier") == 0 || // this stream is automatically created by Windows XP SP2 and should be ignored, so it is not shown to the user StrICmp(listBuf, "encryptable") == 0)) // this stream appears mostly on thumbs.db, nobody knows what it is, but Windows creates it, so we ignore it too { listBuf[0] = 0; @@ -1531,7 +1531,7 @@ BOOL CFilesWindow::BuildScriptDir(COperations* script, CActionType type, char* s else st = sourceEnd; if (st - sourcePath + strlen(dirName) >= MAX_PATH - 2) // -2 determined experimentally (longer paths cannot be listed) - { // data are on disk, which doesn't mean they can't exceed MAX_PATH + { // the data is on disk, which does not mean it cannot exceed MAX_PATH *sourceEnd = 0; // restoring original sourcePath _snprintf_s(text, _TRUNCATE, LoadStr(IDS_NAMEISTOOLONG), dirName, sourcePath); BOOL skip = TRUE; @@ -1544,8 +1544,8 @@ BOOL CFilesWindow::BuildScriptDir(COperations* script, CActionType type, char* s params.Caption = LoadStr(IDS_ERRORBUILDINGSCRIPT); params.Text = text; char aliasBtnNames[200]; - /* used by export_mnu.py script that generates salmenu.mnu for the Translator - we let the msgbox buttons resolve hotkey collisions by simulating that it is a menu + /* used by the export_mnu.py script, which generates salmenu.mnu for the Translator + for msgbox buttons, let hotkey collisions be resolved by simulating a menu MENU_TEMPLATE_ITEM MsgBoxButtons[] = { {MNTT_PB, 0 @@ -1588,9 +1588,9 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = char* s2; if (mapName == NULL) { - // Petr: a bit of a hack: the *.* mask doesn't produce a copy of the source name, which is a problem when copying - // directories with invalid names, e.g. "c ..." + "*.*" = "c ", so we'll help ourselves a bit and - // change the mask to NULL = a simple textual copy of the name + // Petr: a bit of a hack: the *.* mask does not create a copy of the source name, which is a problem when copying + // directories with invalid names, e.g. "c ..." + "*.*" = "c ", so the mask is changed + // to NULL, i.e. a simple textual copy of the name char* opMask = mask != NULL && strcmp(mask, "*.*") == 0 ? NULL : mask; s2 = MaskName(finalName, 2 * MAX_PATH + 200, dirName, opMask); if (opMask != NULL) @@ -1613,8 +1613,8 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = params.Caption = LoadStr(IDS_ERRORBUILDINGSCRIPT); params.Text = text; char aliasBtnNames[200]; - /* used by export_mnu.py script that generates salmenu.mnu for the Translator - we let the msgbox buttons resolve hotkey collisions by simulating that it is a menu + /* used by the export_mnu.py script, which generates salmenu.mnu for Translator + for message box buttons, hotkey collisions are resolved by simulating a menu MENU_TEMPLATE_ITEM MsgBoxButtons[] = { {MNTT_PB, 0 @@ -1674,7 +1674,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = int res = SalMessageBox(MainWindow->HWindow, text, LoadStr(IDS_QUESTION), MB_YESNOCANCEL | MB_ICONQUESTION); UpdateWindow(MainWindow->HWindow); - if (res == IDNO || res == IDCANCEL) // if CANCEL or NO was chosen, we end or skip the directory + if (res == IDNO || res == IDCANCEL) // if CANCEL or NO was chosen, stop or skip the directory { *sourceEnd = 0; // restoring sourcePath if (targetEnd != NULL) @@ -1754,7 +1754,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = { srcAndTgtPathsFlags &= ~(OPFL_SRCPATH_IS_NET | OPFL_SRCPATH_IS_FAST); srcAndTgtPathsFlags |= GetPathFlagsForCopyOp(sourcePath, OPFL_SRCPATH_IS_NET, OPFL_SRCPATH_IS_FAST); - if (targetPathState == tpsEncryptedExisting || targetPathState == tpsNotEncryptedExisting) // target directory exists, get to know its flags (otherwise inherit flags from the parent target directory) + if (targetPathState == tpsEncryptedExisting || targetPathState == tpsNotEncryptedExisting) // target directory exists, determine its flags (otherwise keep the flags from the parent target directory) { srcAndTgtPathsFlags &= ~(OPFL_TGTPATH_IS_NET | OPFL_TGTPATH_IS_FAST); srcAndTgtPathsFlags |= GetPathFlagsForCopyOp(targetPath, OPFL_TGTPATH_IS_NET, OPFL_TGTPATH_IS_FAST); @@ -1812,7 +1812,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = } dirCreated = TRUE; } - else // copying to a non-NTFS filesystem (prompt to discard ADS) + else // copying to a filesystem other than NTFS (prompt to drop ADS) { int res; if (ConfirmADSLossAll) @@ -1889,8 +1889,8 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = params.Caption = LoadStr(IDS_ERRORTITLE); params.Text = text; char aliasBtnNames[200]; - /* used by export_mnu.py script that generates salmenu.mnu for the Translator - we let the msgbox buttons resolve hotkey collisions by simulating that it is a menu + /* used by the export_mnu.py script that generates salmenu.mnu for the Translator + for message box buttons, resolve hotkey collisions by simulating a menu MENU_TEMPLATE_ITEM MsgBoxButtons[] = { {MNTT_PB, 0 @@ -1952,7 +1952,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = { op.Opcode = ocCreateDir; op.OpFlags = checkNewDirName ? 0 : OPFL_IGNORE_INVALID_NAME; - if (!script->CopyAttrs && // when copying attributes, the heuristic for setting the Encrypted attribute is skipped + if (!script->CopyAttrs && // when copying attributes, the heuristic for setting the Encrypted attribute does not apply ((sourceDirAttr & FILE_ATTRIBUTE_ENCRYPTED) || targetPathState == tpsEncryptedExisting || targetPathState == tpsEncryptedNotExisting)) { @@ -2008,7 +2008,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = BOOL copyMoveDirIsLink = FALSE; BOOL copyMoveSkipLinkContent = FALSE; - if ((type == atCopy || type == atMove) && // if it's a link, determine whether to skip or copy its content + if ((type == atCopy || type == atMove) && // if it is a link, determine whether to skip or copy its content (sourceDirAttr & FILE_ATTRIBUTE_REPARSE_POINT)) { copyMoveDirIsLink = TRUE; @@ -2069,7 +2069,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = //--- build the path to sourceDirName and start searching for contained files BOOL delDirectory = TRUE; // delete a non-empty directory? BOOL delDirectoryReturn = TRUE; // return value when a non-empty directory isn't removed - BOOL canDelDirAfterMove = TRUE; // Move only: FALSE if not everything is moved (filter skipped something), source directory can't be removed (won't be empty) + BOOL canDelDirAfterMove = TRUE; // Move only: FALSE if not everything is moved (the filter skipped something); the source directory cannot be removed because it will not be empty if (!copyMoveDirIsLink || !copyMoveSkipLinkContent) { WIN32_FIND_DATA f; @@ -2080,7 +2080,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = { DWORD err = GetLastError(); if (err == ERROR_PATH_NOT_FOUND && type == atCountSize && dirDOSName != NULL && strcmp(dirName, dirDOSName) != 0) - { // workaround for computing the size of a directory that must be accessed via DOS-name when we can't handle the UNICODE name (the multibyte version converted back to UNICODE doesn't match the original) + { // workaround for computing the size of a directory that must be accessed via a DOS name when the Unicode name cannot be used (the multibyte version converted back to Unicode does not match the original directory name) lstrcpyn(finalName, sourcePath, 2 * MAX_PATH + 200); if (CutDirectory(finalName) && SalPathAppend(finalName, dirDOSName, 2 * MAX_PATH + 200) && @@ -2110,8 +2110,8 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = params.Caption = LoadStr(IDS_ERRORTITLE); params.Text = text; char aliasBtnNames[200]; - /* used by export_mnu.py script that generates salmenu.mnu for the Translator - we let the msgbox buttons resolve hotkey collisions by simulating that it is a menu + /* used by the export_mnu.py script, which generates salmenu.mnu for Translator + for message box buttons, resolve hotkey collisions by simulating a menu MENU_TEMPLATE_ITEM MsgBoxButtons[] = { {MNTT_PB, 0 @@ -2125,7 +2125,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = DIALOG_NO, LoadStr(IDS_MSGBOXBTN_SKIPALL)); params.AliasBtnNames = aliasBtnNames; int msgRes = SalMessageBoxEx(¶ms); - if (msgRes != DIALOG_YES /* Skip */ && msgRes != DIALOG_NO /* Skip All */) + if (msgRes != DIALOG_YES /* Skip All */ && msgRes != DIALOG_NO /* Skip All */) skip = FALSE; if (msgRes == DIALOG_NO /* Skip All */) ErrListDirSkipAll = TRUE; @@ -2171,7 +2171,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = } askDirDelete = FALSE; } - //--- does anyone want to interrupt script building? + //--- check whether script building should be interrupted if (GetTickCount() - LastTickCount > BS_TIMEOUT) { if (UserWantsToCancelSafeWaitWindow()) @@ -2248,8 +2248,8 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = params.Caption = LoadStr(IDS_ERRORTITLE); params.Text = text; char aliasBtnNames[200]; - /* used by export_mnu.py script that generates salmenu.mnu for the Translator - we let the msgbox buttons resolve hotkey collisions by simulating that it is a menu + /* used by the export_mnu.py script that generates salmenu.mnu for Translator + for message box buttons, we resolve hotkey collisions by simulating a menu MENU_TEMPLATE_ITEM MsgBoxButtons[] = { {MNTT_PB, 0 @@ -2293,7 +2293,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = { return skip; } - if ((op.TargetName = BuildName(sourcePath, dirName)) == NULL) // overly long name not a concern here, previous condition would handle it + if ((op.TargetName = BuildName(sourcePath, dirName)) == NULL) // an overly long name is not a concern here; it would already have been handled by the previous condition { free(op.SourceName); return FALSE; @@ -2337,8 +2337,8 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = } else { - // if directory's time&date should be preserved, store an operation to set the directory's time&date - // (can be done only after finishing writing subdirectories and files into this directory) + // if the directory's date and time should be preserved, store an operation to set them + // (this can be done only after finishing writing subdirectories and files into this directory) if ((type == atCopy || type == atMove) && filterCriteria != NULL && filterCriteria->PreserveDirTime && createDirIndex >= 0 && createDirIndex < script->Count) @@ -2361,7 +2361,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = } // if we need to delete the directory or a link to it at sourcePath + dirName (delete and move) - if (copyMoveDirIsLink && type == atMove || // for a link canDelDirAfterMove is irrelevant (a link can always be removed) + if (copyMoveDirIsLink && type == atMove || // for a link, canDelDirAfterMove is irrelevant (a link can always be deleted) !copyMoveDirIsLink && type == atMove && canDelDirAfterMove || type == atDelete) // delete the source directory or the link to the directory { if (type == atDelete && !delDirectory) @@ -2377,7 +2377,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = &ErrTooLongDirNameSkipAll, sourcePath)) == NULL) { if (skip) - skipTooLongSrcNameErr = TRUE; // we also want to add a flag to skip directory creation + skipTooLongSrcNameErr = TRUE; // we also want to add a flag to skip creating the directory else return FALSE; } @@ -2490,7 +2490,7 @@ BOOL CFilesWindow::BuildScriptFile(COperations* script, CActionType type, char* op.Opcode = (type == atCopy) ? ocCopyFile : ocMoveFile; op.FileSize = fileSizeLoc; op.OpFlags = srcAndTgtPathsFlags; - if (!script->CopyAttrs && // when copying attributes, the heuristic for setting the Encrypted attribute is skipped + if (!script->CopyAttrs && // when copying attributes, the heuristic for setting the Encrypted attribute does not apply ((sourceFileAttr & FILE_ATTRIBUTE_ENCRYPTED) || targetPathState == tpsEncryptedExisting || targetPathState == tpsEncryptedNotExisting)) { @@ -2521,8 +2521,8 @@ BOOL CFilesWindow::BuildScriptFile(COperations* script, CActionType type, char* params.Caption = LoadStr(IDS_ERRORTITLE); params.Text = message; char aliasBtnNames[200]; - /* used by export_mnu.py script that generates salmenu.mnu for the Translator - we let the msgbox buttons resolve hotkey collisions by simulating that it is a menu + /* used by the export_mnu.py script, which generates salmenu.mnu for the Translator + for message box buttons, we resolve hotkey collisions by simulating a menu MENU_TEMPLATE_ITEM MsgBoxButtons[] = { {MNTT_PB, 0 @@ -2545,9 +2545,9 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = char finalName[2 * MAX_PATH + 200]; // +200 is a reserve (Windows creates paths longer than MAX_PATH) if (mapName == NULL) { - // Petr: a bit of a hack: the *.* mask doesn't create a copy of the source name, which is a problem when copying - // files with invalid names, e.g. "c ..." + "*.*" = "c ", so we help ourselves - // by changing the mask to NULL = a simple textual copy of the name + // Petr: a bit of a hack: the *.* mask does not create a copy of the source name, which is a problem when copying + // files with invalid names, e.g. "c ..." + "*.*" = "c ", so the mask is changed + // to NULL, i.e. a simple textual copy of the name char* opMask = mask != NULL && strcmp(mask, "*.*") == 0 ? NULL : mask; if ((op.TargetName = BuildName(targetPath, MaskName(finalName, 2 * MAX_PATH + 200, fileName, opMask), @@ -2571,7 +2571,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = { free(op.SourceName); free(op.TargetName); - if (type == atMove) // moving where it already is ... + if (type == atMove) // moving to the same location ... { SalMessageBox(MainWindow->HWindow, LoadStr(IDS_CANNOTMOVEFILETOITSELF), LoadStr(IDS_ERRORTITLE), MB_OK | MB_ICONEXCLAMATION); @@ -2594,12 +2594,12 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = script->SameRootButDiffVolume || !HasTheSameRootPath(sourcePath, targetPath)) { // if the path ends with a space/period, it is invalid and we must not perform the copy, - // CreateFile trims spaces/periods, potentially resulting in copying a different file or to a different name + // because CreateFile trims spaces/periods and could copy a different file or copy it under a different name BOOL invalidSrcName = FileNameIsInvalid(op.SourceName, TRUE); - // optimization "overwrite older" for copying from a slow network to a fast local disk - // (reading file times over a slow network is much faster when the directory - // listing is read sequentially instead of querying each file individually) + // "overwrite older" optimization for copying from a slow network to a fast local disk + // (reading file timestamps over a slow network is much faster when the directory + // listing is read sequentially than when each file is queried individually) if (!invalidSrcName && (srcAndTgtPathsFlags & OPFL_TGTPATH_IS_NET) == 0 && script->OverwriteOlder && fileLastWriteTime != NULL) { BOOL invalidTgtName = FileNameIsInvalid(op.TargetName, TRUE); @@ -2621,7 +2621,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = *(unsigned __int64*)&roundedInTime = *(unsigned __int64*)fileLastWriteTime - (*(unsigned __int64*)fileLastWriteTime % 10000000); *(unsigned __int64*)&dataOut.ftLastWriteTime = *(unsigned __int64*)&dataOut.ftLastWriteTime - (*(unsigned __int64*)&dataOut.ftLastWriteTime % 10000000); - if (CompareFileTime(&roundedInTime, &dataOut.ftLastWriteTime) <= 0) // source file is not newer than the target one - skip the copy operation + if (CompareFileTime(&roundedInTime, &dataOut.ftLastWriteTime) <= 0) // source file is not newer than the target file - skip the copy operation { free(op.SourceName); free(op.TargetName); @@ -2645,7 +2645,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = // we have a new file size, we need to handle this again: // file too large for FAT32 (warn the user the operation will likely fail) - if (targetPathIsFAT32 && fileSizeLoc > CQuadWord(0xFFFFFFFF /* 4GB minus 1 Byte */, 0)) + if (targetPathIsFAT32 && fileSizeLoc > CQuadWord(0xFFFFFFFF /* 4 GB minus 1 byte */, 0)) { free(op.TargetName); op.TargetName = NULL; @@ -2662,7 +2662,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = else op.Size = COPY_MIN_FILE_SIZE; // zero/small files take at least as long as files of size COPY_MIN_FILE_SIZE - if (sourcePathSupADS && // if there's a chance that ADS will be found and + if (sourcePathSupADS && // if there is a chance of finding ADS and ADS should not be ignored (targetPathSupADS || !ConfirmADSLossAll)) // if ADS should not be ignored { CQuadWord adsSize; @@ -2729,13 +2729,13 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = } } } - else // an error occurred or no ADS + else // an error occurred or no ADS are present { if (invalidSrcName || adsWinError != NO_ERROR && // an error occurred (adsWinError != ERROR_INVALID_FUNCTION || StrNICmp(op.SourceName, "\\\\tsclient\\", 11) != 0) && // paths to local disks in Terminal Server do not support ADS listing (even though ADS is otherwise supported, irony of ironies) (adsWinError != ERROR_INVALID_PARAMETER && adsWinError != ERROR_NO_MORE_ITEMS || - (srcAndTgtPathsFlags & OPFL_SRCPATH_IS_NET) == 0)) // mounted FAT/FAT32 disk cannot be detected on a network drive (e.g. \petr\f\drive_c) plus a Novell NetWare volume browsed via NDS - we think it is NTFS and thus try to read ADS, which reports this error + (srcAndTgtPathsFlags & OPFL_SRCPATH_IS_NET) == 0)) // a mounted FAT/FAT32 disk cannot be detected on a network drive (e.g. \\petr\\f\\drive_c), and for a Novell NetWare volume browsed via NDS we assume it is NTFS and therefore try to read ADS, which reports this error { // firstly, we try whether an error occurs even during opening the file - such an error // the user understands it more easily, so we show it preferentially (before the ADS read error) @@ -2779,7 +2779,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = } } } - else // report a file open error + else // report a file opening error { DWORD err = GetLastError(); if (invalidSrcName) @@ -2888,13 +2888,13 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = memmove(name + l, fileName, 1 + strlen(fileName)); // name is always < MAX_PATH CQuadWord s; DWORD err = NO_ERROR; - if (FileBasedCompression && !onlySize && // if compression is even possible - (sourceFileAttr & (FILE_ATTRIBUTE_COMPRESSED | FILE_ATTRIBUTE_SPARSE_FILE))) // if the file is compressed or sparse (sparse file) + if (FileBasedCompression && !onlySize && // if file-based compression is enabled at all + (sourceFileAttr & (FILE_ATTRIBUTE_COMPRESSED | FILE_ATTRIBUTE_SPARSE_FILE))) // if the file is compressed or sparse { s.LoDWord = GetCompressedFileSize(name, &s.HiDWord); err = GetLastError(); if (err == ERROR_FILE_NOT_FOUND && fileDOSName != NULL && strcmp(fileName, fileDOSName) != 0) - { // workaround for computing the size of a file that must be accessed via DOS-name when we cannot do it via the UNICODE name (the multibyte version of the name converted back to UNICODE doesn't match the original file name) + { // workaround for determining the size of a file that must be accessed via its DOS name when we cannot use the Unicode name (the multibyte version of the name converted back to Unicode does not match the original Unicode file name) memmove(name + l, fileDOSName, 1 + strlen(fileDOSName)); // name is always < MAX_PATH s.LoDWord = GetCompressedFileSize(name, &s.HiDWord); err = GetLastError(); @@ -2915,7 +2915,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = MB_YESNO | MB_ICONEXCLAMATION) == IDYES; UpdateWindow(MainWindow->HWindow); } - s = fileSizeLoc; // cannot determine compressed size, we settle for the normal size + s = fileSizeLoc; // Cannot determine the compressed size; use the normal size. } script->Sizes.Add(fileSizeLoc); // the output dialog is prepared for the case when this array is in an error state @@ -3013,7 +3013,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = { return skip; } - if ((op.TargetName = BuildName(sourcePath, fileName)) == NULL) // if the name is too long, it will manifest already at this earlier condition + if ((op.TargetName = BuildName(sourcePath, fileName)) == NULL) // if the name is too long, it is already handled by the previous condition { free(op.SourceName); return FALSE; @@ -3036,7 +3036,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = return TRUE; } } - return FALSE; // cannot do anything else + return FALSE; // does not support anything else } void CFilesWindow::CalculateDirSizes() @@ -3068,12 +3068,12 @@ void CFilesWindow::ExecuteFromArchive(int index, BOOL edit, HWND editWithMenuPar int format = PackerFormatConfig.PackIsArchive(GetZIPArchive()); if (format != 0) // "always-true" - we found a supported archive { - if (!PackerFormatConfig.GetUsePacker(format - 1)) // no Edit? + if (!PackerFormatConfig.GetUsePacker(format - 1)) // no edit support? { if (SalMessageBox(HWindow, LoadStr(IDS_EDITPACKNOTSUPPORTED), LoadStr(IDS_QUESTION), MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION) != IDYES) { - return; // action aborted (user does not want to edit if the archive cannot be updated) + return; // action canceled (the user does not want to edit if the archive cannot be updated) } } } @@ -3094,7 +3094,7 @@ void CFilesWindow::ExecuteFromArchive(int index, BOOL edit, HWND editWithMenuPar int j; for (j = 0; j < count; j++) { - if (index != j) // do not compare the same item + if (index != j) // do not compare an item with itself { CFileData* f2 = j < Dirs->Count ? &Dirs->At(j) : &Files->At(j - Dirs->Count); if (f2->NameLen == f->NameLen && @@ -3122,7 +3122,7 @@ void CFilesWindow::ExecuteFromArchive(int index, BOOL edit, HWND editWithMenuPar { format--; int index2 = PackerFormatConfig.GetUnpackerIndex(format); - if (index2 < 0) // view: is this internal handling (plug-in)? + if (index2 < 0) // view: is this internal handling (plugin)? { CPluginData* data = Plugins.Get(-index2 - 1); if (data != NULL) @@ -3161,7 +3161,7 @@ void CFilesWindow::ExecuteFromArchive(int index, BOOL edit, HWND editWithMenuPar char tmpPath[MAX_PATH]; memcpy(tmpPath, name, backSlash - name); tmpPath[backSlash - name] = 0; - BeginStopRefresh(); // the snooper can take a break + BeginStopRefresh(); // stop refreshing SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); HCURSOR oldCur = SetCursor(LoadCursor(NULL, IDC_WAIT)); if (PackUnpackOneFile(this, GetZIPArchive(), PluginData.GetInterface(), @@ -3242,7 +3242,7 @@ void CFilesWindow::ExecuteFromArchive(int index, BOOL edit, HWND editWithMenuPar if (UnpackedAssocFiles.AddFile(GetZIPArchive(), GetZIPPath(), buf, s, dosName, lastWrite, fileSize, attr)) { // this file doesn't have the disk-cache 'lock' object ExecuteAssocEvent yet - DiskCache.AssignName(dcFileName, ExecuteAssocEvent, FALSE, crtCache); // arcCacheCacheCopies has no effect – caching is done until the archive is closed, we won't unpack earlier + DiskCache.AssignName(dcFileName, ExecuteAssocEvent, FALSE, crtCache); // arcCacheCacheCopies has no effect - caching continues until the archive is closed, and we will not unpack earlier } else { // it is unnecessary to add the same 'lock' object to a tmp file diff --git a/src/fileswn7.cpp b/src/fileswn7.cpp index dc88ef3db..f5ae799a3 100644 --- a/src/fileswn7.cpp +++ b/src/fileswn7.cpp @@ -624,9 +624,9 @@ void CFilesWindow::UnpackZIPArchive(CFilesWindow* target, BOOL deleteOp, const c if (!ok) { - //--- refresh directories that are not automatically refreshed - // if directory creation failed, report immediately changes (the user may - // choose a completely different path next time); the new path is kept (almost dead code) + //--- refresh directories that are not refreshed automatically + // if directory creation failed, report the changes immediately (the user may + // choose a completely different path next time); the newly created path is not removed (almost dead code) MainWindow->PostChangeOnPathNotification(changesRoot, TRUE); SalPathAddBackslash(path, MAX_PATH + 200); @@ -668,7 +668,7 @@ void CFilesWindow::UnpackZIPArchive(CFilesWindow* target, BOOL deleteOp, const c if (PackUncompress(MainWindow->HWindow, this, GetZIPArchive(), PluginData.GetInterface(), path, GetZIPPath(), PanelSalEnumSelection, &data)) { // unpacking succeeded - if (tgtPath == NULL) // if it is not drag&drop (selection is not cleared there) + if (tgtPath == NULL) // Only if this is not drag&drop; selection is not cleared there. { SetSel(FALSE, -1, TRUE); // explicit redraw PostMessage(HWindow, WM_USER_SELCHANGED, 0, 0); // sel-change notify @@ -681,7 +681,7 @@ void CFilesWindow::UnpackZIPArchive(CFilesWindow* target, BOOL deleteOp, const c } SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); - if (GetForegroundWindow() == MainWindow->HWindow) // for unknown reasons focus disappears from the panel when dragging to Explorer; return it + if (GetForegroundWindow() == MainWindow->HWindow) // for unknown reasons, focus disappears from the panel during drag and drop to Explorer; restore it to the panel RestoreFocusInSourcePanel(); } else @@ -722,7 +722,7 @@ void CFilesWindow::UnpackZIPArchive(CFilesWindow* target, BOOL deleteOp, const c MainWindow->PostChangeOnPathNotification(GetPath(), FALSE); } } - else // delete + else // Delete icon { //--- ask whether the user is sure they want to delete HICON hIcon = (HICON)HANDLES(LoadImage(Shell32DLL, MAKEINTRESOURCE(WindowsVistaAndLater ? 16777 : 161), // delete icon @@ -822,7 +822,7 @@ BOOL _ReadDirectoryTree(HWND parent, char (&path)[MAX_PATH], char* name, CSalama char* end = path + strlen(path); char text[2 * MAX_PATH + 100]; if ((end - path) + (*(end - 1) != '\\' ? 1 : 0) + strlen(name) + 2 >= _countof(path)) - return TRUE; // path too long: continue without reporting the error until enumeration is complete + return TRUE; // path too long: continue; report the error during enumeration if (*(end - 1) != '\\') { *end++ = '\\'; @@ -850,7 +850,7 @@ BOOL _ReadDirectoryTree(HWND parent, char (&path)[MAX_PATH], char* name, CSalama { if (errorOccured != NULL) *errorOccured = SALENUM_CANCEL; - return FALSE; // user wants to quit + return FALSE; // user wants to cancel } } return TRUE; // user wants to continue @@ -883,7 +883,7 @@ BOOL _ReadDirectoryTree(HWND parent, char (&path)[MAX_PATH], char* name, CSalama if (file.cFileName[0] == 0 || file.cFileName[0] == '.' && (file.cFileName[1] == 0 || (file.cFileName[1] == '.' && file.cFileName[2] == 0))) - continue; // "." a ".." + continue; // "." and ".." static DWORD lastBreakCheck = 0; if (containsDirLinks != NULL && GetTickCount() - lastBreakCheck > 200) @@ -962,7 +962,7 @@ BOOL _ReadDirectoryTree(HWND parent, char (&path)[MAX_PATH], char* name, CSalama newF.IsOffline = newF.Attr & FILE_ATTRIBUTE_OFFLINE ? 1 : 0; } - if (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) // directory, so it is certainly a disk + if (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) // directory, so it is definitely on disk { CSalamanderDirectory* salDir = NULL; if (dir != NULL) @@ -1042,7 +1042,7 @@ BOOL _ReadDirectoryTree(HWND parent, char (&path)[MAX_PATH], char* name, CSalama { if (errorOccured != NULL) *errorOccured = SALENUM_CANCEL; - return FALSE; // user wants to quit + return FALSE; // user canceled } } @@ -1149,7 +1149,7 @@ CSalamanderDirectory* ReadDirectoryTree(HWND parent, CPanelTmpEnumData* data, in } else { - if ((f->Attr & FILE_ATTRIBUTE_REPARSE_POINT) != 0) // directory link found, stop... + if ((f->Attr & FILE_ATTRIBUTE_REPARSE_POINT) != 0) // found a directory link, stop { *containsDirLinks = 1; strcpy(path, data->WorkPath); @@ -1236,7 +1236,7 @@ const char* WINAPI PanelEnumDiskSelection(HWND parent, int enumFiles, const char { data->DiskDirectoryTree = ReadDirectoryTree(parent, data, errorOccured, enumFiles == 3, NULL, NULL); if (data->DiskDirectoryTree == NULL) - return NULL; // error, stop + return NULL; // error, abort } const CFileData* f = NULL; const char* ret = _PanelSalEnumSelection(enumFiles, dosName, isDir, size, &f, data, parent, errorOccured); @@ -1487,7 +1487,7 @@ void CFilesWindow::Pack(CFilesWindow* target, int pluginIndex, const char* plugi if (delFilesAfterPacking == 1) PackerConfig.Move = TRUE; - if (delFilesAfterPacking == 0 || // Petr: changed default - user must always enable deletion, it is too risky + if (delFilesAfterPacking == 0 || // Petr: changed the default; the user must always enable deletion because it is too risky delFilesAfterPacking == 2) { PackerConfig.Move = FALSE; @@ -1545,12 +1545,13 @@ void CFilesWindow::Pack(CFilesWindow* target, int pluginIndex, const char* plugi SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); SetCurrentDirectoryToSystem(); - // the directory contains a link and cannot be combined with "delete files after packing": - // I can't handle the situation where packing a single file from the directory fails - // (e.g., if the file is locked or access is denied), and I entered the directory via the link. - // Deleting the whole link is wrong because it won't show that packing failed, + // The directory contains a link and cannot be combined with "delete files after packing": + // this does not safely handle the case where packing a single file from the directory fails + // (for example, because the file is locked or access is denied) after entering it via the link. + // Deleting the whole link is wrong because it would hide that something failed to pack, // and deleting everything except one file after traversing the link is also wrong, - // because it alters the original directory content, which users report as a bug since it's unexpected. + // because it changes the contents of the original directory, which would be reported as a bug + // because that behavior is unexpected. if (containsDirLinks == 1) { _snprintf_s(text, _TRUNCATE, LoadStr(IDS_DELFILESAFTERPACKINGNOLINKS), linkName); @@ -1725,7 +1726,7 @@ void CFilesWindow::Unpack(CFilesWindow* target, int pluginIndex, const char* plu break; } } - if (i2 == UnpackerConfig.GetUnpackersCount()) // requested plugin not found + if (i2 == UnpackerConfig.GetUnpackersCount()) // the requested plugin was not found { sprintf(subject, LoadStr(IDS_PLUGINUNPACKERNOTFOUND), pluginName); SalMessageBox(HWindow, subject, LoadStr(IDS_ERRORUNPACK), MB_OK | MB_ICONEXCLAMATION); @@ -1803,7 +1804,7 @@ void CFilesWindow::Unpack(CFilesWindow* target, int pluginIndex, const char* plu if (newDir[0] != 0) RemoveEmptyDirs(newDir); } - else // unpacking succeeded (no Cancel, Skip may have occurred) + else // unpacking succeeded (no Cancel; Skip may have occurred) { if (delArchiveWhenDone && archiveVolumes.Length > 0) { @@ -1820,7 +1821,7 @@ void CFilesWindow::Unpack(CFilesWindow* target, int pluginIndex, const char* plu { DWORD err = GetLastError(); if (err == ERROR_FILE_NOT_FOUND) - break; // if the user already managed to delete the file, all is OK + break; // if the user has already deleted the file, everything is OK int res = (int)CFileErrorDlg(MainWindow->HWindow, LoadStr(IDS_ERRORDELETINGFILE), name, GetErrorText(err)).Execute(); if (res == IDB_SKIPALL) skipAll = TRUE; @@ -1871,9 +1872,9 @@ void CFilesWindow::Unpack(CFilesWindow* target, int pluginIndex, const char* plu { CutDirectory(newDir); // should always work (path to the first newly created directory) - //--- refresh directories that are not automatically refreshed - // if creating directories failed, report changes immediately (the user may - // choose a completely different path next time); the newly created path is kept (almost dead code) + //--- refresh directories that are not refreshed automatically + // if directory creation failed, report the changes immediately (the user may + // choose a completely different path next time); the newly created path is not removed (almost dead code) MainWindow->PostChangeOnPathNotification(newDir, TRUE); } goto DO_AGAIN; @@ -1955,7 +1956,7 @@ void CFilesWindow::CalculateOccupiedZIPSpace(int countSizeMode) } delete[] (indexes); } - else // take the selected file or directory + else // Use the selected file or directory { selIndex = GetCaretIndex(); if (upDir && selIndex == 0) @@ -2032,7 +2033,7 @@ void CFilesWindow::AcceptChangeOnPathNotification(const char* path, BOOL includi refresh = !includingSubdirs && StrICmp(path1, path2) == 0 || // exact match includingSubdirs && StrNICmp(path1, path2, len1) == 0 && // prefix match (path2[len1] == 0 || path2[len1] == '\\'); - if (Is(ptDisk) && !refresh && CutDirectory(path1)) // pointless for archives + if (Is(ptDisk) && !refresh && CutDirectory(path1)) // not applicable to archives { SalPathRemoveBackslash(path1); // on NTFS the last subdirectory timestamp also changes (unfortunately visible only after entering @@ -2049,7 +2050,7 @@ void CFilesWindow::AcceptChangeOnPathNotification(const char* path, BOOL includi } else { - if (Is(ptPluginFS) && GetPluginFS()->NotEmpty()) // send notification to the FS + if (Is(ptPluginFS) && GetPluginFS()->NotEmpty()) // send a notification to the FS { // the EnterPlugin+LeavePlugin section must be exposed up to here (not wrapped inside the interface) EnterPlugin(); @@ -2091,7 +2092,7 @@ void CFilesWindow::IconOverlaysChangedOnPath(const char* path) // if the timer fails, attempt an immediate refresh... } // try to refresh immediately (as long as it didn't come too soon after the previous one) - if (!IconCacheValid) // perform after icons finish loading (they may or may not load correctly) + if (!IconCacheValid) // refresh after icon loading completes (icons may or may not load correctly) { // TRACE_I("CFilesWindow::IconOverlaysChangedOnPath: delaying refresh till end of reading of icons"); NeedIconOvrRefreshAfterIconsReading = TRUE; diff --git a/src/fileswn8.cpp b/src/fileswn8.cpp index 4a230002b..a5b26f2d9 100644 --- a/src/fileswn8.cpp +++ b/src/fileswn8.cpp @@ -64,8 +64,8 @@ BOOL CFilesWindow::DeleteThroughRecycleBin(int* selection, int selCount, CFileDa SalPathAddBackslash(path, MAX_PATH); int pathLen = (int)strlen(path); // Verify that the path does not contain components ending with a space or dot; - // as this can confuse the Recycle Bin and cause it to delete from a different path (it quietly trims - // those spaces or dots) + // this confuses the Recycle Bin and causes it to delete from a different path (it silently trims + // those spaces or dots). if (!PathContainsValidComponents(path, TRUE)) { char textBuf[2 * MAX_PATH + 200]; @@ -108,7 +108,7 @@ BOOL CFilesWindow::DeleteThroughRecycleBin(int* selection, int selCount, CFileDa fo.fAnyOperationsAborted = FALSE; fo.hNameMappings = NULL; fo.lpszProgressTitle = ""; - // Perform the actual deletion - wonderfully simple, unfortunately it sometimes crashes ;-) + // Perform the actual deletion; unfortunately, it sometimes crashes. CALL_STACK_MESSAGE1("CFilesWindow::DeleteThroughRecycleBin::SHFileOperation"); BOOL ret = DeleteThroughRecycleBinAux(&fo) == 0; SetCurrentDirectoryToSystem(); @@ -127,7 +127,7 @@ void PluginFSConvertPathToExternal(char* path) Plugins.IsPluginFS(fsName, index, fsNameIndex)) { CPluginData* plugin = Plugins.Get(index); - if (plugin != NULL && plugin->InitDLL(MainWindow->HWindow, FALSE, TRUE, FALSE)) // the plugin may not be loaded, let it load if needed + if (plugin != NULL && plugin->InitDLL(MainWindow->HWindow, FALSE, TRUE, FALSE)) // the plugin may not be loaded yet; load it if necessary plugin->GetPluginInterfaceForFS()->ConvertPathToExternal(fsName, fsNameIndex, fsUserPart); } } @@ -270,7 +270,7 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count // if packing to the archive in the other panel is not possible, leave the path empty int format = PackerFormatConfig.PackIsArchive(target->GetZIPArchive()); - if (format != 0) // we found a supported archive + if (format != 0) // supported archive found { if (!PackerFormatConfig.GetUsePacker(format - 1)) // no edit -> empty operation target { @@ -286,7 +286,7 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count (type == atCopy && target->GetPluginFS()->IsServiceSupported(FS_SERVICE_COPYFROMDISKTOFS) || type == atMove && target->GetPluginFS()->IsServiceSupported(FS_SERVICE_MOVEFROMDISKTOFS))) { - // // this is just a modification of the target path text in the plug-in -> no point in lowering the thread's priority + // // this is just a modification of the target path text in the plugin -> no point in lowering the thread's priority int selFiles = 0; int selDirs = 0; if (count > 0) // some files are selected @@ -294,7 +294,7 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count selFiles = files; selDirs = count - files; } - else // take the focused item + else // use the focused item { int index = GetCaretIndex(); if (index >= Dirs->Count) @@ -341,7 +341,7 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count if (invertRecycleBin) { if (Configuration.UseRecycleBin == 0) - recycle = 1; // all + recycle = 1; // for all else recycle = 0; // none } @@ -397,7 +397,7 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count else expanded[0] = 0; // not used } - else // count-files in directories and individualfiles + else // `count - files` directories and `files` files { ExpandPluralFilesDirs(expanded, 200, files, count - files, epfdmNormal, FALSE); } @@ -440,7 +440,7 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count DWORD clusterSize = 0; CChangeCaseData changeCaseData; CCriteriaData criteria; - if (CopyMoveOptions.Get() != NULL) // if they exist, pull the defaults + if (CopyMoveOptions.Get() != NULL) // if they exist, load the defaults criteria = *CopyMoveOptions.Get(); CCriteriaData* criteriaPtr = NULL; // pointer to 'criteria'; if NULL, they are ignored BOOL copyToExistingDir = FALSE; @@ -461,7 +461,7 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count while (1) { if (strlen(path) >= 2 * MAX_PATH) - path[0] = 0; // the path is too long; not an ideal solution but I'm not up for a better one now :( + path[0] = 0; // the path is too long; this is not an ideal solution res = (int)CCopyMoveMoreDialog(HWindow, path, 2 * MAX_PATH, (type == atCopy) ? LoadStr(IDS_COPY) : LoadStr(IDS_MOVE), &str, (type == atCopy) ? IDD_COPYDIALOG : IDD_MOVEDIALOG, @@ -527,7 +527,7 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count { if (pathType == PATH_TYPE_ARCHIVE) // path into an archive { - if (strlen(secondPart) >= MAX_PATH) // isn't the path inside the archive too long? + if (strlen(secondPart) >= MAX_PATH) // is the path inside the archive too long? { SalMessageBox(HWindow, LoadStr(IDS_TOOLONGPATH), (type == atCopy) ? LoadStr(IDS_ERRORCOPY) : LoadStr(IDS_ERRORMOVE), @@ -535,7 +535,7 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count continue; } - if (criteriaPtr != NULL && Configuration.CnfrmCopyMoveOptionsNS) // archives do not support options from the Copy/Move dialog + if (criteriaPtr != NULL && Configuration.CnfrmCopyMoveOptionsNS) // archives do not support the options from the Copy/Move dialog { MSGBOXEX_PARAMS params; memset(¶ms, 0, sizeof(params)); @@ -557,7 +557,7 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count data.IndexesCount = count; data.Indexes = indexes; // deallocated via 'indexes' } - else // take the focused item + else // use the focused item { oneIndex = GetCaretIndex(); data.IndexesCount = 1; @@ -599,7 +599,7 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count { nullFile = (size == CQuadWord(0, 0)); - //--- if it's a zero-size file, we must delete it; archivers can not handle them + //--- if it is a zero-size file, we must delete it; archivers cannot handle such files DWORD nullFileAttrs; if (nullFile) { @@ -635,7 +635,7 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count } else { - if (nullFile) // it failed, we have to create it again + if (nullFile) // The previous attempt failed, so we have to create it again { HANDLE hFile2 = HANDLES_Q(CreateFile(path, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, @@ -694,9 +694,9 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count } else { - if (pathType == PATH_TYPE_FS) // file-system path + if (pathType == PATH_TYPE_FS) // file system path { - if (strlen(secondPart) >= MAX_PATH) // is the user's part of the FS path too long? + if (strlen(secondPart) >= MAX_PATH) // is the user-entered part of the FS path too long? { SalMessageBox(HWindow, LoadStr(IDS_TOOLONGPATH), (type == atCopy) ? LoadStr(IDS_ERRORCOPY) : LoadStr(IDS_ERRORMOVE), @@ -731,7 +731,7 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count data.IndexesCount = count; data.Indexes = indexes; // deallocated via 'indexes' } - else // take the focused item + else // use the focused item { oneIndex = GetCaretIndex(); if (oneIndex >= Dirs->Count) @@ -802,13 +802,13 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count PluginFSConvertPathToExternal(targetPath); strcpy(path, targetPath); invalidPath = TRUE; - break; // we must go back to the copy/move dialog + break; // return to the Copy/Move dialog } // trying another FS } } } - if (i == list->Count) // active and detached FS couldn't handle it, we will create a new FS + if (i == list->Count) // neither the active nor the detached FS could handle it, so create a new FS { int index; int fsNameIndex; @@ -842,16 +842,16 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count { // done/cancel unselect = !invalidPathOrCancel; } - else // syntax error/plugin error + else // syntax error or plugin error { if (invalidPathOrCancel) { // convert the path to external format (before displaying it in the dialog) PluginFSConvertPathToExternal(targetPath); strcpy(path, targetPath); - invalidPath = TRUE; // we must go back to the Copy/Move dialog + invalidPath = TRUE; // we must return to the Copy/Move dialog } - else // plugin error (new FS, but returns "requested operation cannot be performed on this FS" error) + else // plugin error (new FS, but it returns "requested operation cannot be performed on this FS") { TRACE_E("CopyOrMoveFromDiskToFS on new (empty) FS may not return error 'unable to process operation'."); } @@ -880,7 +880,7 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count if (invalidPath) continue; // back to the copy/move dialog - if (unselect) // unselect files/directories in the panel + if (unselect) // deselect files/directories in the panel { SetSel(FALSE, -1, TRUE); // explicit redraw PostMessage(HWindow, WM_USER_SELCHANGED, 0, 0); // sel-change notify @@ -935,7 +935,7 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count break; } } - if (res == IDOK && // begin disk operation + if (res == IDOK && // begin disk operations CheckPath(TRUE) == ERROR_SUCCESS) { if (type == atDelete && recycle == 1) @@ -1118,7 +1118,7 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count script->ResetState(); FreeScript(script); } - else // removing selected index + else // clear the selected index { if (res2) { @@ -1163,9 +1163,9 @@ void CFilesWindow::FilesAction(CActionType type, CFilesWindow* target, int count } } -// extracts all subdirectories from 'path' directory and calls itself recursively -// adds files mapi -// returns TRUE, if everything succeeded; otherwise returns FALSE +// extracts all subdirectories from the 'path' directory and calls itself recursively +// adds files to MAPI +// returns TRUE if everything succeeded; otherwise returns FALSE BOOL EmailFilesAddDirectory(CSimpleMAPI* mapi, const char* path, BOOL* errGetFileSizeOfLnkTgtIgnAll) { WIN32_FIND_DATA file; @@ -1232,9 +1232,9 @@ BOOL EmailFilesAddDirectory(CSimpleMAPI* mapi, const char* path, BOOL* errGetFil return ok; } -// pulls the selection from the panel and processes every item: -// if it's a directory, calls EmailFilesAddDirectory for it -// if it's a file, adds it to mapi +// gets the selection from the panel and processes all items: +// if it is a directory, calls EmailFilesAddDirectory for it +// if it is a file, adds it to MAPI // if everything succeeds, creates the email void CFilesWindow::EmailFiles() { @@ -1377,9 +1377,9 @@ BOOL CFilesWindow::OpenFocusedInOtherPanel(BOOL activate) if (otherPanel == NULL) return FALSE; - // allow opening the up-dir + // allow opening the parent directory // if (FocusedIndex == 0 && FocusedIndex < Dirs->Count && - // strcmp(Dirs->At(0).Name, "..") == 0) return FALSE; // do not handle the up-dir + // strcmp(Dirs->At(0).Name, "..") == 0) return FALSE; // do not consider the parent directory if (FocusedIndex < 0 || FocusedIndex >= Files->Count + Dirs->Count) return FALSE; // ignore invalid index diff --git a/src/fileswn9.cpp b/src/fileswn9.cpp index 442aebc8f..f69a0bdb8 100644 --- a/src/fileswn9.cpp +++ b/src/fileswn9.cpp @@ -200,7 +200,7 @@ BOOL CFilesWindow::ClipboardPaste(BOOL onlyLinks, BOOL onlyTest, const char* pas BOOL ourClipDataObject = FALSE; DWORD effect = 0; - if (ownRutine) // if there's a chance for our own handling, check if it's copy or move + if (ownRutine) // if our own handling is possible, check whether this is a copy or move { DWORD dropEffect = 0; UINT cfPrefDrop = RegisterClipboardFormat(CFSTR_PREFERREDDROPEFFECT); @@ -226,7 +226,7 @@ BOOL CFilesWindow::ClipboardPaste(BOOL onlyLinks, BOOL onlyTest, const char* pas if (GetClipboardData(cfSalDataObject) != NULL) ourClipDataObject = TRUE; else - ownRutine = FALSE; // if it is not our IDataObject, we won't perform our own operation + ownRutine = FALSE; // if it is not our IDataObject, do not perform our own operation CloseClipboard(); } else @@ -241,7 +241,7 @@ BOOL CFilesWindow::ClipboardPaste(BOOL onlyLinks, BOOL onlyTest, const char* pas } filesOnClip = files && ourClipDataObject; - if (ownRutine) // execute our own routine - copy or move + if (ownRutine) // perform the internal copy or move routine { if (pastePath != NULL) strcpy(DropPath, pastePath); @@ -290,7 +290,7 @@ BOOL CFilesWindow::ClipboardPaste(BOOL onlyLinks, BOOL onlyTest, const char* pas } else { - if (files && !onlyTest) // perform paste/pastelink + if (files && !onlyTest) // perform Paste/Paste Link { // MainWindow->ReleaseMenuNew(); // Windows are not designed for multiple context menus @@ -415,7 +415,7 @@ BOOL CFilesWindow::ClipboardPasteToArcOrFS(BOOL onlyTest, DWORD* pasteDefEffect) if (IsSimpleSelection(dataObj, namesList)) // check if these are files/directories from disk and if they come from the same path { ret = TRUE; - // check if it's copy or move + // determine whether this is a copy or move operation DWORD dropEffect = DROPEFFECT_COPY | DROPEFFECT_MOVE; // if we can't determine the effect, assume both (Copy takes priority) UINT cfPrefDrop = RegisterClipboardFormat(CFSTR_PREFERREDDROPEFFECT); if (OpenClipboard(HWindow)) @@ -563,7 +563,7 @@ BOOL CFilesWindow::IsTextOnClipboard() else { if (attempt++ <= 10) - Sleep(10); // wait to see if the clipboard gets released (max. 100 ms) + Sleep(10); // wait for the clipboard to be released (max. 100 ms) else { TRACE_E("OpenClipboard() has failed!"); @@ -585,7 +585,7 @@ BOOL CFilesWindow::PostProcessPathFromUser(HWND parent, char (&buff)[2 * MAX_PAT // trim quotes, see https://forum.altap.cz/viewtopic.php?t=4160 CutDoubleQuotesFromBothSides(buff); - if (IsFileURLPath(buff)) // it is a URL: convert URL (file://) to a Windows path + if (IsFileURLPath(buff)) // it is a URL: convert the URL (file://) to a Windows path { char path[MAX_PATH]; DWORD pathLen = _countof(path); @@ -605,8 +605,8 @@ BOOL CFilesWindow::PostProcessPathFromUser(HWND parent, char (&buff)[2 * MAX_PAT return TRUE; // let the FS plugin handle the processing } - // expand ENV variables (as frequently requested on the forum and for internal use) - // if an ENV variable does not exist, a directory with the same name gets a chance to be expanded + // expand ENV variables (at frequent request on the forum and for internal use) + // if an ENV variable does not exist, a directory with the same name gets a chance instead char expandedBuff[_countof(buff) + 1]; DWORD auxRes = ExpandEnvironmentStrings(buff, expandedBuff, _countof(expandedBuff)); if (auxRes == 0 || auxRes > _countof(buff)) @@ -717,7 +717,7 @@ BOOL CFilesWindow::OnLButtonDown(WPARAM wParam, LPARAM lParam, LRESULT* lResult) } // compatibility with Windows Explorer: clicking outside (in either the active or inactive panel) - // means confirming the rename; other actions (Alt+Tab), unlike Explorer, are considered + // confirms the rename; other actions (Alt+Tab), unlike in Explorer, are treated // as canceling the rename if (!MainWindow->DoQuickRename()) { @@ -1145,7 +1145,7 @@ void CFilesWindow::OfferArchiveUpdateIfNeeded(HWND parent, int textID, BOOL* arc CFilesWindow* otherPanel = MainWindow->LeftPanel == this ? MainWindow->RightPanel : MainWindow->LeftPanel; BOOL otherPanelArchMaybeUpdated = FALSE; if (otherPanel->Is(ptZIPArchive) && StrICmp(GetZIPArchive(), otherPanel->GetZIPArchive()) == 0) - { // the same archive is in the other panel, we must update it as well + { // the same archive is open in the other panel, so we must update it as well otherPanel->OfferArchiveUpdateIfNeededAux(parent, textID, &otherPanelArchMaybeUpdated); if (otherPanelArchMaybeUpdated) *archMaybeUpdated = TRUE; @@ -1173,21 +1173,21 @@ BOOL CFilesWindow::OnMouseMove(WPARAM wParam, LPARAM lParam, LRESULT* lResult) { CALL_STACK_MESSAGE_NONE *lResult = 0; - if (BeginDragDrop && (wParam & (MK_LBUTTON | MK_RBUTTON))) // "dragging" for drag&drop + if (BeginDragDrop && (wParam & (MK_LBUTTON | MK_RBUTTON))) // start drag-and-drop when the mouse is dragged { int x = abs(LButtonDown.x - (short)LOWORD(lParam)); int y = abs(LButtonDown.y - (short)HIWORD(lParam)); if (x > GetSystemMetrics(SM_CXDRAG) || y > GetSystemMetrics(SM_CYDRAG)) // move { - // the condition "!PerformingDragDrop" was added after AS 2.52 due to a bug report from ehter: - // in the directory there must be two files (one EXE downloaded via IE, which contains a security ADS) and another file - // dragging the other file onto the EXE triggers a security dialog, which triggers a security dialog that is NONMODAL and has its own message loop - // thus Salamander's main thread gets stuck in ShellAction(); then a second drag&drop leads to a crash - // this patch disables new drag&drop, just like Windows Explorer does - // the solution isn't perfect because Salamander only appears to be running (the main thread isn't in our app loop) + // The "!PerformingDragDrop" condition was added after AS 2.52 because of a state reported by ehter: + // the directory must contain two files (one EXE downloaded via IE so it contains a security ADS) and another file + // dragging the other file onto the EXE opens a security dialog, but it is NONMODAL and has its own message loop + // so Salamander's main thread gets stuck in ShellAction(); then a second drag&drop led to a crash + // this patch disables a new drag&drop operation, just as Windows Explorer does + // the solution is not clean, because Salamander only appears to be running (the main thread is not in our application loop) if (!PerformingDragDrop) { - if (Is(ptZIPArchive) && AssocUsed) // if the user edited files from the archive we must update them before operating on it, otherwise we'd work with old versions of the edited files stored directly in the archive + if (Is(ptZIPArchive) && AssocUsed) // If the user edited files from the archive, we must update them before operating on the archive; otherwise, we would work with old versions of the edited files stored directly in the archive. { BOOL archMaybeUpdated; OfferArchiveUpdateIfNeeded(MainWindow->HWindow, IDS_ARCHIVECLOSEEDIT3, &archMaybeUpdated); @@ -1244,7 +1244,7 @@ BOOL CFilesWindow::OnMouseMove(WPARAM wParam, LPARAM lParam, LRESULT* lResult) return TRUE; } - if (BeginBoxSelect && (wParam & (MK_LBUTTON | MK_RBUTTON))) // "opening" selection box + if (BeginBoxSelect && (wParam & (MK_LBUTTON | MK_RBUTTON))) // Start the selection box { short xPos = (short)LOWORD(lParam); short yPos = (short)HIWORD(lParam); @@ -1684,7 +1684,7 @@ CFilesWindow::CreateDragImage(int cursorX, int cursorY, int& dxHotspot, int& dyH // DrawBriefDetailedItem(hDC, itemIndex, &r, DRAWFLAG_NO_FRAME | DRAWFLAG_NO_STATE | DRAWFLAG_SKIP_VISTEST | DRAWFLAG_DRAGDROP | DRAWFLAG_ICON_ONLY); } ListBox->XOffset = oldXOffset; - if (GetViewMode() == vmBrief) // not sure what is in XOffset in brief mode, so ensure dxHotspot is correct + if (GetViewMode() == vmBrief) // XOffset in brief mode is uncertain, so make sure dxHotspot is correct oldXOffset = 0; } else if (GetViewMode() == vmIcons || GetViewMode() == vmThumbnails) @@ -1810,7 +1810,7 @@ BOOL CopyUNCPathToClipboard(const char* path, const char* name, BOOL isDir, HWND } if (!isDir) strcat(uncPath, name); - if (SalGetFullName(uncPath)) // root "c:\\", others without '\\' at the end + if (SalGetFullName(uncPath)) // root "c:\\", others without a trailing '\\' return CopyTextToClipboard(uncPath); } @@ -1864,7 +1864,7 @@ BOOL CFilesWindow::CopyFocusedNameToClipboard(CCopyFocusedNameModeEnum mode) if (FocusedIndex == 0 && FocusedIndex < Dirs->Count && strcmp(Dirs->At(0).Name, "..") == 0) - return FALSE; // do not accept up-directory entries + return FALSE; // ignore the up-directory entry if (FocusedIndex < 0 || FocusedIndex >= Files->Count + Dirs->Count) return FALSE; // ignore an invalid index @@ -2019,7 +2019,7 @@ BOOL CFilesWindow::BuildColumnsTemplate() { lstrcpy(column.Name, LoadStr(item->NameResID)); lstrcpy(column.Description, LoadStr(item->DescResID)); - if (i == 0) // column "Name" + if (i == 0) // "Name" column { if ((ViewTemplate->Flags & VIEW_SHOW_EXTENSION) == 0) // "Ext" is part of the "Name" column, the name and description of the "Ext" column are after the terminating null of the name and description { @@ -2110,7 +2110,7 @@ void CFilesWindow::DeleteColumnsWithoutData(DWORD columnValidMask) { Columns.Delete(i); if (!Columns.IsGood()) - Columns.ResetState(); // cannot fail, the array just wasn't reduced + Columns.ResetState(); // this cannot fail; only the array was not reduced } } } @@ -2158,7 +2158,7 @@ void CFilesWindow::OnHeaderLineColWidthChanged() } if (column->ID == COLUMN_ID_CUSTOM) // it is a column added by a plugin { - if (column->FixedWidth && PluginData.NotEmpty()) // only non-elastic columns + "always true" + if (column->FixedWidth && PluginData.NotEmpty()) // only fixed-width columns + "always true" { PluginData.ColumnWidthWasChanged(leftPanel, column, column->Width); pluginColMaybeChanged = TRUE; @@ -2166,7 +2166,7 @@ void CFilesWindow::OnHeaderLineColWidthChanged() } else { - if (colIndex != -1) // "always true" + if (colIndex != -1) // "always TRUE" { if (leftPanel) ViewTemplate->Columns[colIndex].LeftWidth = column->Width; diff --git a/src/fileswna.cpp b/src/fileswna.cpp index d5d2df197..7a5ddecb7 100644 --- a/src/fileswna.cpp +++ b/src/fileswna.cpp @@ -35,7 +35,7 @@ void CFilesWindow::PluginFSFilesAction(CPluginFSActionType type) { // count how many directories are selected (the remaining selected items are files) int i; - for (i = 0; i < Dirs->Count; i++) // ".." cannot be selected, the check would be useless + for (i = 0; i < Dirs->Count; i++) // ".." cannot be selected, so the check would be redundant { if (Dirs->At(i).Selected) selectedDirs++; @@ -176,7 +176,7 @@ void CFilesWindow::PluginFSFilesAction(CPluginFSActionType type) if (ParsePath(targetPath, pathType, pathIsDir, secondPart, errTitle, NULL, &error, MAX_PATH)) { // instead of using a 'switch' statement, we use 'if' so that 'break' and 'continue' work properly - if (pathType == PATH_TYPE_WINDOWS) // Windows path (disk + UNC) + if (pathType == PATH_TYPE_WINDOWS) // Windows path (drive + UNC) { char* mask; if (SalSplitWindowsPath(HWindow, LoadStr(copy ? IDS_COPY : IDS_MOVE), @@ -188,7 +188,7 @@ void CFilesWindow::PluginFSFilesAction(CPluginFSActionType type) { // masks not supported and mask is empty, cut it off *mask = 0; // double-null terminated } - if (!operationMask && mask != NULL && *mask != 0) // mask exists but isn't allowed + if (!operationMask && mask != NULL && *mask != 0) // mask is present but not allowed { char* e = targetPath + strlen(targetPath); // fix 'targetPath' (merge 'targetPath' and 'mask') if (e > targetPath && *(e - 1) != '\\') @@ -264,7 +264,7 @@ void CFilesWindow::PluginFSFilesAction(CPluginFSActionType type) BOOL ret = GetPluginFS()->Delete(GetPluginFS()->GetPluginFSName(), 1, HWindow, panel, count - selectedDirs, selectedDirs, cancelOrError); - if (!cancelOrError) // not a cancel/operation error + if (!cancelOrError) // not canceled and no operation error { if (!ret) { @@ -474,7 +474,7 @@ void CFilesWindow::DragDropToArcOrFS(CTmpDragDropOperData* data) newF.IsLink = IsFileLink(newF.Ext); } - if ((newF.Attr & FILE_ATTRIBUTE_DIRECTORY) && !baseDir->AddDir("", newF, NULL) || // directory, certainly a disk + if ((newF.Attr & FILE_ATTRIBUTE_DIRECTORY) && !baseDir->AddDir("", newF, NULL) || // directory; this is definitely on disk (newF.Attr & FILE_ATTRIBUTE_DIRECTORY) == 0 && !baseDir->AddFile("", newF, NULL)) // file { free(newF.Name); @@ -576,7 +576,7 @@ void CFilesWindow::DragDropToArcOrFS(CTmpDragDropOperData* data) if (PackCompress(HWindow, this, data->ArchiveOrFSName, data->ArchivePathOrUserPart, !data->Copy, data->Data->SrcPath, PanelEnumDiskSelection, &dataEnum)) { // packing succeeded - if (nullFile && // zero-length file might have had a different compressed attribute, set archive accordingly + if (nullFile && // the zero-length file might have had a different compressed attribute; set the archive file to match nullFileAttrs != INVALID_FILE_ATTRIBUTES) { HANDLE hFile2 = HANDLES_Q(CreateFile(data->ArchiveOrFSName, GENERIC_READ | GENERIC_WRITE, @@ -642,12 +642,12 @@ void CFilesWindow::DragDropToArcOrFS(CTmpDragDropOperData* data) MB_OK | MB_ICONEXCLAMATION); } } - else // to FS + else // Route to FS { int selFiles = dataEnum.Files->Count; int selDirs = dataEnum.Dirs->Count; - // lower thread's priority to "normal" (so that operations don't burden the machine too much) + // lower the thread priority to "normal" (so the operation does not put too much load on the machine) SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); // select the FS that performs the operation (priority: active, then new) @@ -658,7 +658,7 @@ void CFilesWindow::DragDropToArcOrFS(CTmpDragDropOperData* data) fs = GetPluginFS(); int fsNameIndex; - if (fs != NULL && fs->NotEmpty() && // interface is valid + if (fs != NULL && fs->NotEmpty() && // FS interface is valid fs->IsFSNameFromSamePluginAsThisFS(data->ArchiveOrFSName, fsNameIndex)) // FS name is from the same plugin (otherwise it's not worth trying) { BOOL invalidPathOrCancel; @@ -676,22 +676,22 @@ void CFilesWindow::DragDropToArcOrFS(CTmpDragDropOperData* data) dataEnum.Reset(); if (invalidPathOrCancel) - done = TRUE; // invalid path + user cannot fix it, ending - // else ; // we should try a new FS + done = TRUE; // invalid path + user cannot correct the path, stop + // else ; // try a new FS } } - if (!done) // active FS failed, create a new FS + if (!done) // the active FS could not handle it, create a new FS { int index; int fsNameIndex2; if (Plugins.IsPluginFS(data->ArchiveOrFSName, index, fsNameIndex2)) // determine plugin index { - // obtain the plug-in associated with the FS + // obtain the plugin associated with the FS CPluginData* plugin = Plugins.Get(index); if (plugin != NULL) { // open a new FS - // load the plug-in before obtaining DLLName, Version and plugin interfaces + // load the plugin before obtaining DLLName, Version and plugin interfaces CPluginFSInterfaceAbstract* auxFS = plugin->OpenFS(data->ArchiveOrFSName, fsNameIndex2); CPluginFSInterfaceEncapsulation pluginFS(auxFS, plugin->DLLName, plugin->Version, plugin->GetPluginInterfaceForFS()->GetInterface(), diff --git a/src/fileswnb.cpp b/src/fileswnb.cpp index bb9328661..873114f0f 100644 --- a/src/fileswnb.cpp +++ b/src/fileswnb.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -22,10 +23,10 @@ extern "C" //**************************************************************************** -// definujeme GUID udalosti "Lock Volume" (napr. "chkdsk /f E:", kde E: je USB stick): {50708874-C9AF-11D1-8FEF-00A0C9A06D32} +// define the "Lock Volume" event GUID (e.g., "chkdsk /f E:" where E: is a USB stick): {50708874-C9AF-11D1-8FEF-00A0C9A06D32} GUID GUID_IO_LockVolume = {0x50708874, 0xC9AF, 0x11D1, 0x8F, 0xEF, 0x00, 0xA0, 0xC9, 0xA0, 0x6D, 0x32}; // -// v Ioevent.h z DDK je definice teto konstanty (a mnoha dalsich): +// Ioevent.h from the DDK defines this constant (and many others): // // Volume lock event. This event is signalled when an attempt is made to // lock a volume. There is no additional data. @@ -68,7 +69,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) HCURSOR oldCur; switch (uMsg) { - //--- roztahovani listboxu po celem okne + //--- expanding the listbox over the entire window case WM_SIZE: { if (ListBox != NULL && ListBox->HWindow != NULL && StatusLine != NULL && DirectoryLine != NULL) @@ -143,16 +144,16 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) // TRACE_I("WM_DEVICECHANGE: DBT_CUSTOMEVENT"); if (IsCustomEventGUID(lParam, GUID_IO_LockVolume)) - { // chodi na XPckach, kdyz se spusti "chkdsk /f e:" ("e:" je removable USB stick) a bohuzel taky pri otevirani .ifo a .vob souboru (DVD) a pri spousteni Ashampoo Burning Studio 6 -- zadost "lock volume" + { // occurs on XP when "chkdsk /f e:" ("e:" is a removable USB stick) is run, and unfortunately also when opening .ifo and .vob files (DVD) and when starting Ashampoo Burning Studio 6 -- "lock volume" request if (UseSystemIcons || UseThumbnails) - SleepIconCacheThread(); // pozastavime cteni ikonek/thumbnailu - DetachDirectory((CFilesWindow*)this, TRUE); // zavreme change-notifikace + DeviceNotification + SleepIconCacheThread(); // pause reading icons/thumbnails + DetachDirectory((CFilesWindow*)this, TRUE); // close change notifications and DeviceNotification HANDLES(EnterCriticalSection(&TimeCounterSection)); int t1 = MyTimeCounter++; HANDLES(LeaveCriticalSection(&TimeCounterSection)); BOOL salIsActive = GetForegroundWindow() == MainWindow->HWindow; - PostMessage(HWindow, WM_USER_REFRESH_DIR_EX, salIsActive, t1); // refresh obnovi cteni ikon/thumbnailu + otevre opet change-notifikace + DeviceNotification; vime, ze jde pravdepodobne o zbytecny refresh + PostMessage(HWindow, WM_USER_REFRESH_DIR_EX, salIsActive, t1); // refresh resumes icon/thumbnail reading and reopens change notifications and DeviceNotification; we know this is probably an unnecessary refresh } break; } @@ -160,8 +161,8 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case DBT_DEVICEQUERYREMOVE: { // TRACE_I("WM_DEVICECHANGE: DBT_DEVICEQUERYREMOVE"); - DetachDirectory((CFilesWindow*)this, TRUE, FALSE); // bez zavreni DeviceNotification - return TRUE; // povolime odstraneni tohoto device + DetachDirectory((CFilesWindow*)this, TRUE, FALSE); // without closing DeviceNotification + return TRUE; // allow removal of this device } case DBT_DEVICEQUERYREMOVEFAILED: @@ -176,7 +177,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { // if (wParam == DBT_DEVICEREMOVEPENDING) TRACE_I("WM_DEVICECHANGE: DBT_DEVICEREMOVEPENDING"); // else TRACE_I("WM_DEVICECHANGE: DBT_DEVICEREMOVECOMPLETE"); - DetachDirectory((CFilesWindow*)this, TRUE); // zavreme DeviceNotification + DetachDirectory((CFilesWindow*)this, TRUE); // close DeviceNotification if (MainWindow->LeftPanel == this) { if (!ChangeLeftPanelToFixedWhenIdleInProgress) @@ -204,7 +205,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { ProgressDialogActivateDrop = LastWndFromGetData; UnpackZIPArchive(NULL, FALSE, tgtPath); - ProgressDialogActivateDrop = NULL; // pro dalsi pouziti progress dialogu musime globalku vycistit + ProgressDialogActivateDrop = NULL; // clear global variable for further use of progress dialog SHChangeNotify(SHCNE_UPDATEDIR, SHCNF_PATH, tgtPath, NULL); } free(tgtPath); @@ -223,22 +224,22 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { int count = GetSelCount(); if (count > 0 || GetCaretIndex() != 0 || - Dirs->Count == 0 || strcmp(Dirs->At(0).Name, "..") != 0) // test jestli se nepracuje jen s ".." + Dirs->Count == 0 || strcmp(Dirs->At(0).Name, "..") != 0) // check whether we are working only with ".." { - BeginSuspendMode(); // cmuchal si da pohov - BeginStopRefresh(); // jen aby se nedistribuovaly zpravy o zmenach na cestach + BeginSuspendMode(); // snooper takes a break + BeginStopRefresh(); // just to avoid distributing notifications about path changes UserWorkedOnThisPath = TRUE; - StoreSelection(); // ulozime selection pro prikaz Restore Selection + StoreSelection(); // save the selection for the Restore Selection command ProgressDialogActivateDrop = LastWndFromGetData; int selectedDirs = 0; if (count > 0) { - // spocitame kolik adresaru je oznaceno (zbytek oznacenych polozek jsou soubory) + // count how many directories are selected (the rest of the marked items are files) int i; - for (i = 0; i < Dirs->Count; i++) // ".." nemuzou byt oznaceny, test by byl zbytecny + for (i = 0; i < Dirs->Count; i++) // ".." cannot be selected, so the test would be unnecessary { if (Dirs->At(i).Selected) selectedDirs++; @@ -253,16 +254,16 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) BOOL cancelOrHandlePath = FALSE; char targetPath[2 * MAX_PATH]; lstrcpyn(targetPath, tgtPath, 2 * MAX_PATH - 1); - if (tgtPath[0] == '\\' && tgtPath[1] == '\\' || // UNC cesta - tgtPath[0] != 0 && tgtPath[1] == ':') // klasicka diskova cesta (C:\path) + if (tgtPath[0] == '\\' && tgtPath[1] == '\\' || // UNC path + tgtPath[0] != 0 && tgtPath[1] == ':') // regular disk path (C:\path) { int l = (int)strlen(targetPath); if (l > 3 && targetPath[l - 1] == '\\') - targetPath[l - 1] = 0; // krom "c:\" zrusime koncovy backslash + targetPath[l - 1] = 0; // except for "c:\" remove the trailing backslash } - targetPath[strlen(targetPath) + 1] = 0; // zajistime dve nuly na konci retezce + targetPath[strlen(targetPath) + 1] = 0; // ensure two nulls at the end of the string - // snizime prioritu threadu na "normal" (aby operace prilis nezatezovaly stroj) + // lower thread priority to "normal" so the operation does not put too much load on the system SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); BOOL ret = GetPluginFS()->CopyOrMoveFromFS(copy, 5, GetPluginFS()->GetPluginFSName(), @@ -272,33 +273,33 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) cancelOrHandlePath, ProgressDialogActivateDrop); - // opet zvysime prioritu threadu, operace dobehla + // increase thread priority again; the operation has finished SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); if (ret && !cancelOrHandlePath) { - if (targetPath[0] != 0) // zmena fokusu na 'targetPath' + if (targetPath[0] != 0) // change focus to 'targetPath' { lstrcpyn(NextFocusName, targetPath, MAX_PATH); - // RefreshDirectory nemusi probehnout - zdroj se nemusel zmenit - pro sichr postneme message + // RefreshDirectory may not run; the source may be unchanged, so post a message just in case PostMessage(HWindow, WM_USER_DONEXTFOCUS, 0, 0); } - // uspesna operace, ale zdroj neodznacime, protoze jde o drag&drop - // SetSel(FALSE, -1, TRUE); // explicitni prekresleni - // PostMessage(HWindow, WM_USER_SELCHANGED, 0, 0); // sel-change notify + // successful operation, but do not clear the source selection because this is drag and drop + // SetSel(FALSE, -1, TRUE); // explicit redraw + // PostMessage(HWindow, WM_USER_SELCHANGED, 0, 0); // selection-change notification UpdateWindow(MainWindow->HWindow); } - ProgressDialogActivateDrop = NULL; // pro dalsi pouziti progress dialogu musime globalku vycistit - if (tgtPath[0] == '\\' && tgtPath[1] == '\\' || // UNC cesta - tgtPath[0] != 0 && tgtPath[1] == ':') // klasicka diskova cesta (C:\path) + ProgressDialogActivateDrop = NULL; // clear the global variable for further use of the progress dialog + if (tgtPath[0] == '\\' && tgtPath[1] == '\\' || // UNC path + tgtPath[0] != 0 && tgtPath[1] == ':') // regular disk path (C:\path) { SHChangeNotify(SHCNE_UPDATEDIR, SHCNF_PATH, tgtPath, NULL); } EndStopRefresh(); - EndSuspendMode(); // ted uz zase cmuchal nastartuje + EndSuspendMode(); // the snooper will start again now } } free(tgtPath); @@ -307,8 +308,8 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_USER_UPDATEPANEL: { - // nekdo rozdistribuoval zpravy (otevrel se messagebox) a je treba updatnou - // obsah panelu + // someone dispatched messages (a message box opened) and the panel + // content must be updated RefreshListBox(0, -1, -1, FALSE, FALSE); return 0; } @@ -316,20 +317,20 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_USER_ENTERMENULOOP: case WM_USER_LEAVEMENULOOP: { - // pouze predame hlavnimu oknu + // just pass it to the main window return SendMessage(MainWindow->HWindow, uMsg, wParam, lParam); } case WM_USER_CONTEXTMENU: { CMenuPopup* popup = (CMenuPopup*)(CGUIMenuPopupAbstract*)wParam; - // pokud je nad timto panelem otevrene Alt+F1(2) menu a RClick patri jemu, - // predame mu notifikaci + // if the Alt+F1(2) menu is open above this panel and the RClick belongs to it, + // pass the notification to it if (OpenedDrivesList != NULL && OpenedDrivesList->GetMenuPopup() == popup) { return OpenedDrivesList->OnContextMenu((BOOL)lParam, -1, PANEL_SOURCE, NULL); } - return FALSE; //p.s. nespoustet prikaz, neotevirat submenu + return FALSE; //p.s. do not run the command, do not open the submenu } case WM_TIMER: @@ -337,7 +338,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (wParam == IDT_SM_END_NOTIFY) { KillTimer(HWindow, IDT_SM_END_NOTIFY); - if (SmEndNotifyTimerSet) // nejde jen o "zatoulany" WM_TIMER + if (SmEndNotifyTimerSet) // not just a stray WM_TIMER PostMessage(HWindow, WM_USER_SM_END_NOTIFY_DELAYED, 0, 0); SmEndNotifyTimerSet = FALSE; return 0; @@ -347,7 +348,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (wParam == IDT_REFRESH_DIR_EX) { KillTimer(HWindow, IDT_REFRESH_DIR_EX); - if (RefreshDirExTimerSet) // nejde jen o "zatoulany" WM_TIMER + if (RefreshDirExTimerSet) // not just a stray WM_TIMER PostMessage(HWindow, WM_USER_REFRESH_DIR_EX_DELAYED, FALSE, RefreshDirExLParam); RefreshDirExTimerSet = FALSE; return 0; @@ -357,7 +358,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (wParam == IDT_ICONOVRREFRESH) { KillTimer(HWindow, IDT_ICONOVRREFRESH); - if (IconOvrRefreshTimerSet && // nejde jen o "zatoulany" WM_TIMER + if (IconOvrRefreshTimerSet && // not just a stray WM_TIMER Configuration.EnableCustomIconOverlays && Is(ptDisk) && (UseSystemIcons || UseThumbnails) && IconCache != NULL) { @@ -374,7 +375,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (wParam == IDT_INACTIVEREFRESH) { KillTimer(HWindow, IDT_INACTIVEREFRESH); - if (InactiveRefreshTimerSet) // nejde jen o "zatoulany" WM_TIMER + if (InactiveRefreshTimerSet) // not just a stray WM_TIMER { // TRACE_I("Timer IDT_INACTIVEREFRESH: posting refresh!"); PostMessage(HWindow, WM_USER_INACTREFRESH_DIR, FALSE, InactRefreshLParam); @@ -400,12 +401,12 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) else PostMessage(HWindow, WM_USER_REFRESH_DIR_EX_DELAYED, FALSE, lParam); } - else // cekame na poslani WM_USER_REFRESH_DIR_EX_DELAYED + else // waiting for WM_USER_REFRESH_DIR_EX_DELAYED to be posted { - if (RefreshDirExLParam < lParam) // vezmeme "novejsi" cas + if (RefreshDirExLParam < lParam) // take the "newer" time RefreshDirExLParam = lParam; - KillTimer(HWindow, IDT_REFRESH_DIR_EX); // timer nahodime znovu, aby pomaly byl pomaly (5000ms) a rychly byl rychly (200ms) - zkratka nesmi zalezet na typu predchoziho refreshe + KillTimer(HWindow, IDT_REFRESH_DIR_EX); // restart timer so slow remains slow (5000ms) and fast remains fast (200ms) - the previous refresh type must not matter if (!SetTimer(HWindow, IDT_REFRESH_DIR_EX, wParam ? 5000 : 200, NULL)) { RefreshDirExTimerSet = FALSE; @@ -429,52 +430,52 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) } else return 0; - // tady break nechybi -- pokud se nepovede zalozit timer, provede se WM_USER_SM_END_NOTIFY_DELAYED hned + // the break is not missing -- if the timer cannot be started, WM_USER_SM_END_NOTIFY_DELAYED runs immediately } - //--- byl ukoncen suspend mode, podivame se, jestli nepotrebujeme refresh + //--- suspend mode ended; check if a refresh is needed case WM_USER_SM_END_NOTIFY_DELAYED: { if (SnooperSuspended || StopRefresh) - return 0; // pockame na dalsi WM_USER_SM_END_NOTIFY_DELAYED - if (PluginFSNeedRefreshAfterEndOfSM) // ma dojit k refreshi plug-in FS? + return 0; // wait for the next WM_USER_SM_END_NOTIFY_DELAYED + if (PluginFSNeedRefreshAfterEndOfSM) // should the plugin FS be refreshed? { PluginFSNeedRefreshAfterEndOfSM = FALSE; - PostMessage(HWindow, WM_USER_REFRESH_PLUGINFS, 0, 0); // zkusime ho provest ted + PostMessage(HWindow, WM_USER_REFRESH_PLUGINFS, 0, 0); // attempt it now } - if (NeedRefreshAfterEndOfSM) // ma dojit k refreshi? + if (NeedRefreshAfterEndOfSM) // should a refresh occur? { NeedRefreshAfterEndOfSM = FALSE; lParam = RefreshAfterEndOfSMTime; - wParam = FALSE; // nebudeme nahazovat RefreshFinishedEvent + wParam = FALSE; // do not trigger RefreshFinishedEvent } else return 0; } - //--- v adresari byla zaznamenana zmena obsahu pri suspend modu + //--- a directory content change was recorded during suspend mode case WM_USER_S_REFRESH_DIR: { - if (uMsg == WM_USER_S_REFRESH_DIR && // zmena obsahu zaznamenana behem suspend modu + if (uMsg == WM_USER_S_REFRESH_DIR && // content change recorded during suspend mode !IconCacheValid && UseSystemIcons && Is(ptDisk) && GetNetworkDrive()) { // TRACE_I("Delaying refresh from suspend mode until all icons are read."); NeedRefreshAfterIconsReading = TRUE; RefreshAfterIconsReadingTime = max(RefreshAfterIconsReadingTime, (int)lParam); if (wParam) - SetEvent(RefreshFinishedEvent); // nejspis zbytecne, ale je to v popisu WM_USER_S_REFRESH_DIR - return 0; // hlaseni o zmene jsme poznamenali (refresh se postne az se dokonci cteni ikonek), koncime zpracovani + SetEvent(RefreshFinishedEvent); // probably unnecessary but mentioned in WM_USER_S_REFRESH_DIR docs + return 0; // we noted the change (refresh will be posted once icon reading ends); stop processing } setWait = FALSE; if (lParam >= LastRefreshTime) - { // nejde o zbytecny stary refresh - setWait = (GetCursor() != LoadCursor(NULL, IDC_WAIT)); // ceka uz ? + { // not an unnecessary old refresh + setWait = (GetCursor() != LoadCursor(NULL, IDC_WAIT)); // already waiting? if (setWait) oldCur = SetCursor(LoadCursor(NULL, IDC_WAIT)); DWORD err = CheckPath(FALSE, NULL, ERROR_SUCCESS, !SnooperSuspended && !StopRefresh); if (err == ERROR_SUCCESS) { - if (GetMonitorChanges()) // snooper ho mozna vykopnul ze seznamu + if (GetMonitorChanges()) // the snooper might have removed it from the list ChangeDirectory(this, GetPath(), MyGetDriveType(GetPath()) == DRIVE_REMOVABLE); } else @@ -487,7 +488,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) } } } - //--- bylo ukonceno cteni ikonek, podivame se, jestli nepotrebujeme refresh + //--- icon reading has finished; check whether a refresh is needed case WM_USER_ICONREADING_END: { // TRACE_I("WM_USER_ICONREADING_END"); @@ -496,19 +497,19 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { IconCacheValid = TRUE; EndOfIconReadingTime = GetTickCount(); - if (NeedRefreshAfterIconsReading) // ma dojit k refreshi? + if (NeedRefreshAfterIconsReading) // should we refresh? { // TRACE_I("Doing delayed refresh (all icons are read)."); NeedRefreshAfterIconsReading = FALSE; lParam = RefreshAfterIconsReadingTime; - wParam = FALSE; // nebudeme nahazovat RefreshFinishedEvent + wParam = FALSE; // do not trigger RefreshFinishedEvent setWait = FALSE; - probablyUselessRefresh = TRUE; // nejspis jen refresh vyvolany chybne systemem po nacitani ikonek ze sitoveho drivu + probablyUselessRefresh = TRUE; // probably just a refresh incorrectly triggered by the system after loading icons from a network drive // TRACE_I("delayed refresh (after reading of all icons): probablyUselessRefresh=TRUE"); } else { - if (NeedIconOvrRefreshAfterIconsReading) // refreshneme icon-overlays + if (NeedIconOvrRefreshAfterIconsReading) // refresh icon overlays { NeedIconOvrRefreshAfterIconsReading = FALSE; @@ -525,7 +526,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) } } } - //--- v adresari byla zaznamenana zmena obsahu + //--- a directory content change was recorded case WM_USER_REFRESH_DIR: case WM_USER_REFRESH_DIR_EX_DELAYED: case WM_USER_INACTREFRESH_DIR: @@ -535,30 +536,30 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { if (GetTickCount() - EndOfIconReadingTime < 1000) { - probablyUselessRefresh = TRUE; // do 1 sekundy po dokonceni cteni ikon jeste ocekavame zbytecny refresh zpusobeny ctenim ikonek + probablyUselessRefresh = TRUE; // for one second after icon reading finishes, we still expect a redundant refresh caused by icon reading // TRACE_I("less than second after reading of icons was finished: probablyUselessRefresh=TRUE"); } else { - probablyUselessRefresh = (uMsg == WM_USER_REFRESH_DIR_EX_DELAYED || uMsg == WM_USER_INACTREFRESH_DIR); // jde o odlozeny refresh, ktery muze byt take zbytecny (takhle se zamezi nekonecnemu cyklu pri cteni ikon na sitovem disku, ktere vyvolava dalsi refresh) + probablyUselessRefresh = (uMsg == WM_USER_REFRESH_DIR_EX_DELAYED || uMsg == WM_USER_INACTREFRESH_DIR); // deferred refresh that may also be unnecessary (this prevents an infinite loop when reading icons on network drives triggers additional refreshes) // TRACE_I("WM_USER_REFRESH_DIR_EX_DELAYED or WM_USER_INACTREFRESH_DIR: probablyUselessRefresh=" << probablyUselessRefresh); } } - if ((uMsg == WM_USER_REFRESH_DIR && wParam || // zmena obsahu hlasena snooperem - uMsg == WM_USER_ICONREADING_END || // nebo hlaseni konce cteni ikonek (muze prijit pozde, uz se zase muzou cist ikonky) - uMsg == WM_USER_INACTREFRESH_DIR) && // nebo odlozeny refresh v neaktivnim okne (jde o refresh vyzadany snooperem nebo pri ukonceni suspend modu) + if ((uMsg == WM_USER_REFRESH_DIR && wParam || // content change reported by the snooper + uMsg == WM_USER_ICONREADING_END || // or a notification that icon reading finished (it may arrive later, and icon reading may already have restarted) + uMsg == WM_USER_INACTREFRESH_DIR) && // or deferred refresh in an inactive window (refresh requested by the snooper or when ending suspend mode) !IconCacheValid && UseSystemIcons && Is(ptDisk) && GetNetworkDrive()) { // TRACE_I("Delaying refresh until all icons are read."); NeedRefreshAfterIconsReading = TRUE; RefreshAfterIconsReadingTime = max(RefreshAfterIconsReadingTime, (int)lParam); - // hlaseni o zmene jsme poznamenali (refresh se postne az se dokonci cteni ikonek), koncime zpracovani + // the change notification was recorded (refresh will be posted once icon reading finishes), stopping processing } else { if (SnooperSuspended || StopRefresh) - { // uz je zapnuty suspend mode (pracuje se nad vnitrnimi daty -> nelze je refreshnout) + { // suspend mode is already on (working with internal data -> cannot refresh) NeedRefreshAfterEndOfSM = TRUE; RefreshAfterEndOfSMTime = max(RefreshAfterEndOfSMTime, (int)lParam); if ((uMsg == WM_USER_S_REFRESH_DIR || uMsg == WM_USER_SM_END_NOTIFY_DELAYED) && setWait) @@ -566,20 +567,20 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) SetCursor(oldCur); } } - else // nejde o refresh v suspend modu + else // not a refresh during suspend mode { - if (lParam >= LastRefreshTime) // nejde o zbytecny stary refresh + if (lParam >= LastRefreshTime) // not a stale refresh { BOOL isInactiveRefresh = FALSE; BOOL skipRefresh = FALSE; - if ((uMsg == WM_USER_REFRESH_DIR && wParam || // zmena obsahu hlasena snooperem - uMsg == WM_USER_ICONREADING_END || // nebo hlaseni konce cteni ikonek (odlozeny refresh vyzadany snooperem + po ukonceni suspend modu) - uMsg == WM_USER_INACTREFRESH_DIR) && // nebo odlozeny refresh v neaktivnim okne (jde o refresh vyzadany snooperem nebo pri ukonceni suspend modu) - GetForegroundWindow() != MainWindow->HWindow) // neaktivni hlavni okno Salamandera: pribrzdime refreshe, je-li treba + if ((uMsg == WM_USER_REFRESH_DIR && wParam || // content change reported by the snooper + uMsg == WM_USER_ICONREADING_END || // or notification that icon reading finished (deferred refresh requested by the snooper + after ending suspend mode) + uMsg == WM_USER_INACTREFRESH_DIR) && // or deferred refresh in an inactive window (refresh requested by the snooper or when ending suspend mode) + GetForegroundWindow() != MainWindow->HWindow) // inactive Salamander main window: slow down refreshes if needed { // TRACE_I("Refresh from snooper in inactive window"); isInactiveRefresh = TRUE; - if (LastInactiveRefreshStart != LastInactiveRefreshEnd) // nejaky refresh uz probehl od posledni deaktivace + if (LastInactiveRefreshStart != LastInactiveRefreshEnd) // a refresh has already occurred since the last deactivation { DWORD delay = 20 * (LastInactiveRefreshEnd - LastInactiveRefreshStart); // TRACE_I("Calculated delay between refreshes is " << delay); @@ -590,11 +591,11 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) // TRACE_I("Delay between refreshes is " << delay); DWORD ti = GetTickCount(); // TRACE_I("Last refresh was before " << ti - LastInactiveRefreshEnd); - if (InactiveRefreshTimerSet || // timer uz bezi, jen na nej pockame - ti - LastInactiveRefreshEnd + 100 < delay) // +100 aby se timer nenahazoval "zbytecne" (at je odklad refreshe aspon o 100ms) + if (InactiveRefreshTimerSet || // timer already running, just wait for it + ti - LastInactiveRefreshEnd + 100 < delay) // +100 so the timer isn't needlessly set (ensures at least a 100ms refresh delay) { // TRACE_I("Delaying refresh"); - if (!InactiveRefreshTimerSet) // timer jeste nebezi, zalozime ho + if (!InactiveRefreshTimerSet) // timer not running yet, create it { // TRACE_I("Setting timer"); if (SetTimer(HWindow, IDT_INACTIVEREFRESH, max(200, delay - (ti - LastInactiveRefreshEnd)), NULL)) @@ -604,11 +605,11 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) skipRefresh = TRUE; } } - else // timer uz bezi, jen na nej pockame + else // timer is already running; just wait for it { // TRACE_I("Timer already set"); if (lParam > InactRefreshLParam) - InactRefreshLParam = lParam; // prevezmeme novejsi cas do InactRefreshLParam + InactRefreshLParam = lParam; // use the newer time for InactRefreshLParam skipRefresh = TRUE; } } @@ -619,7 +620,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (uMsg == WM_USER_REFRESH_DIR || uMsg == WM_USER_REFRESH_DIR_EX_DELAYED || uMsg == WM_USER_ICONREADING_END || uMsg == WM_USER_INACTREFRESH_DIR) { - setWait = (GetCursor() != LoadCursor(NULL, IDC_WAIT)); // ceka uz ? + setWait = (GetCursor() != LoadCursor(NULL, IDC_WAIT)); // already waiting? if (setWait) oldCur = SetCursor(LoadCursor(NULL, IDC_WAIT)); } @@ -627,7 +628,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) CPanelType typeBackup; if (isInactiveRefresh) { - lstrcpyn(pathBackup, GetPath(), MAX_PATH); // zajimaji nas jen diskove cesty a cesty do archivu (u plugin-FS nas snooper o zmenach neinformuje) + lstrcpyn(pathBackup, GetPath(), MAX_PATH); // we care only about disk paths and archive paths (the snooper does not report changes for plugin FS) typeBackup = GetPanelType(); LastInactiveRefreshStart = GetTickCount(); } @@ -641,17 +642,17 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (isInactiveRefresh) { if (typeBackup != GetPanelType() || StrICmp(pathBackup, GetPath()) != 0) - { // pokud doslo ke zmene cesty (nejspis nekdo prave smazal adresar zobrazeny v panelu), provedeme pripadny dalsi refresh bez cekani (da se ocekavat, ze smazou i adresar nove zobrazeny v panelu, tak abysme z nej umeli rychle "vycouvat") + { // if the path changed (most likely because someone just deleted the directory shown in the panel), perform any further refresh immediately (the newly displayed directory may be deleted as well, so we can back out of it quickly) LastInactiveRefreshEnd = LastInactiveRefreshStart; } else { LastInactiveRefreshEnd = GetTickCount(); if ((int)(LastInactiveRefreshEnd - LastInactiveRefreshStart) <= 0) - LastInactiveRefreshEnd = LastInactiveRefreshStart + 1; // nesmi byt shodne (to je stav "zatim zadny refresh") + LastInactiveRefreshEnd = LastInactiveRefreshStart + 1; // must not be equal (this means "no refresh yet") } } - /* // Petr: nevim proc bylo nastaveni LastRefreshTime az zde - logicky pokud dojde ke zmene behem refreshe, je nutne udelat dalsi refresh - sralo se to v Nethoodu, protoze enumeracni thread stihl postnout refresh jeste pred dokoncenim RefreshDirectory, tedy doslo k jeho vyignorovani (je to refresh behem refreshe) + /* // Petr: It is unclear why LastRefreshTime was set only here. If a change occurs during a refresh, another refresh is required. This caused problems in Nethood because the enumeration thread posted a refresh before RefreshDirectory finished, so it was ignored as a refresh during a refresh. HANDLES(EnterCriticalSection(&TimeCounterSection)); LastRefreshTime = MyTimeCounter++; HANDLES(LeaveCriticalSection(&TimeCounterSection)); @@ -671,12 +672,12 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_USER_REFRESH_PLUGINFS: { if (SnooperSuspended || StopRefresh) - { // uz je zapnuty suspend mode (pracuje se nad vnitrnimi daty -> nelze je refreshnout) - // navic muzeme byt i uvnitr plug-inu -> vicenasobne volani metod plug-inu nepodporujeme + { // suspend mode is already active (working with internal data -> cannot refresh) + // moreover, we might also be inside a plugin -> multiple calls to plugin methods are not supported PluginFSNeedRefreshAfterEndOfSM = TRUE; } else - { // nejsme uvnitr plug-inu + { // we are not inside a plugin if (Is(ptPluginFS)) { if (GetPluginFS()->NotEmpty()) @@ -694,20 +695,20 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (uMsg == WM_USER_REFRESHINDEX) { - // pokud slo o nacteni "staticke" ikony asociace, ulozime ji do Associations (pocita - // i s thumbnaily - nedopadne podminka na Flag==1 nebo 2) - if (file != NULL && !isDir && // jde o soubor - (!Is(ptPluginFS) || GetPluginIconsType() != pitFromPlugin)) // nejde o ikonu z plug-inu + // if a "static" association icon was loaded, store it in Associations + // also covers thumbnails - the Flag==1 or 2 condition does not apply + if (file != NULL && !isDir && // this is a file + (!Is(ptPluginFS) || GetPluginIconsType() != pitFromPlugin)) // not an icon from a plugin { - char buf[MAX_PATH + 4]; // pripona malymi pismeny + char buf[MAX_PATH + 4]; // extension in lowercase char *s1 = buf, *s2 = file->Ext; while (*s2 != 0) *s1++ = LowerCase[*s2++]; *((DWORD*)s1) = 0; int index; CIconSizeEnum iconSize = IconCache->GetIconSize(); - if (Associations.GetIndex(buf, index) && // pripona ma ikonku (asociaci) - (Associations[index].GetIndex(iconSize) == -1 || // jde o ikonku, ktera se nacita + if (Associations.GetIndex(buf, index) && // the extension has an icon (association) + (Associations[index].GetIndex(iconSize) == -1 || // this icon is being loaded Associations[index].GetIndex(iconSize) == -3)) { int icon; @@ -715,16 +716,16 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) int srcIconListIndex; memmove(buf, file->Name, file->NameLen); *(DWORD*)(buf + file->NameLen) = 0; - if (IconCache->GetIndex(buf, icon, NULL, NULL) && // icon-thread ji nacita - (IconCache->At(icon).GetFlag() == 1 || IconCache->At(icon).GetFlag() == 2) && // ikona je nactena nova nebo stara + if (IconCache->GetIndex(buf, icon, NULL, NULL) && // the icon thread is loading it + (IconCache->At(icon).GetFlag() == 1 || IconCache->At(icon).GetFlag() == 2) && // icon is loaded new or old IconCache->GetIcon(IconCache->At(icon).GetIndex(), - &srcIconList, &srcIconListIndex)) // povede se ziskat nactenou ikonku - { // ikonka pro priponu -> icon-thread uz ji nacetl + &srcIconList, &srcIconListIndex)) // able to obtain the loaded icon + { // icon for the extension -> icon thread has already loaded it CIconList* dstIconList; int dstIconListIndex; int i = Associations.AllocIcon(&dstIconList, &dstIconListIndex, iconSize); - if (i != -1) // ziskali jsme misto pro novou ikonku - { // nakopirujeme si ji z IconCache do Associations + if (i != -1) // we obtained space for a new icon + { // copy it from IconCache to Associations Associations[index].SetIndex(i, iconSize); BOOL leaveSection; @@ -745,13 +746,13 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (!StopIconRepaint) { - // panely prekreslime pouze pokud odpovidaji velikosti ikon + // repaint panels only if the icon sizes match if (iconSize == GetIconSizeForCurrentViewMode()) - RepaintIconOnly(-1); // u nas vsechny + RepaintIconOnly(-1); // all of ours CFilesWindow* otherPanel = MainWindow->GetOtherPanel(this); if (iconSize == otherPanel->GetIconSizeForCurrentViewMode()) - otherPanel->RepaintIconOnly(-1); // a u sousedu vsechny + otherPanel->RepaintIconOnly(-1); // and all in the other panel } else PostAllIconsRepaint = TRUE; @@ -761,10 +762,10 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) } } - // provedeme prekresleni postizeneho indexu - if (file != NULL) // file se zde pouziva jen pro test na NULL + // redraw the affected index + if (file != NULL) // file is used here only to test for NULL { - if (!StopIconRepaint) // pokud je povoleno prekreslovani ikon + if (!StopIconRepaint) // if icon repainting is allowed RepaintIconOnly((int)wParam); else PostAllIconsRepaint = TRUE; @@ -800,7 +801,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_USER_CHANGEDIR: { - // postprocessing provedeme jen u cest, ktere jsme ziskali jako text (a ne primo dropnutim adresare) + // postprocess only paths obtained as text (not directly from a dropped directory) char buff[2 * MAX_PATH]; strcpy_s(buff, (char*)lParam); if (!(BOOL)wParam || PostProcessPathFromUser(HWindow, buff)) @@ -810,8 +811,8 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_USER_FOCUSFILE: { - // Musime okno vytahnout uz tady, protoze behem volani ChangeDir muze dojit - // k vyskoceni messageboxu (cesta neexistuje) a ten by zustal pod Findem. + // We must bring the window to the front here because calling ChangeDir can + // pop up a message box (the path does not exist) which would otherwise remain under Find. SetForegroundWindow(MainWindow->HWindow); if (IsIconic(MainWindow->HWindow)) { @@ -822,7 +823,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { strcpy(NextFocusName, (char*)wParam); SendMessage(HWindow, WM_USER_DONEXTFOCUS, 0, 0); - // SetForegroundWindow(MainWindow->HWindow); // tady uz je pozde - presunuto nahoru + // SetForegroundWindow(MainWindow->HWindow); // it's too late here - moved above UpdateWindow(MainWindow->HWindow); } return 0; @@ -845,14 +846,14 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_USER_VIEWFILEWITH: { COpenViewerData* data = (COpenViewerData*)wParam; - ViewFile(data->FileName, FALSE, (DWORD)lParam, data->EnumFileNamesSourceUID, // FIXME_X64 - overit pretypovani na (DWORD) + ViewFile(data->FileName, FALSE, (DWORD)lParam, data->EnumFileNamesSourceUID, // FIXME_X64 - verify cast to (DWORD) data->EnumFileNamesLastFileIndex); return 0; } case WM_USER_EDITFILEWITH: { - EditFile((char*)wParam, (DWORD)lParam); // FIXME_X64 - overit pretypovani na (DWORD) + EditFile((char*)wParam, (DWORD)lParam); // FIXME_X64 - verify cast to (DWORD) return 0; } @@ -863,10 +864,10 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) // return 0; // } - case WM_USER_DONEXTFOCUS: // pokud to jiz nestihl RefreshDirectory, udelame to tady + case WM_USER_DONEXTFOCUS: // if RefreshDirectory did not manage it already, do it here { DontClearNextFocusName = FALSE; - if (NextFocusName[0] != 0) // je-li co fokusit + if (NextFocusName[0] != 0) // if there is something to focus { int total = Files->Count + Dirs->Count; int found = -1; @@ -876,14 +877,14 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) CFileData* f = (i < Dirs->Count) ? &Dirs->At(i) : &Files->At(i - Dirs->Count); if (StrICmp(f->Name, NextFocusName) == 0) { - if (strcmp(f->Name, NextFocusName) == 0) // soubor nalezen presne + if (strcmp(f->Name, NextFocusName) == 0) // file found with exact case match { NextFocusName[0] = 0; SetCaretIndex(i, FALSE); break; } if (found == -1) - found = i; // soubor nalezen (ignore-case) + found = i; // file found (case-insensitive) } } if (i == total && found != -1) @@ -927,7 +928,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (plSizeValid || sizeValid && (!isDir || f->SizeValid)) selectedSize += plSizeValid ? plSize : f->Size; else - displaySize = FALSE; // soubor nezname velikosti nebo adresar bez zname/vypocitane velikosti + displaySize = FALSE; // file of unknown size or directory without known/calculated size } } if (files > 0 || dirs > 0) @@ -950,7 +951,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) StatusLine->SetSubTexts(varPlacements, varPlacementsCount); } else - varPlacementsCount = 100; // mohlo se poskodit + varPlacementsCount = 100; // might have been corrupted } } if (!done) @@ -965,7 +966,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) ExpandPluralFilesDirs(text, 200, files, dirs, epfdmSelected, FALSE); if (StatusLine->SetText(text) && displaySize) StatusLine->SetSubTexts(varPlacements, varPlacementsCount); - varPlacementsCount = 100; // mohlo se poskodit + varPlacementsCount = 100; // might have been corrupted } } else @@ -976,25 +977,25 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { LastFocus = INT_MAX; int index = GetCaretIndex(); - ItemFocused(index); // pri odznaceni + ItemFocused(index); // when deselecting } - IdleRefreshStates = TRUE; // pri pristim Idle vynutime kontrolu stavovych promennych + IdleRefreshStates = TRUE; // at the next Idle enforce checking of state variables return 0; } case WM_CREATE: { - //--- pridani tohoto panelu do pole zdroju pro enumeraci souboru ve viewerech + //--- add this panel to the array of sources for file enumeration in viewers EnumFileNamesAddSourceUID(HWindow, &EnumFileNamesSourceUID); - //--- vytvoreni listboxu se soubory a adresari + //--- create listbox with files and directories ListBox = new CFilesBox(this); if (ListBox == NULL) { TRACE_E(LOW_MEMORY); return -1; } - //--- vytvoreni statusliny s informacemi o akt. souboru + //--- create status line with information about the current file StatusLine = new CStatusWindow(this, blBottom, ooStatic); if (StatusLine == NULL) { @@ -1002,7 +1003,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) return -1; } ToggleStatusLine(); - //--- vytvoreni statusliny s informacemi o akt. adresari + //--- create status line with information about the current directory DirectoryLine = new CStatusWindow(this, blTop, ooStatic); if (DirectoryLine == NULL) { @@ -1011,8 +1012,8 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) } DirectoryLine->SetLeftPanel(MainWindow->LeftPanel == this); ToggleDirectoryLine(); - //--- nahozeni typu viewu + nacteni obsahu adresare - SetThumbnailSize(Configuration.ThumbnailSize); // musi existovat ListBox + //--- apply view type and load directory contents + SetThumbnailSize(Configuration.ThumbnailSize); // ListBox must exist if (!ListBox->CreateEx(WS_EX_WINDOWEDGE, CFILESBOX_CLASSNAME, "", @@ -1045,7 +1046,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) SelectViewTemplate(index, FALSE, FALSE); ShowWindow(ListBox->HWindow, SW_SHOW); - // srovname nastaveni promenne AutomaticRefresh a directory-liny + // align AutomaticRefresh variable with the directory line SetAutomaticRefresh(AutomaticRefresh, TRUE); return 0; @@ -1053,18 +1054,18 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_DESTROY: { - //--- zruseni tohoto panelu z pole zdroju pro enumeraci souboru ve viewerech + //--- remove this panel from the array of sources for file enumeration in viewers EnumFileNamesRemoveSourceUID(HWindow); CancelUI(); // cancel QuickSearch and QuickEdit LastRefreshTime = INT_MAX; BeginStopRefresh(); DetachDirectory(this); - //--- uvolneni child-oken + //--- release child windows RevokeDragDrop(); ListBox->DetachWindow(); delete ListBox; - ListBox = NULL; // pro jistotu, at se chyby ukazou... + ListBox = NULL; // just to be sure so errors show up... StatusLine->DestroyWindow(); delete StatusLine; @@ -1072,16 +1073,16 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) DirectoryLine->DestroyWindow(); delete DirectoryLine; - DirectoryLine = NULL; // oprava padacky + DirectoryLine = NULL; // fix for crash //--- return 0; } - case WM_USER_ENUMFILENAMES: // hledani dalsiho/predchoziho jmena pro viewer + case WM_USER_ENUMFILENAMES: // searching for next/previous name for the viewer { HANDLES(EnterCriticalSection(&FileNamesEnumDataSect)); - if (InactiveRefreshTimerSet) // pokud je zde odlozeny refresh, musime jej provest ihned, jinak budeme enumerovat nad neaktualnim listingem; pokud bude dele trvat nevadi, GetFileNameForViewer si na vysledek pocka... + if (InactiveRefreshTimerSet) // if a refresh is pending here, execute it now; otherwise enumeration would use an outdated listing; a longer delay is fine, GetFileNameForViewer waits for the result... { // TRACE_I("Refreshing during enumeration (refresh in inactive window was delayed)"); KillTimer(HWindow, IDT_INACTIVEREFRESH); @@ -1090,14 +1091,14 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) SendMessage(HWindow, WM_USER_INACTREFRESH_DIR, FALSE, InactRefreshLParam); } - if ((int)wParam /* reqUID */ == FileNamesEnumData.RequestUID && // nedoslo k zadani dalsiho pozadaku (tento by pak byl k nicemu) - EnumFileNamesSourceUID == FileNamesEnumData.SrcUID && // nedoslo ke zmene zdroje - !FileNamesEnumData.TimedOut) // na vysledek jeste nekdo ceka + if ((int)wParam /* reqUID */ == FileNamesEnumData.RequestUID && // no new request was made (otherwise this one would be useless) + EnumFileNamesSourceUID == FileNamesEnumData.SrcUID && // the source hasn't changed + !FileNamesEnumData.TimedOut) // someone is still waiting for the result { if (Files != NULL && Is(ptDisk)) { BOOL selExists = FALSE; - if (FileNamesEnumData.PreferSelected) // je-li to treba, zjistime jestli existuje selectiona + if (FileNamesEnumData.PreferSelected) // if needed, check whether anything is selected { int i; for (i = 0; i < Files->Count; i++) @@ -1113,19 +1114,19 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) int index = FileNamesEnumData.LastFileIndex; int count = Files->Count; BOOL indexNotFound = TRUE; - if (index == -1) // hledame od prvniho nebo od posledniho + if (index == -1) // searching from the first or last item { if (FileNamesEnumData.RequestType == fnertFindPrevious) - index = count; // hledame predchozi + mame zacit na poslednim - // else // hledame nasledujici + mame zacit na prvnim + index = count; // searching for the previous item + start at the last item + // else // searching for the next item + start at the first item } else { - if (FileNamesEnumData.LastFileName[0] != 0) // zname plne jmeno souboru na 'index', zkontrolujeme jestli nedoslo k rozesunuti/sesunuti pole + pripadne dohledame novy index + if (FileNamesEnumData.LastFileName[0] != 0) // we know the full file name at 'index', so check whether the array shifted and, if needed, find the new index { int pathLen = (int)strlen(GetPath()); if (StrNICmp(GetPath(), FileNamesEnumData.LastFileName, pathLen) == 0) - { // cesta k souboru se musi shodovat s cestou v panelu ("always true") + { // file path must match the path in the panel ("always true") const char* name = FileNamesEnumData.LastFileName + pathLen; if (*name == '\\' || *name == '/') name++; @@ -1135,11 +1136,11 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (nameIsSame) indexNotFound = FALSE; if (f == NULL || !nameIsSame) - { // jmeno na indexu 'index' neni FileNamesEnumData.LastFileName, zkusime najit novy index tohoto jmena + { // the name at index 'index' is not FileNamesEnumData.LastFileName, try to find a new index for this name int i; for (i = 0; i < count && StrICmp(name, Files->At(i).Name) != 0; i++) ; - if (i != count) // novy index nalezen + if (i != count) // new index found { indexNotFound = FALSE; index = i; @@ -1162,9 +1163,9 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) int wantedViewerType = 0; BOOL onlyAssociatedExtensions = FALSE; - if (FileNamesEnumData.OnlyAssociatedExtensions) // preje si viewer filtrovani podle asociovanych pripon? + if (FileNamesEnumData.OnlyAssociatedExtensions) // does the viewer request filtering by associated extensions? { - if (FileNamesEnumData.Plugin != NULL) // viewer z pluginu + if (FileNamesEnumData.Plugin != NULL) // viewer from a plugin { int pluginIndex = Plugins.GetIndex(FileNamesEnumData.Plugin); if (pluginIndex != -1) // "always true" @@ -1173,7 +1174,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) onlyAssociatedExtensions = TRUE; } } - else // interni viewer + else // internal viewer { wantedViewerType = VIEWER_INTERNAL; onlyAssociatedExtensions = TRUE; @@ -1183,7 +1184,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) BOOL preferSelected = selExists && FileNamesEnumData.PreferSelected; switch (FileNamesEnumData.RequestType) { - case fnertFindNext: // dalsi + case fnertFindNext: // next { CDynString strViewerMasks; if (!onlyAssociatedExtensions || MainWindow->GetViewersAssoc(wantedViewerType, &strViewerMasks)) @@ -1212,7 +1213,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) break; } - case fnertFindPrevious: // predchozi + case fnertFindPrevious: // previous { CDynString strViewerMasks; if (!onlyAssociatedExtensions || MainWindow->GetViewersAssoc(wantedViewerType, &strViewerMasks)) @@ -1241,7 +1242,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) break; } - case fnertIsSelected: // zjisteni oznaceni + case fnertIsSelected: // query selection { if (!indexNotFound && index >= 0 && index < Files->Count) { @@ -1251,7 +1252,7 @@ CFilesWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) break; } - case fnertSetSelection: // nastaveni oznaceni + case fnertSetSelection: // set selection { if (!indexNotFound && index >= 0 && index < Files->Count) { @@ -1324,7 +1325,7 @@ void CFilesWindow::OpenDirHistory() if (!MainWindow->DirHistory->HasPaths()) return; - BeginStopRefresh(); // cmuchal si da pohov + BeginStopRefresh(); // snooper takes a break CMenuPopup menu; @@ -1347,14 +1348,14 @@ void CFilesWindow::OpenDirHistory() if (cmd != 0) MainWindow->DirHistory->Execute(cmd, FALSE, this, TRUE, FALSE); - EndStopRefresh(); // ted uz zase cmuchal nastartuje + EndStopRefresh(); // the snooper will start again now } void CFilesWindow::OpenStopFilterMenu() { CALL_STACK_MESSAGE1("CFilesWindow::OpenStopFilterMenu()"); - BeginStopRefresh(); // cmuchal si da pohov + BeginStopRefresh(); // snooper takes a break CMenuPopup menu; @@ -1371,8 +1372,8 @@ void CFilesWindow::OpenStopFilterMenu() } } - /* slouzi pro skript export_mnu.py, ktery generuje salmenu.mnu pro Translator - udrzovat synchronizovane s volanim InsertItem() dole... + /* used by the export_mnu.py script which generates salmenu.mnu for the Translator + keep synchronized with the InsertItem() calls below... MENU_TEMPLATE_ITEM StopFilterMenu[] = { {MNTT_PB, 0 @@ -1423,19 +1424,19 @@ MENU_TEMPLATE_ITEM StopFilterMenu[] = } } - EndStopRefresh(); // ted uz zase cmuchal nastartuje + EndStopRefresh(); // the snooper will start again now } -// na zaklade dostupnych sloupcu naplni popup +// fills the popup based on available columns BOOL CFilesWindow::FillSortByMenu(CMenuPopup* popup) { CALL_STACK_MESSAGE1("CFilesWindow::FillSortByMenu()"); - // sestrelime existujici polozky + // remove existing items popup->RemoveAllItems(); - /* slouzi pro skript export_mnu.py, ktery generuje salmenu.mnu pro Translator - udrzovat synchronizovane s volanim InsertItem() dole... + /* used by the export_mnu.py script which generates salmenu.mnu for the Translator + keep synchronized with the InsertItem() calls below... MENU_TEMPLATE_ITEM SortByMenu[] = { {MNTT_PB, 0 @@ -1449,9 +1450,9 @@ MENU_TEMPLATE_ITEM SortByMenu[] = }; */ - // docasne reseni pro 1.6 beta 6: naleju vzdy (bez ohledu na ValidFileData) - // polozky Name, Ext, Date, Size - // poradi musi korespondovat s CSortType enumem + // temporary solution for 1.6 beta 6: always populate the + // Name, Ext, Date, and Size entries (regardless of ValidFileData) + // the order must correspond to the CSortType enum int textResID[5] = {IDS_COLUMN_MENU_NAME, IDS_COLUMN_MENU_EXT, IDS_COLUMN_MENU_TIME, IDS_COLUMN_MENU_SIZE, IDS_COLUMN_MENU_ATTR}; int leftCmdID[5] = {CM_LEFTNAME, CM_LEFTEXT, CM_LEFTTIME, CM_LEFTSIZE, CM_LEFTATTR}; int rightCmdID[5] = {CM_RIGHTNAME, CM_RIGHTEXT, CM_RIGHTTIME, CM_RIGHTSIZE, CM_RIGHTATTR}; @@ -1500,7 +1501,7 @@ void CFilesWindow::SetThumbnailSize(int size) { if (size != ListBox->ThumbnailWidth || size != ListBox->ThumbnailHeight) { - // vycisteni icon-cache + // clear the icon cache SleepIconCacheThread(); IconCache->Release(); EndOfIconReadingTime = GetTickCount() - 10000; @@ -1530,7 +1531,7 @@ void CFilesWindow::SetFont() { if (DirectoryLine != NULL) DirectoryLine->SetFont(); - //if (ListBox != NULL) // toto se nastavi z volani SetFont() + //if (ListBox != NULL) // this is set by the SetFont() call // ListBox->SetFont(); if (StatusLine != NULL) StatusLine->SetFont(); diff --git a/src/fileswnd.h b/src/fileswnd.h index 79e605b94..48db91d1b 100644 --- a/src/fileswnd.h +++ b/src/fileswnd.h @@ -70,7 +70,7 @@ struct CTmpDragDropOperData CDragDropOperData* Data; }; -class CCriteriaData // data pro atCopy/atMove +class CCriteriaData // data for atCopy/atMove { public: BOOL OverwriteOlder; // overwrite older, skip newer ones @@ -371,7 +371,7 @@ class CTopIndexMem TopIndexesCount = 0; } // clears memory void Push(const char* path, int topIndex); // stores the top index for the given path - BOOL FindAndPop(const char* path, int& topIndex); // looks for the top index of the path, FALSE -> not found + BOOL FindAndPop(const char* path, int& topIndex); // finds the top index for the given path; returns FALSE if not found }; //****************************************************************************** @@ -483,7 +483,7 @@ class CFilesWindowAncestor : public CWindow // the real object core - everything BOOL MonitorChanges; // should changes be monitored (auto refresh)? UINT DriveType; // disk+archive: drive type of Path (see MyGetDriveType()) - // when we are inside an archive: + // when browsing an archive: CSalamanderDirectory* ArchiveDir; // content of the open archive; basic data - array of CFileData char ZIPArchive[MAX_PATH]; // path to the open archive char ZIPPath[MAX_PATH]; // path inside the open archive @@ -491,31 +491,31 @@ class CFilesWindowAncestor : public CWindow // the real object core - everything CQuadWord ZIPArchiveSize; // archive size - used to detect archive changes // when browsing a plugin file system: - CPluginFSInterfaceEncapsulation PluginFS; // pointer to the open FS + CPluginFSInterfaceEncapsulation PluginFS; // encapsulation of the open FS CSalamanderDirectory* PluginFSDir; // content of the open FS; basic data - array of CFileData - int PluginIconsType; // icon type in the panel when listing a FS + int PluginIconsType; // icon type in the panel when browsing a plugin FS // when viewing an archive listed by a plugin or within a plugin FS CPluginInterfaceAbstract* PluginIface; // use exclusively for locating the plugin in Plugins (not for invoking methods) int PluginIfaceLastIndex; // index of PluginIface in Plugins during the last search, use only to locate the plugin public: - // contents of all columns shown in the panel (both basic data and plug-in data for archives and FS) + // contents of all columns shown in the panel (both basic data and plugin data for archives and FS) CFilesArray* Files; // filtered list of files (shallow copy; basic data - CFileData structure) CFilesArray* Dirs; // filtered list of directories (shallow copy; basic data - CFileData structure) - // interface used to obtain plug-in specific data; data for plug-in columns; defines how - // to use CFileData::PluginData; for FS plug-ins with pitFromPlugin icons, it is also used to + // interface used to obtain plugin specific data; data for plugin columns; defines how + // to use CFileData::PluginData; for FS plugins with pitFromPlugin icons, it is also used to // retrieving icons "in the background" in the icon reader thread - before making any changes, call SleepIconCacheThread() CPluginDataInterfaceEncapsulation PluginData; - CIconList* SimplePluginIcons; // FS + pitFromPlugin only: image list with simple plug-in icons + CIconList* SimplePluginIcons; // FS + pitFromPlugin only: image list with simple plugin icons // current number of selected items; must be updated everywhere the variable // CFileData::Selected is modified int SelectedCount; // helper variables used for smoother refresh (without "the panel contains no items") - // for plug-in file systems: + // for plugin file systems: // TRUE = the listing should not be released in a standard way but only detached (objects from NewFSXXX will continue // to be used) BOOL OnlyDetachFSListing; @@ -529,7 +529,7 @@ class CFilesWindowAncestor : public CWindow // the real object core - everything ~CFilesWindowAncestor(); // NULL -> Path; echo && err != ERROR_SUCCESS -> only report the error - // 'parent' is the parent of the message box (NULL == HWindow) + // 'parent' is the parent window of the message box (NULL == HWindow) DWORD CheckPath(BOOL echo, const char* path = NULL, DWORD err = ERROR_SUCCESS, BOOL postRefresh = TRUE, HWND parent = NULL); @@ -640,7 +640,7 @@ enum CCopyFocusedNameModeEnum class CVisibleItemsArray { protected: - CRITICAL_SECTION Monitor; // section used to synchronize this object (monitor behavior) + CRITICAL_SECTION Monitor; // critical section used to synchronize this object (monitor behavior) BOOL SurroundArr; // TRUE/FALSE = array of items around the visible area / array ofitems only from the visible area @@ -678,8 +678,9 @@ class CVisibleItemsArray // called only by the icon reader BOOL ArrContains(const char* name, BOOL* isArrValid, int* versionNum); - // If the array is filled and valid and contains the given index 'index', it returns - // TRUE; moreover, in 'isArrValid', it returns TRUE if the array is filled and valid and in 'versionNum' the number of the array version + // Returns TRUE if the array is populated, valid, and contains index 'index'; + // additionally, stores in 'isArrValid' whether the array is valid and in 'versionNum' + // the array version number // Called only by the icon reader BOOL ArrContainsIndex(int index, BOOL* isArrValid, int* versionNum); }; @@ -715,12 +716,12 @@ class CFilesWindow : public CFilesWindowAncestor // If a filesystem is attached, it may modify these columns: new // columns can appear and some of the visible ones may be temporarily removed TDirectArray ColumnsTemplate; // template for the Columns variable - // Firstly, this template is built from the current 'ViewTemplate' - // and panel content type (disk / archive + FS). Then the template is - // copied into Columns. Added for performance so we do not build the - // array repeatedly. + // This template is first built from the current 'ViewTemplate' + // and panel content type (disk / archive + FS). It is then + // copied into Columns. Introduced for performance so the + // array does not have to be rebuilt repeatedly. BOOL ColumnsTemplateIsForDisk; // TRUE = if ColumnsTemplate was built for a disk, otherwise for archive or FS - FGetPluginIconIndex GetPluginIconIndex; // callback for retrieving a simple icon index for plug-ins + FGetPluginIconIndex GetPluginIconIndex; // callback for retrieving a simple icon index for plugins // with their own icons (FS, pitFromPlugin) CFilesMap FilesMap; // used for selecting items by dragging a selection box @@ -728,7 +729,7 @@ class CFilesWindow : public CFilesWindowAncestor CIconCache* IconCache; // cache containing icons directly from files BOOL IconCacheValid; // is the cache already loaded? - BOOL InactWinOptimizedReading; // TRUE = only icons/thumbnails/overlays from the visible part of the panel are being read (used when the main window is inactive and a refresh is triggered – we try to minimize system load as we're "in the background") + BOOL InactWinOptimizedReading; // TRUE = read only icons/thumbnails/overlays from the visible part of the panel (used when the main window is inactive and a refresh is triggered to minimize system load because the application is "in the background") DWORD WaitBeforeReadingIcons; // how many milliseconds to wait before the icon reader starts reading icons (used on refresh; while waiting old icons can be pushed into the cache to avoid repeated reading and endless refreshes on network drives) DWORD WaitOneTimeBeforeReadingIcons; // how many milliseconds to wait before starting to read icons, then this value resets (used to catch batches of changes from Tortoise SVN, see IconOverlaysChangedOnPath()) DWORD EndOfIconReadingTime; // GetTickCount() from the moment all icons were loaded in the panel @@ -785,10 +786,10 @@ class CFilesWindow : public CFilesWindowAncestor // as a recipient of device event notifications (used to detect the media before // it is disconnected from the computer) - // should icons be retrieved from files on this disk?? - // For ptDisk: TRUE if icons are retrieved from files; for ptZIPArchive: TRUE - // if icons are retrieved from the registry; for ptPluginFs: TRUE if icons are retrieved from the registry (pitFromRegistry) or - // directly from the plug-in (pitFromPlugin) + // should icons be retrieved from files on this disk? + // for ptDisk, TRUE if icons are retrieved from files; for ptZIPArchive, TRUE if + // icons are retrieved from the registry; for ptPluginFS, TRUE if icons are retrieved + // from the registry (pitFromRegistry) or directly from the plugin (pitFromPlugin) BOOL UseSystemIcons; BOOL UseThumbnails; // TRUE when thumbnails are displayed in the panel and loaded in the icon reader @@ -800,7 +801,7 @@ class CFilesWindow : public CFilesWindowAncestor BOOL NeedRefreshAfterEndOfSM; // will a refresh be needed after exiting suspend mode? int RefreshAfterEndOfSMTime; // "time" of the latest refresh that arrived after suspend mode started - BOOL PluginFSNeedRefreshAfterEndOfSM; // will the plug-in FS need a refresh after leaving suspend mode? + BOOL PluginFSNeedRefreshAfterEndOfSM; // will the plugin FS need a refresh after leaving suspend mode? BOOL SmEndNotifyTimerSet; // TRUE when the timer for sending WM_USER_SM_END_NOTIFY_DELAYED is running BOOL RefreshDirExTimerSet; // TRUE when the timer for sending WM_USER_REFRESH_DIR_EX_DELAYED is running @@ -814,7 +815,7 @@ class CFilesWindow : public CFilesWindowAncestor BOOL NeedRefreshAfterIconsReading; // is a refresh needed after icon reading finishes? int RefreshAfterIconsReadingTime; // "time" of the latest refresh that arrived while icons were being read - CPathHistory* PathHistory; // browsing history for this panel (for the panel) + CPathHistory* PathHistory; // browsing history for this panel DWORD HiddenDirsFilesReason; // bit field indicating the reason why files/directories are hidden (HIDDEN_REASON_xxx) int HiddenDirsCount, // number of hidden directories in the panel (number of skipped ones) @@ -860,9 +861,9 @@ class CFilesWindow : public CFilesWindowAncestor BOOL DragSelect; // mode for marking/unmarking by mouse drag BOOL BeginDragDrop; // are we dragging the file? BOOL DragDropLeftMouseBtn; // TRUE = drag&drop with left mouse button, FALSE = with the right one - BOOL BeginBoxSelect; // are we "opening" the selection box? + BOOL BeginBoxSelect; // start of selection box BOOL PersistentTracking; // during WM_CAPTURECHANGED, tracking mode will not be disabled - BOOL SelectItems; // during Drag Select, do we mark items? + BOOL SelectItems; // mark items during Drag Select? BOOL FocusedSinceClick; // the item already had focus when we clicked it BOOL CutToClipChanged; // is at least one CutToClip flag set on files/directories? @@ -930,26 +931,31 @@ class CFilesWindow : public CFilesWindowAncestor // returns TRUE if the path is accessible BOOL CheckAndRestorePath(const char* path); - // recognizes the path type (FS/Windows/archive) and splits it into components: - // for FS paths it's fs-name and fs-user-part; for archives it's path-to-archive and - // path-in-archive; for Windows paths it's an existing part and the remaining path. for FS paths, nothing is checked, - // for Windows (normal/UNC) paths, it checks how far the path exists (possibly restore network paths), - // for archives, it checks whether the archive file exists (determined by extension); - // 'path' is a full or relative path (for relative paths, the path in the active panel is used as the base for evaluating the full path). The resulting full path is - // stored back into 'path' (buffer must be at least 'pathBufSize' characters). Returns TRUE - // when recognized successfully, setting 'type' to PATH_TYPE_XXX and 'pathPart' as follows: - // - for Windows paths, pointer just after the existing path (after '\\' or at the end of string); - // if a file exists in the path, it points after the path to this file, WARNING: the returned part length is not - // checked and may exceed MAX_PATH. - // - for archive paths, pointer past the archive file; WARNING: again the length inside the archive is not checked and can - // exceed MAX_PATH. - // - for FS paths, pointer after ':' following the file-system name (user - part of the path); - // WARNING: length of user - part path isn't checked and may exceed MAX_PATH. - // On success, 'isDir' is TRUE if the first part of the path up to 'pathPart' is a directory, - // FALSE if it's a file (Windows paths). For archive and FS paths, 'isDir' is FALSE. - // If it returns FALSE, an error that occurred during recognition was already displayed to the user, 'errorTitle' is the message box title with the error. - // If 'nextFocus' is not NULL and the Windows/archive path doesn't contain '\\' or ends with - // it, the path is copied to 'nextFocus' (see SalGetFullName) + // Recognizes the path type (FS/Windows/archive) and splits it into its parts: + // for FS paths, into fs-name and fs-user-part; for archive paths, into path-to-archive and + // path-in-archive; for Windows paths, into the existing part and the rest of the path. FS paths + // are not checked; for Windows (normal/UNC) paths, it checks how much of the path exists + // (and may restore the network connection); for archive paths, it checks whether the archive file + // exists (archive type is determined by the extension); + // 'path' is a full or relative path (for relative paths, the path in the active panel is used + // as the base for resolving the full path); the resulting full path is stored back into 'path' + // (the buffer must be at least 'pathBufSize' characters). Returns TRUE on successful recognition; + // then 'type' is the path type (see PATH_TYPE_XXX) and 'secondPart' is set: + // - in 'path' to the position after the existing path (after '\\' or at the end of the string; + // if the path contains a file, it points past the path to that file) (Windows path type), WARNING: + // the length of the returned part of the path is not checked (the whole path may be longer than MAX_PATH) + // - after the archive file (archive path type), WARNING: the length of the path inside the archive is not checked + // (it may be longer than MAX_PATH) + // - after ':' following the file system name, to the user part of the file system path (FS path type), WARNING: + // the length of the user part is not checked (it may be longer than MAX_PATH); + // if TRUE is returned, 'isDir' is also set to: + // - TRUE if the first part of the path (from the beginning up to 'secondPart') is a directory, FALSE if it is a file + // (Windows path type) + // - FALSE for archive and FS paths; + // if FALSE is returned, an error that occurred during recognition has already been reported to the user; + // 'errorTitle' is the title of the error message box; if 'nextFocus' != NULL and the Windows/archive + // path does not contain '\\' or only ends with '\\', the path is copied to 'nextFocus' (see + // SalGetFullName) BOOL ParsePath(char* path, int& type, BOOL& isDir, char*& secondPart, const char* errorTitle, char* nextFocus, int* error, int pathBufSize); @@ -965,12 +971,12 @@ class CFilesWindow : public CFilesWindowAncestor // when 0, a dialog is shown, the change is applied immediately void ChangeDrive(char drive = 0); - // it finds the first fixed drive and switches to it; - // 'parent' is the parent of message boxes; - // if 'noChange' is not NULL it returns TRUE if the panel listing data (Files + Dirs) - // were not recreated again; + // finds the first fixed drive and switches to it; + // 'parent' is the parent window for message boxes; + // if 'noChange' is not NULL, it returns TRUE if the panel listing data (Files + Dirs) + // were not recreated; // if 'refreshListBox' is FALSE, RefreshListBox is not called; - // if 'canForce' is TRUE, the user can forcibly close even a path the plug-in refuses to close; + // if 'canForce' is TRUE, the user gets a chance to forcibly close even a path the plugin refuses to close; // if 'failReason' != NULL, it is set to one of the CHPPFR_XXX constants; // only for FS in panel: 'tryCloseReason' is the reason passed to CPluginFSInterfaceAbstract::TryCloseOrDetach(); // returns TRUE on success @@ -985,34 +991,36 @@ class CFilesWindow : public CFilesWindowAncestor int* failReason = NULL); // helper method: - // serves as preparation for CloseCurrentPath, prepares closing/detached the current path (updates - // edited files and calls CanCloseArchive for archives; TryCloseOrDetach for FS); - // returns TRUE if the path can be closed/detached by the upcoming CloseCurrentPath call, - // returns FALSE if it cannot close/defer(the current path won't change or close); - // when 'canForce' is TRUE, the user may forcibly close even a path the plug-in doesn't want - // to close (necessary when closing Salamander – if there is a bug in the plug-in, Salamander would otherwise not close); - // when 'canForce' is FALSE and 'canDetach' is TRUE and it's an FS path, the path may be - // closed (returns 'detachFS' FALSE) or detached (returns 'detachFS' TRUE). In other cases the - // path can only be closed (returns 'detachFS' FALSE). For FS in the panel only, 'tryCloseReason' - // is the reason passed to CPluginFSInterfaceAbstract::TryCloseOrDetach() - // 'parent' is the parent message box + // prepares for CloseCurrentPath; prepares closing/detaching the current path (updates + // edited files and calls CanCloseArchive for archives; calls TryCloseOrDetach for FS); + // returns TRUE if the path can be closed/detached by the following CloseCurrentPath call, + // returns FALSE if the path cannot be closed/detached (the current path will neither change nor close); + // if 'canForce' is TRUE, the user gets a chance to force-close even a path that the plugin + // does not want to close (necessary when closing Salamander; if there is a bug in the plugin, + // Salamander could not be closed otherwise); if 'canForce' is FALSE and 'canDetach' is TRUE + // and this is an FS path, the path may be closed (returns 'detachFS' FALSE) or detached + // (returns 'detachFS' TRUE); in other cases, the path can only be closed (returns 'detachFS' + // FALSE); for FS in the panel only, 'tryCloseReason' is the reason for calling + // CPluginFSInterfaceAbstract::TryCloseOrDetach() + // 'parent' is the parent of the message box BOOL PrepareCloseCurrentPath(HWND parent, BOOL canForce, BOOL canDetach, BOOL& detachFS, int tryCloseReason); - // helper method: - // finishes closing/detaching the current path started by PrepareCloseCurrentPath; if 'cancel' - // is TRUE the current path is restored (it is neither closed nor changed; triggers - // Event(FSE_CLOSEORDETACHCANCELED) for FS). If 'cancel' is FALSE all no-longer-needed - // resources of the current path are released (depending on path type: Files, Dirs, PluginData, - // ArchiveDir, PluginFS and PluginFSDir). 'detachFS' is the value returned from + // Helper method: + // completes closing/detaching the current path started by PrepareCloseCurrentPath; if 'cancel' + // is TRUE, the current path is restored (it is neither closed nor changed; this ensures + // Event(FSE_CLOSEORDETACHCANCELED) is called for FS). If 'cancel' is FALSE, all resources of the + // current path that are no longer needed are released (depending on the path type: Files, Dirs, + // PluginData, ArchiveDir, PluginFS, and PluginFSDir). 'detachFS' is the value returned by // PrepareCloseCurrentPath (meaningful only for FS; if TRUE, PluginFS is added to DetachedFSList - // instead of being freed). When closing an FS with pitFromPlugin icons you must first call - // SleepIconCacheThread() so PluginData isn't released while its method loads icons. - // 'parent' is the message box parent; 'newPathIsTheSame' is TRUE (meaningful only if 'cancel' - // is FALSE) if the same path ends up in the panel again after closing the path (for example a successful path refresh); - // 'isRefresh' is TRUE for a hard refresh (Ctrl+R or change notification); - // if 'canChangeSourceUID' is TRUE you may change EnumFileNamesSourceUID and with that cancel enumeration - // of files from the panel (e.g. for the viewer). FALSE is used when changing to the same path - // that was already in the panel (similar to refresh via hot-path, focus-name, etc.) + // instead of being released). When closing an FS with pitFromPlugin icons, SleepIconCacheThread() + // must be called first so that PluginData is not released while its method is loading icons. + // 'parent' is the parent of the message box; 'newPathIsTheSame' is TRUE (meaningful only if + // 'cancel' is FALSE) if the same path appears in the panel again after the path is closed + // (for example, after a successful path refresh); 'isRefresh' is TRUE for a hard refresh + // (Ctrl+R or a change notification); if 'canChangeSourceUID' is TRUE, EnumFileNamesSourceUID may + // be changed, which cancels file enumeration from the panel (e.g. for the viewer). FALSE is used + // when changing to the same path that was already in the panel (similar to a refresh, but via + // hot-path, focus-name, etc.) void CloseCurrentPath(HWND parent, BOOL cancel, BOOL detachFS, BOOL newPathIsTheSame, BOOL isRefresh, BOOL canChangeSourceUID); @@ -1044,21 +1052,21 @@ class CFilesWindow : public CFilesWindowAncestor int currentPathFSNameIndex, BOOL forceUpdate, char* cutFileName, BOOL* keepOldListing); - // path change-handles both relative and absolute paths to Windows form (UNC and C:\path); - // shortens the path if needed. When changing within the same drive (including archives) + // changes the path, handling both relative and absolute paths in Windows form (UNC and C:\path), + // and shortens the path if needed. When changing within the same drive (including archives), // it finds a valid directory even if that means switching to a fixed drive (when the current drive is inaccessible); // 'parent' is the parent of the message box; // if suggestedTopIndex != -1 the top index will be set; // if suggestedFocusName != NULL and present in the new list it will be focused; - // if noChange (if not NULL) it returns TRUE when the listing data in the panel were not recreated + // in noChange (if not NULL) it returns TRUE if the listing data in the panel were not recreated // (Files + Dirs); // if refreshListBox is FALSE RefreshListBox is not called; - // if canForce is TRUE, the user can forcibly close even a path the plug-in refuses to close; - // if isRefresh is TRUE, this call comes from RefreshDirectory (no error leading to shortening is shown, + // if canForce is TRUE, the user gets a chance to forcibly close even a path the plugin refuses to close; + // if isRefresh is TRUE, this call comes from RefreshDirectory (no error leading to path shortening is shown, // quick search is not canceled); // if failReason != NULL, it is set to one of the CHPPFR_XXX constants; - // if shorterPathWarning is TRUE, a message box with an error is opened when the path is shortened - // (only when it is not a refresh); + // if shorterPathWarning is TRUE, a message box with an error is opened when the path is shortened, + // but only if this is not a refresh; // only for FS in the panel: 'tryCloseReason' is the reason passed to CPluginFSInterfaceAbstract::TryCloseOrDetach() // returns TRUE if the requested path was listed successfully BOOL ChangePathToDisk(HWND parent, const char* path, int suggestedTopIndex = -1, @@ -1066,52 +1074,55 @@ class CFilesWindow : public CFilesWindowAncestor BOOL refreshListBox = TRUE, BOOL canForce = FALSE, BOOL isRefresh = FALSE, int* failReason = NULL, BOOL shorterPathWarning = TRUE, int tryCloseReason = FSTRYCLOSE_CHANGEPATH); - // changes to an archive path; only absolute Windows paths are allowed (archive is UNC or C:\path\archive) + // changes the path to an archive; only absolute Windows paths are allowed (archive is UNC or C:\path\archive); // if suggestedTopIndex != -1, the top index will be set; - // if suggestedFocusName != NULL, and present in the new list, it will be focused; + // if suggestedFocusName != NULL and is present in the new list, it will be selected; // if forceUpdate is TRUE, the case where the new path equals the current one is not optimized; // if noChange is not NULL, it returns TRUE if the listing data in the panel were not recreated // (ArchiveDir + PluginData); // if refreshListBox is FALSE, RefreshListBox is not called; - // if failReason != NULL it is set to one of the CHPPFR_XXX constants; + // if failReason != NULL, it is set to one of the CHPPFR_XXX constants; // if isRefresh is TRUE, this call comes from RefreshDirectory (quick search is not canceled); // if archivePath contains a file name and canFocusFileName is TRUE, that file is focused // (returns FALSE because the path was shortened); - // if isHistory is TRUE (used when selecting a path from a path history) and the archive cannot + // if isHistory is TRUE (used when selecting a path from the panel path history) and the archive cannot // be opened (or does not exist), the panel opens at least the path to the archive - // (optionally shortened, on path error it does not switch to a fixed drive); - // returns TRUE if the requested path was uccessfully listed + // (optionally shortened; on path error it does not switch to a fixed drive); + // returns TRUE if the requested path was successfully listed BOOL ChangePathToArchive(const char* archive, const char* archivePath, int suggestedTopIndex = -1, const char* suggestedFocusName = NULL, BOOL forceUpdate = FALSE, BOOL* noChange = NULL, BOOL refreshListBox = TRUE, int* failReason = NULL, BOOL isRefresh = FALSE, BOOL canFocusFileName = FALSE, BOOL isHistory = FALSE); - // change path to the plug-in FS; - // if suggestedTopIndex != -1 the top index will be set; - // if suggestedFocusName != NULL and present in the new list, it will be focused; - // if forceUpdate is TRUE, the case where the new path equals the current one is not optimized; - // 'mode' is the path change mode: - // 1 (refresh path) - shortens the path, if needed; do not report path not found (just shorten them), - // report a file instead of path, inaccessibility of path and other errors - // 2 (called via ChangePanelPathToPluginFS from plugin, back/forward in history, etc.) - shortens the path, if needed; - // report all path errors (file instead of path, not found, not accessible, ...) + // Changes the path to the plugin FS. + // If suggestedTopIndex != -1, the top index is set. + // If suggestedFocusName != NULL and it is present in the new list, it is selected. + // If forceUpdate is TRUE, the case where the current path matches the new path is not optimized away. + // 'mode' is the path-change mode: + // 1 (refresh path) - shortens the path if needed; do not report a non-existing path + // (shorten it silently), report file-instead-of-path, path inaccessibility, + // and other errors + // 2 (called from a plugin via ChangePanelPathToPluginFS, back/forward in history, etc.) - shortens the path + // if needed; report all path errors (file instead of path, + // non-existence, inaccessibility, and others) // 3 (change-dir command) - shortens the path only if it is a file or the path cannot be listed - // (ListCurrentPath returns FALSE); do not report file instead of path - // (silent shorten and return the file name), report all other path errors (not found, not accessible, ...) - // if noChange is not NULL, it returns TRUE when the listing data in the panel were not recreated - // (PluginFSDir + PluginData); - // if refreshListBox is FALSE, RefreshListBox is not called; - // if failReason != NULL, it is set to one of the CHPPFR_XXX constants; - // if isRefresh is TRUE, this call comes from RefreshDirectory (quick search is not canceled); - // if fsUserPart contains a file name and canFocusFileName is TRUE, the file is focused - // (returns FALSE because the path was shortened); - // if 'convertPathToInternal' is TRUE, CPluginInterfaceForFSAbstract::ConvertPathToInternal() is called; - // returns TRUE if the requested path was listed successfully + // (ListCurrentPath returns FALSE for it); do not report file instead of path + // (shorten it silently and return the file name), report all other + // path errors (non-existence, inaccessibility, and others) + // In noChange (if not NULL), returns TRUE if the listing data in the panel were not recreated + // (PluginFSDir + PluginData). + // If refreshListBox is FALSE, RefreshListBox is not called. + // If failReason != NULL, it is set to one of the CHPPFR_XXX constants. + // If isRefresh is TRUE, this is a call from RefreshDirectory (quick search is not canceled). + // If fsUserPart contains a file name and canFocusFileName is TRUE, that file is focused + // (returns FALSE because the path was shortened). + // If 'convertPathToInternal' is TRUE, CPluginInterfaceForFSAbstract::ConvertPathToInternal() is called. + // Returns TRUE if the requested path was listed successfully. BOOL ChangePathToPluginFS(const char* fsName, const char* fsUserPart, int suggestedTopIndex = -1, const char* suggestedFocusName = NULL, BOOL forceUpdate = FALSE, int mode = 2, BOOL* noChange = NULL, BOOL refreshListBox = TRUE, int* failReason = NULL, BOOL isRefresh = FALSE, BOOL canFocusFileName = FALSE, BOOL convertPathToInternal = FALSE); - // change path to a detached plug-in FS (in MainWindow->DetachedFSList at index 'fsIndex'); + // change path to a detached plugin FS (in MainWindow->DetachedFSList at index 'fsIndex'); // if suggestedTopIndex != -1, the top index will be set; // if suggestedFocusName != NULL and present in the new list, it will be selected; // if refreshListBox is FALSE, RefreshListBox is not called; @@ -1128,19 +1139,20 @@ class CFilesWindow : public CFilesWindowAncestor int* failReason = NULL, const char* newFSName = NULL, const char* newUserPart = NULL, int mode = -1, BOOL canFocusFileName = FALSE); - // changes the panel path; the input may be an absolute or relative Windows path or an archive path - // or an FS path (absolute/relative is handled directly by the plug-in). If the input path points to a file, + // changes the path in the panel; the input may be an absolute or relative Windows path or an archive path + // or an FS path (absolute/relative is handled directly by the plugin); if the input is a path to a file, // that file is focused; // if suggestedTopIndex != -1, the top index will be set; - // if suggestedFocusName != NULL and present in the new list, it will be selected; - // 'mode' specifies the change mode for FS paths-see ChangePathToPluginFS(); it has no meaning + // if suggestedFocusName != NULL and it is present in the new list, it will be selected; + // 'mode' specifies the path-change mode for FS paths, see ChangePathToPluginFS(); it has no meaning // for archives or disks; // if failReason != NULL, it is set to one of the CHPPFR_XXX constants; - // if 'convertFSPathToInternal' is TRUE or 'newDir' is NULL and it is an FS path, + // if 'convertFSPathToInternal' is TRUE or 'newDir' is NULL and this is an FS path, // CPluginInterfaceForFSAbstract::ConvertPathToInternal() is called; - // 'showNewDirPathInErrBoxes' exists only for paths taken from links (disk paths only) - // the entire path from the link should be shown, not just the part where the error was detected (otherwise the user won’t get the full path from the link); - // returns TRUE if the requested path was successfully listed + // 'showNewDirPathInErrBoxes' was added only for paths extracted from links (disk paths only); + // the full path from the link should be shown, not only the part where the error was detected (otherwise the user + // will not get the full path from the link); + // returns TRUE if the requested path was listed successfully BOOL ChangeDir(const char* newDir = NULL, int suggestedTopIndex = -1, const char* suggestedFocusName = NULL, int mode = 3 /*change-dir*/, int* failReason = NULL, BOOL convertFSPathToInternal = TRUE, @@ -1185,7 +1197,7 @@ class CFilesWindow : public CFilesWindowAncestor // // removes the current path in the panel from the path history of this panel void RemoveCurrentPathFromHistory(); - // returns TRUE, if the plug-in is no longer used by the panel + // returns TRUE, if the plugin is no longer used by the panel BOOL CanUnloadPlugin(HWND parent, CPluginInterfaceAbstract* plugin); void ItemFocused(int index); // called when focus changes @@ -1265,9 +1277,8 @@ class CFilesWindow : public CFilesWindowAncestor BOOL FillViewWithData(TDirectArray* items); // displays the focused file using the viewer identified by 'index' void OnViewFileWith(int index); - // view-file-with: opens a menu to choose a viewer; name == NULL -> item under the cursor in the panel; - // if handlerID != NULL, only the selected handler ID is returned (the viewer is not opened); - // on error returns 0xFFFFFFFF + // view-file-with: opens a menu for selecting a viewer; name == NULL -> item under the cursor in the panel; + // handlerID != NULL -> returns only the selected handler ID (does not open the viewer); on failure returns 0xFFFFFFFF void ViewFileWith(char* name, HWND hMenuParent, const POINT* menuPos, DWORD* handlerID, int enumFileNamesSourceUID, int enumFileNamesLastFileIndex); @@ -1275,9 +1286,8 @@ class CFilesWindow : public CFilesWindowAncestor void FillEditWithMenu(CMenuPopup* popup); // edits the focused file using the editor identified by the variable 'index' void OnEditFileWith(int index); - // edit-file-with: opens a menu to choose an editor; name == NULL -> item under the cursor in the panel; - // if handlerID != NULL, only the selected handler ID is returned (the editor is not opened), - // on error returns 0xFFFFFFFF + // edit-file-with: opens a menu for selecting an editor; name == NULL -> item under the cursor in the panel; + // handlerID != NULL -> returns only the selected handler ID (does not open the viewer); on failure returns 0xFFFFFFFF void EditFileWith(char* name, HWND hMenuParent, const POINT* menuPos, DWORD* handlerID = NULL); void FindFile(); void DriveInfo(); @@ -1323,11 +1333,11 @@ class CFilesWindow : public CFilesWindowAncestor virtual LRESULT WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam); // loads Files and Dirs according to panel type from disk, ArchiveDir or PluginFSDir; - // for ptDisk it returns TRUE if the directory was successfully read from disk (FALSE on read - // error or out of memory). For ptZIPArchive and ptPluginFS it returns FALSE only when memory - // runs out or if the path does not exist (checked before calling ReadDirectory, should not happen); - // 'parent' is the parent of message boxes; - // if TRUE is returned, SortDirectory() is also called + // for ptDisk it returns TRUE if the directory was successfully read from disk (FALSE on failure + // to read or out of memory); for ptZIPArchive and ptPluginFS it returns FALSE only if memory + // runs out or if the path does not exist (that is checked before calling ReadDirectory, so it + // should not happen); 'parent' is the parent of message boxes + // if it returns TRUE, it also calls SortDirectory() BOOL ReadDirectory(HWND parent, BOOL isRefresh); // sorts Files and Dirs using the current ordering method; because it reorders them, @@ -1348,14 +1358,14 @@ class CFilesWindow : public CFilesWindowAncestor void RefreshDirectory(BOOL probablyUselessRefresh = FALSE, BOOL forceReloadThumbnails = FALSE, BOOL isInactiveRefresh = FALSE); - // read-dir (archives, FS, disk), sort - // parent is the parent message box - // if suggestedTopIndex != -1, the top index will be set - // if suggestedFocusName != NULL and present in the new list, it will be selected + // reads the directory (archives, FS, disk), sorts + // parent is the parent of the message box + // if suggestedTopIndex != -1, the top index is set + // if suggestedFocusName != NULL and it is present in the new list, it is selected // if refreshListBox is FALSE, RefreshListBox is not called // if readDirectory is FALSE, ReadDirectory is not called - // if isRefresh is TRUE, the path in the panel is refreshed by this - // returns TRUE if ReadDirectory succeeded + // if isRefresh is TRUE, this refreshes the path in the panel + // returns TRUE if ReadDirectory succeeds BOOL CommonRefresh(HWND parent, int suggestedTopIndex = -1, const char* suggestedFocusName = NULL, BOOL refreshListBox = TRUE, BOOL readDirectory = TRUE, BOOL isRefresh = FALSE); @@ -1434,8 +1444,8 @@ class CFilesWindow : public CFilesWindowAncestor BOOL IsTextOnClipboard(); void ClipboardPastePath(); // for changing the current directory - // postprocesses of the user provided path: trims surrounding white spaces and quotes, removes file:// and - // expands environment variables; returns FALSE on error (processing should stop); 'parent' is + // postprocesses the user-provided path: trims surrounding white spaces and quotes, removes file:// and + // expands ENV variables; returns FALSE on failure (processing should stop); 'parent' is // the parent for error message boxes BOOL PostProcessPathFromUser(HWND parent, char (&buff)[2 * MAX_PATH]); @@ -1446,7 +1456,7 @@ class CFilesWindow : public CFilesWindowAncestor void EndQuickSearch(); // ends Quick Search mode // QuickRenameWindow - void AdjustQuickRenameRect(const char* text, RECT* r); // adjusts 'r' so it doesn't exceed the panel and is large enough at the same time + void AdjustQuickRenameRect(const char* text, RECT* r); // adjusts 'r' so it does not exceed the panel and is large enough void AdjustQuickRenameWindow(); // void QuickRenameOnIndex(int index); // calls QuickRenameBegin for the given index void QuickRenameBegin(int index, const RECT* labelRect); // opens QuickRenameWindow @@ -1487,7 +1497,7 @@ class CFilesWindow : public CFilesWindowAncestor int GetCaretIndex(); void SetDropTarget(int index); // marks where files will be dropped - void SetSingleClickIndex(int index); // highlights the item and clears the old one + void SetSingleClickIndex(int index); // highlights the item and unhighlights the old one void SelectFocusedIndex(); void DrawDragBox(POINT p); @@ -1498,13 +1508,13 @@ class CFilesWindow : public CFilesWindowAncestor // RepaintListBox(DRAWFLAG_DIRTY_ONLY | DRAWFLAG_SKIP_VISTEST); // only the first method SetSel can repaint items on explicit request // the first two methods (SetSel and SetSelRange) do not mark the ".." directory item - void SetSel(BOOL select, int index, BOOL repaintDirtyItems = FALSE); // If index is -1 the selection is added to or removed from all strings + void SetSel(BOOL select, int index, BOOL repaintDirtyItems = FALSE); // If index is -1, the selection is added to or removed from all items // returns TRUE if the state of at least one item has changed, otherwise returns FALSE BOOL SetSelRange(BOOL select, int firstIndex, int lastIndex); void SetSel(BOOL select, CFileData* data); // data must be held by the corresponding list BOOL GetSel(int index); - int GetSelItems(int itemsCountMax, int* items, BOOL focusedItemFirst = FALSE); // if 'focusedItemFirst' is TRUE (not used anymore; see GetSelItems body): for context menus, we start we start from the focused item and end with the item before the focus (there is intermediate wrapping back to the beginning of the name list) (the system does it in the same way, see Add To Windows Media Player List on MP3 files) + int GetSelItems(int itemsCountMax, int* items, BOOL focusedItemFirst = FALSE); // if 'focusedItemFirst' is TRUE (no longer used; see the GetSelItems implementation): for context menus, start at the focused item and end with the item before it (wrapping back to the start of the name list in between). The system does the same; see Add To Windows Media Player List on MP3 files // if GetSelCount > 0 returns TRUE, if at least one directory is selected (".." not counted); otherwise it returns FALSE // if GetSelCount == 0 returns TRUE, if a directory is focused (".." not counted); otherwise it returns FALSE @@ -1535,7 +1545,7 @@ class CFilesWindow : public CFilesWindowAncestor void GotoSelectedItem(BOOL next); // if 'next' is TRUE, it moves caret to the next selected item, otherwise to the previous one - void OnSetFocus(BOOL focusVisible = TRUE); // 'focusVisible'==FALSE when switching from the command line to the panel while the user is in a modeless dialog (main window is inactive) - required by the FTP plugin Welcome Message dialog + void OnSetFocus(BOOL focusVisible = TRUE); // 'focusVisible'==FALSE when switching from the command line to the panel while the user is in a modeless dialog (the main window is not active) - needed for the FTP plugin Welcome Message dialog void OnKillFocus(HWND hwndGetFocus); BOOL OnLButtonDown(WPARAM wParam, LPARAM lParam, LRESULT* lResult); @@ -1545,7 +1555,7 @@ class CFilesWindow : public CFilesWindowAncestor BOOL OnRButtonUp(WPARAM wParam, LPARAM lParam, LRESULT* lResult); BOOL OnMouseMove(WPARAM wParam, LPARAM lParam, LRESULT* lResult); - BOOL IsDragDropSafe(int x, int y); // safer drag&drop: returns TRUE if the drag was long enough; x,y are coordinates relative to the panel origin + BOOL IsDragDropSafe(int x, int y); // safer drag-and-drop: returns TRUE if dragging lasted long enough; x and y are coordinates relative to the panel origin BOOL OnTimer(WPARAM wParam, LPARAM lParam, LRESULT* lResult); BOOL OnCaptureChanged(WPARAM wParam, LPARAM lParam, LRESULT* lResult); @@ -1553,7 +1563,7 @@ class CFilesWindow : public CFilesWindowAncestor void LayoutListBoxChilds(); // after a font change layout must be updated void RepaintListBox(DWORD drawFlags); - void RepaintIconOnly(int index); // for index == -1 redraws icons of all items + void RepaintIconOnly(int index); // for index == -1, redraws the icons of all items void EnsureItemVisible(int index); // ensures the item is visible void SetQuickSearchCaretPos(); // sets caret position within FocusedIndex diff --git a/src/filter.cpp b/src/filter.cpp index 7d0198749..ec07ab43a 100644 --- a/src/filter.cpp +++ b/src/filter.cpp @@ -7,7 +7,7 @@ // Attributes const char* FILTERCRITERIA_ATTRIBUTESMASK_REG = "Attributes Mask"; const char* FILTERCRITERIA_ATTRIBUTESVALUE_REG = "Attributes Value"; -// Size Min/Max +// Minimum/maximum size const char* FILTERCRITERIA_USEMINSIZE_REG = "UseMinSize"; const char* FILTERCRITERIA_MINSIZELO_REG = "MinSizeLo"; const char* FILTERCRITERIA_MINSIZEHI_REG = "MinSizeHi"; @@ -30,8 +30,8 @@ const char* FILTERCRITERIA_USETOTIME_REG = "UseToTime"; const char* FILTERCRITERIA_TOLO_REG = "ToLo"; const char* FILTERCRITERIA_TOHI_REG = "ToHi"; -// we used the following variables in Altap Salamander 2.5, -// where we switched to CFilterCriteria and its Save/Load +// the following variables were used up to Altap Salamander 2.5, +// when we switched to CFilterCriteria and its Save/Load const char* OLD_FINDOPTIONSITEM_ARCHIVE_REG = "Archive"; const char* OLD_FINDOPTIONSITEM_READONLY_REG = "ReadOnly"; const char* OLD_FINDOPTIONSITEM_HIDDEN_REG = "Hidden"; @@ -86,7 +86,7 @@ void CFilterCriteria::Reset() AttributesMask = 0; // 0 -> indeterminate checkbox state AttributesValue = 0; - // Size Min/Max + // Minimum/Maximum Size UseMinSize = FALSE; MinSize.Set(1, 0); MinSizeUnits = fcsuKB; @@ -230,7 +230,7 @@ void CFilterCriteria::PrepareForTest() { SYSTEMTIME st; // 'st' can be modified, see the reset of hours, minutes, and seconds GetLocalTime(&st); - // weekday is redundant information; we will not work with it + // the weekday is redundant information; we will not use it st.wDayOfWeek = 0; SYSTEMTIME stCurrent = st; // current time that we won't modify @@ -364,8 +364,8 @@ void CFilterCriteria::PrepareForTest() } if (SystemTimeToFileTime(&st, (FILETIME*)&MaxTime)) { - // we want to be the absolute maximum time, sticking right at the very end of the interval - // at the resolution of FILETIME + // we want the absolute maximum time, so we move all the way to the end of the interval + // at FILETIME resolution MaxTime += 9999999; // almost one second UseMaxTime = TRUE; @@ -385,7 +385,7 @@ BOOL CFilterCriteria::Test(DWORD attributes, const CQuadWord* size, const FILETI // Attributes BOOL ok = ((attributes & AttributesMask) == (AttributesValue & AttributesMask)); - // Size Min/Max + // Min/max size if (ok && (UseMinSize || UseMaxSize)) { if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0) @@ -395,7 +395,7 @@ BOOL CFilterCriteria::Test(DWORD attributes, const CQuadWord* size, const FILETI } else { - // it's a file, so we can compare its size + // this is a file, so we can compare its size if (UseMinSize) ok = *size >= MinSizeBytes; if (ok && UseMaxSize) @@ -489,8 +489,8 @@ BOOL CFilterCriteria::GetAdvancedDescription(char* buffer, int maxLen, BOOL& dir BOOL CFilterCriteria::Save(HKEY hKey) { - // space optimization in the Registry: we store only "non-default values" - // before saving, it is necessary to clear the key where we will store the data + // registry space optimization: we store only non-default values; + // therefore, before saving, the target key must be cleared CFilterCriteria def; // Attributes @@ -499,7 +499,7 @@ BOOL CFilterCriteria::Save(HKEY hKey) if (AttributesValue != def.AttributesValue) SetValue(hKey, FILTERCRITERIA_ATTRIBUTESVALUE_REG, REG_DWORD, &AttributesValue, sizeof(DWORD)); - // Size Min/Max + // Minimum/maximum size if (UseMinSize != def.UseMinSize) SetValue(hKey, FILTERCRITERIA_USEMINSIZE_REG, REG_DWORD, &UseMinSize, sizeof(DWORD)); if (MinSize != def.MinSize) @@ -537,7 +537,7 @@ BOOL CFilterCriteria::Save(HKEY hKey) // note: starting with 2.53 we'll "forget" the times in disabled FROM/TO controls (see TimeMode == fctmFromTo condition) // if users request a return to the old behavior, we could by default disable the checkboxes in the Date controls, // which would not meet the UseFromDate/UseToDate condition; we would enable the checkbox only when the user enables the control via radio buttons - if (From != def.From && TimeMode == fctmFromTo && (UseFromDate || UseFromTime)) // there's no point in storing times when they are not used (controls would insert the current time) + if (From != def.From && TimeMode == fctmFromTo && (UseFromDate || UseFromTime)) // No need to store times when they are not used (the controls then fill in the current time) { SetValue(hKey, FILTERCRITERIA_FROMLO_REG, REG_DWORD, &(((FILETIME*)&From)->dwLowDateTime), sizeof(DWORD)); SetValue(hKey, FILTERCRITERIA_FROMHI_REG, REG_DWORD, &(((FILETIME*)&From)->dwHighDateTime), sizeof(DWORD)); @@ -546,7 +546,7 @@ BOOL CFilterCriteria::Save(HKEY hKey) SetValue(hKey, FILTERCRITERIA_USETODATE_REG, REG_DWORD, &UseToDate, sizeof(DWORD)); if (UseToTime != def.UseToTime) SetValue(hKey, FILTERCRITERIA_USETOTIME_REG, REG_DWORD, &UseToTime, sizeof(DWORD)); - if (To != def.To && TimeMode == fctmFromTo && (UseToDate || UseToTime)) // there's no point in storing times when they are not used (controls would insert the current time) + if (To != def.To && TimeMode == fctmFromTo && (UseToDate || UseToTime)) // There is no point in storing times when they are not used (the controls then insert the current time) { SetValue(hKey, FILTERCRITERIA_TOLO_REG, REG_DWORD, &(((FILETIME*)&To)->dwLowDateTime), sizeof(DWORD)); SetValue(hKey, FILTERCRITERIA_TOHI_REG, REG_DWORD, &(((FILETIME*)&To)->dwHighDateTime), sizeof(DWORD)); @@ -560,7 +560,7 @@ BOOL CFilterCriteria::Load(HKEY hKey) GetValue(hKey, FILTERCRITERIA_ATTRIBUTESMASK_REG, REG_DWORD, &AttributesMask, sizeof(DWORD)); GetValue(hKey, FILTERCRITERIA_ATTRIBUTESVALUE_REG, REG_DWORD, &AttributesValue, sizeof(DWORD)); - // Size Min/Max + // Minimum/maximum size GetValue(hKey, FILTERCRITERIA_USEMINSIZE_REG, REG_DWORD, &UseMinSize, sizeof(DWORD)); GetValue(hKey, FILTERCRITERIA_MINSIZELO_REG, REG_DWORD, &MinSize.LoDWord, sizeof(DWORD)); GetValue(hKey, FILTERCRITERIA_MINSIZEHI_REG, REG_DWORD, &MinSize.HiDWord, sizeof(DWORD)); @@ -1029,7 +1029,7 @@ void CFilterCriteriaDialog::Transfer(CTransferInfo& ti) } st.wMilliseconds = 0; if (!SystemTimeToFileTime(&st, (FILETIME*)&Data->From)) - Data->From = (unsigned __int64)0; // error for validation + Data->From = (unsigned __int64)0; // error for Validate Data->UseToDate = DateTime_GetSystemtime(GetDlgItem(HWindow, IDC_FFA_TO_DATE), &st) == GDT_VALID; Data->UseToTime = DateTime_GetSystemtime(GetDlgItem(HWindow, IDC_FFA_TO_TIME), &st2) == GDT_VALID; @@ -1047,7 +1047,7 @@ void CFilterCriteriaDialog::Transfer(CTransferInfo& ti) } st.wMilliseconds = 0; if (!SystemTimeToFileTime(&st, (FILETIME*)&Data->To)) - Data->To = (unsigned __int64)0; // error for validation + Data->To = (unsigned __int64)0; // Error for Validate() } if (ti.Type == ttDataToWindow) @@ -1197,14 +1197,14 @@ void CFilterCriteriaDialog::EnableControls() BOOL minOrMax = FALSE; - // Size Min + // Minimum Size checked = IsDlgButtonChecked(HWindow, IDC_FFA_SIZEMIN) == BST_CHECKED; minOrMax |= checked; EnableWindow(GetDlgItem(HWindow, IDC_FFA_SIZEMIN_VALUE), checked); EnableWindow(GetDlgItem(HWindow, IDC_FFA_SIZEMIN_UPDOWN), checked); EnableWindow(GetDlgItem(HWindow, IDC_FFA_SIZEMIN_UNITS), checked); - // Size Max + // Maximum Size checked = IsDlgButtonChecked(HWindow, IDC_FFA_SIZEMAX) == BST_CHECKED; minOrMax |= checked; EnableWindow(GetDlgItem(HWindow, IDC_FFA_SIZEMAX_VALUE), checked); @@ -1276,9 +1276,9 @@ CFilterCriteriaDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) UDS_ALIGNRIGHT | UDS_ARROWKEYS | UDS_NOTHOUSANDS, 0, 0, 0, 0, HWindow, upDownID[i], HInstance, hEdit, 10000, i == 2 ? 1 : 0, 0); - // move the UpDown control in the z-order right after the edit line, otherwise - // on a slow machine the dialog display looked odd - // (the UpDown was drawn after all the other controls) + // move the UpDown control immediately behind the edit box in the Z-order; otherwise, + // the dialog could display oddly on a slow machine + // (the UpDown was drawn only after all other controls) SetWindowPos(hWnd, hEdit, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); } if (!EnableDirectory) @@ -1310,12 +1310,12 @@ CFilterCriteriaDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (LOWORD(wParam) == IDC_FFA_SIZEMIN_VALUE) { - // size min + // minimum size FillUnits(IDC_FFA_SIZEMIN_VALUE, IDC_FFA_SIZEMIN_UNITS, sizeUnits, TRUE); } if (LOWORD(wParam) == IDC_FFA_SIZEMAX_VALUE) { - // size max + // maximum size FillUnits(IDC_FFA_SIZEMAX_VALUE, IDC_FFA_SIZEMAX_UNITS, sizeUnits, TRUE); } if (LOWORD(wParam) == IDC_FFA_TIMEDURING_VALUE) diff --git a/src/find.cpp b/src/find.cpp index 91b290db6..d450128d0 100644 --- a/src/find.cpp +++ b/src/find.cpp @@ -380,7 +380,7 @@ BOOL CFindIgnore::Save(HKEY hKey) if (CreateKey(hKey, buf, subKey)) { SetValue(subKey, FINDIGNOREITEM_PATH_REG, REG_SZ, Items[i]->Path, -1); - if (!Items[i]->Enabled) // save only if it is FALSE + if (!Items[i]->Enabled) // save only when FALSE SetValue(subKey, FINDIGNOREITEM_ENABLED_REG, REG_DWORD, &Items[i]->Enabled, sizeof(DWORD)); CloseKey(subKey); } @@ -413,9 +413,9 @@ BOOL CFindIgnore::Load(HKEY hKey, DWORD cfgVersion) item->Enabled = TRUE; // saved only if it is FALSE if (Configuration.ConfigVersion < 32) { - // users were confused that this folder was not searched - // so we keep it listed but uncheck the checkbox - // anyone interested can manually enable it + // users were confused that this folder was not being searched + // so we keep it in the list, but clear the checkbox + // anyone who wants to can enable it if (strcmp(item->Path, "Local Settings\\Temporary Internet Files") == 0) item->Enabled = FALSE; } @@ -550,7 +550,7 @@ BOOL CFindIgnore::Contains(const char* path, int startPathLen) m = StrIStr(m, item->Path); if (m != NULL) // found { - if ((m - path) + item->Len > startPathLen) // is it a subpath? then ignore it + if ((m - path) + item->Len > startPathLen) // subpath: ignore it return TRUE; m++; // look for another occurrence, maybe it will be in a subpath } @@ -694,8 +694,8 @@ class CDuplicateCandidates : public TIndirectArray // before calling this method, the array must be sorted with QuickSort void RemoveSingleFiles(BOOL byName, BOOL bySize, BOOL byMD5); - // goes through all stored items and uses CompareFunc assign them - // to groups; Alternates the Different bit for the groups (0, 1, 0, 1, 0, 1, ...) + // Goes through all stored items and uses CompareFunc to assign them + // to groups; alternates the Different bit for the groups (0, 1, 0, 1, 0, 1, ...) // before calling this method, the array must be sorted with QuickSort void SetDifferentFlag(BOOL byName, BOOL bySize, BOOL byMD5); @@ -780,7 +780,7 @@ void CDuplicateCandidates::QuickSort(int left, int right, BOOL byName, BOOL bySi } } while (i <= j); - // the following "nice" code was replaced by a version that saves stack space (max. log(N) recursion depth) + // the following code was replaced by a version that uses substantially less stack space (max. log(N) recursion depth) // if (left < j) QuickSort(left, j, byName, bySize, byMD5); // if (i < right) QuickSort(i, right, byName, bySize, byMD5); @@ -839,7 +839,7 @@ BOOL CDuplicateCandidates::GetMD5Digest(CGrepData* data, CFoundFilesData* file, DWORD read; // number of bytes that were actually read while (TRUE) { - // read a segment from a file 'file' into 'buffer' + // read a segment from file 'file' into 'buffer' if (!ReadFile(hFile, buffer, DUPLICATES_BUFFER_SIZE, &read, NULL)) { // error reading the file @@ -1019,7 +1019,7 @@ void CDuplicateCandidates::Examine(CGrepData* data) // search completed, preparing results (MD5 computation may still follow) data->SearchingText->Set(LoadStr(IDS_FIND_DUPS_RESULTS)); - // sort them according to selected criteria + // sort them by the selected criteria QuickSort(0, Count - 1, byName, bySize, FALSE); // remove items that occur only once @@ -1087,7 +1087,7 @@ void CDuplicateCandidates::Examine(CGrepData* data) int j; for (j = 0; j <= i; j++) Delete(0); - break; // show at least the duplicates that have been already found + break; // show at least the duplicates found so far } // an error occurred during reading the file but the user wants to continue // exclude the file from candidates @@ -1250,10 +1250,10 @@ BOOL TestFileContentAux(BOOL& ok, CQuadWord& fileOffset, const CQuadWord& totalS fileOffset + CQuadWord(viewSize, 0) < totalSize) // the end of the file is not in the file view { // the line can continue beyond the boundary of the current view of the file fileOffset += CQuadWord(DWORD(beg - txt), 0); - return TRUE; // continue with the next view segment + return TRUE; // continue with the next file view } - // line beg->end + // line: beg->end if (data->RegExp.SetLine(beg, end)) { int foundLen, start = 0; @@ -1385,7 +1385,7 @@ BOOL TestFileContent(DWORD sizeLow, DWORD sizeHigh, const char* path, CGrepData* CQuadWord allocGran(AllocationGranularity, 0); while (!data->StopSearch && fileOffset < totalSize) { - // ensure the offset matches the granularity + // ensure the offset is aligned to the allocation granularity CQuadWord mapFileOffset(fileOffset); mapFileOffset = (mapFileOffset / allocGran) * allocGran; @@ -1401,7 +1401,7 @@ BOOL TestFileContent(DWORD sizeLow, DWORD sizeHigh, const char* path, CGrepData* viewSize)); if (txt != NULL) { - // let the file view be examined + // let the file view be searched DWORD diff = (DWORD)(fileOffset - mapFileOffset).Value; BOOL err2 = !TestFileContentAux(ok, fileOffset, totalSize, viewSize - diff, path, txt + diff, data); @@ -1445,7 +1445,7 @@ BOOL AddFoundItem(const char* path, const char* name, DWORD sizeLow, DWORD sizeH DWORD attr, const FILETIME* lastWrite, BOOL isDir, CGrepData* data, CDuplicateCandidates* duplicateCandidates) { - if (duplicateCandidates != NULL && isDir) // directories are irrelevant to us when searching for duplicates + if (duplicateCandidates != NULL && isDir) // directories are ignored when searching for duplicates return TRUE; CFoundFilesData* foundData = new CFoundFilesData; @@ -1513,16 +1513,16 @@ BOOL AddFoundItem(const char* path, const char* name, DWORD sizeLow, DWORD sizeH return TRUE; } -// 'dirStack' stores directories for late grepping. Otherwise, -// during searching in the current directory, recursive searching in subdirectories would occur. With this -// trick all files and directories matching the criteria are found first and -// then this function is called for all discovered directories. -// 'dirStack' only grows. When items are removed from it, they are just destroyed but -// not removed from the array, therefore the variable 'dirStackCount' holds the +// 'dirStack' stores directories to be grep-searched later. Otherwise, +// searching the current directory would recursively search its subdirectories. +// With this workaround, all files and directories matching the criteria are found first, +// and then this function is called for all discovered directories. +// 'dirStack' only grows. When items are removed from it, they are only destroyed, +// but not removed from the array. Therefore, the variable 'dirStackCount' holds the // actual number of items in the array (always less than or equal to dirStack->Count). // If memory is low or subdirectories are not searched, // 'dirStack' is NULL. -// If 'duplicateCandidates' != NULL, found items will be added to this array +// If 'duplicateCandidates' != NULL, found items are added to this array // instead of data->FoundFilesListView void SearchDirectory(char (&path)[MAX_PATH], char* end, int startPathLen, CMaskGroup* masksGroup, BOOL includeSubDirs, CGrepData* data, @@ -1598,7 +1598,7 @@ void SearchDirectory(char (&path)[MAX_PATH], char* end, int startPathLen, { // file name // let the extension be resolved if ext==NULL - if (masksGroup->AgreeMasks(file.cFileName, NULL)) // mask is OK + if (masksGroup->AgreeMasks(file.cFileName, NULL)) // mask matches { BOOL ok; if (data->Grep) @@ -1639,11 +1639,11 @@ void SearchDirectory(char (&path)[MAX_PATH], char* end, int startPathLen, } } } - if (isDir && includeSubDirs && !ignoreDir) // directory + not "." or ".." + if (isDir && includeSubDirs && !ignoreDir) // directory and not "." or ".." { int l = (int)strlen(file.cFileName); - if ((end - path) + l + 1 /* 1 za backslash */ < _countof(path)) + if ((end - path) + l + 1 /* 1 for the backslash */ < _countof(path)) { BOOL searchNow = TRUE; @@ -1700,7 +1700,7 @@ void SearchDirectory(char (&path)[MAX_PATH], char* end, int startPathLen, } } } - else // too long file-name + else // file name too long { FIND_LOG_ITEM log; log.Flags = FLI_ERROR; @@ -1803,7 +1803,7 @@ void RefineData(CMaskGroup* masksGroup, CGrepData* data) { char buf[20]; sprintf(buf, "%d%%", progress); - data->SearchingText->Set(buf); // set the current path + data->SearchingText->Set(buf); // update the progress text oldProgress = progress; } } @@ -1938,8 +1938,8 @@ unsigned GrepThreadFBody(void* ptr) TRACE_E(LOW_MEMORY); // the algorithm will run even without the stack } - // create a local copy of the ignore list since it has to be processed anyway - // and as a bonus the user can edit the ignore list while searching + // make a local copy of the ignore list, since it has to be processed anyway + // this also allows the user to edit the ignore list while the search is in progress CFindIgnore* ignoreList = new CFindIgnore; if (ignoreList == NULL) TRACE_E(LOW_MEMORY); // the algorithm will run even without the ignore list @@ -2138,10 +2138,10 @@ unsigned ThreadFindDialogMessageLoopBody(void* parameter) if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) - break; // equivalent to the situation when GetMessage() is returning FALSE + break; // equivalent to the situation where GetMessage() returns FALSE haveMSG = TRUE; // a message is pending; process it without calling GetMessage() } - else // if there is no message in the queue, perform Idle processing + else // if the queue is empty, perform idle processing { if (findDialog != NULL) findDialog->OnEnterIdle(); @@ -2153,7 +2153,7 @@ unsigned ThreadFindDialogMessageLoopBody(void* parameter) } #ifndef CALLSTK_DISABLE - CCallStack::ReleaseBeforeExitThread(); // before exiting the thread, we must release call-stack data (still in protected section - generating our bug report) + CCallStack::ReleaseBeforeExitThread(); // before the thread exits, call-stack data must be released (we are still in the protected section used to generate our bug report) #endif // CALLSTK_DISABLE _endthreadex(ok ? 0 : 1); return ok ? 0 : 1; // dead code to keep the compiler happy @@ -2172,7 +2172,7 @@ unsigned ThreadFindDialogMessageLoopEH(void* param) { TRACE_I("Thread FindDialogMessageLoop: calling ExitProcess(1)."); // ExitProcess(1); - TerminateProcess(GetCurrentProcess(), 1); // harder exit (this call still performs some operations) + TerminateProcess(GetCurrentProcess(), 1); // more forceful exit (ExitProcess still calls some code) return 1; } #endif // CALLSTK_DISABLE diff --git a/src/find.h b/src/find.h index ae69e76f1..c24e8fbaf 100644 --- a/src/find.h +++ b/src/find.h @@ -269,9 +269,9 @@ class CFindIgnoreItem }; // The CFindIgnore object serves two purposes: -// 1. A global object holding the list of paths editable in the Find/Options/Ignore Directory List -// 2. A temporary copy used for searching -- contains only Enabled items which are -// adjusted (backslashes added) and classified (CFindIgnoreItem::Type set) +// 1. A global object holding the list of paths editable in Find/Options/Ignore Directory List +// 2. A temporary copy of this array for searching; it contains only enabled items, which are +// additionally adjusted (backslashes added) and qualified (CFindIgnoreItem::Type set) class CFindIgnore { protected: @@ -691,7 +691,7 @@ class CFindDialog : public CCommonDialog int ResultsY; // position of the results list int AdvancedY; // position of the Advanced button int AdvancedTextY; // position of the text after the Advanced button - int AdvancedTextX; // position of the text after the Advanced button + int AdvancedTextX; // X position of the text after the Advanced button int FindTextY; // position of the header above the results int FindTextH; // height of the header int CombosX; // position of the comboboxes @@ -715,7 +715,7 @@ class CFindDialog : public CCommonDialog CMenuBar* MenuBar; HWND HStatusBar; HWND HProgressBar; // status bar child window shown for certain operations in a special field - BOOL TwoParts; // does the status bar have two texts? + BOOL TwoParts; // does the status bar have two text fields? // CFindAdvancedDialog FindAdvanced; CFoundFilesListView* FoundFilesListView; char FoundFilesDataTextBuffer[MAX_PATH]; // for obtaining text from CFoundFilesData::GetText @@ -746,7 +746,7 @@ class CFindDialog : public CCommonDialog CBitmap* CacheBitmap; // used when drawing the path - BOOL FlashIconsOnActivation; // flash the status icons when we get activated + BOOL FlashIconsOnActivation; // flash the status icons on activation char FindNowText[100]; diff --git a/src/finddlg1.cpp b/src/finddlg1.cpp index dd15f41b7..2bf89bffe 100644 --- a/src/finddlg1.cpp +++ b/src/finddlg1.cpp @@ -460,7 +460,7 @@ void CFoundFilesListView::SortItems(int sortBy) BOOL enabledPathTime = TRUE; if (FindDialog->GrepData.FindDuplicates) { - enabledPathTime = FALSE; // path and time are irrelevant for duplicates + enabledPathTime = FALSE; // not meaningful for duplicates // sorting by name and size works for duplicates only // when searching for identical name and size enabledNameSize = (FindDialog->GrepData.FindDupFlags & FIND_DUPLICATES_NAME) && @@ -607,7 +607,7 @@ int CFoundFilesListView::CompareFunc(CFoundFilesData* f1, CFoundFilesData* f2, i int next = sortBy; do { - if (f1->IsDir == f2->IsDir) // are the items from the same group (directories/files)? + if (f1->IsDir == f2->IsDir) // Are the items in the same group (directories/files)? { switch (next) { @@ -948,7 +948,7 @@ CFoundFilesListView::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) HANDLES(EnterCriticalSection(&DataCriticalSection)); BOOL selExists = FALSE; - if (FileNamesEnumData.PreferSelected) // if needed, check whether there is a selection + if (FileNamesEnumData.PreferSelected) // if needed, check whether anything is selected { int i = -1; int selCount = 0; // ignore the state where the only marked item is the focused one (this cannot logically be considered as selected items) @@ -981,7 +981,7 @@ CFoundFilesListView::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) } else { - if (FileNamesEnumData.LastFileName[0] != 0) // the full name at 'index' is known; check for shifts and search for a new index if needed + if (FileNamesEnumData.LastFileName[0] != 0) // the full file name at 'index' is known; check whether the array has shifted and find the new index if needed { BOOL ok = FALSE; CFoundFilesData* f = (index >= 0 && index < count) ? Data[index] : NULL; @@ -997,7 +997,7 @@ CFoundFilesListView::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) } } if (!ok) - { // the name at index 'index' isn't FileNamesEnumData.LastFileName, try to find a new index for that name + { // the name at index 'index' is not FileNamesEnumData.LastFileName; try to find that name's new index int i; for (i = 0; i < count; i++) { @@ -1240,7 +1240,7 @@ BOOL CFoundFilesListView::InitColumns() p++; if (IsAlpha[*p]) { - // contains alphabetic characters -- we must find the longest month and day text + // contains alphabetic characters -- we must find the longest month and day names int maxMonth = 0; int sats[] = {1, 5, 4, 1, 6, 3, 1, 5, 2, 7, 4, 2}; int mo; @@ -1776,9 +1776,9 @@ void CFindDialog::BuildSerchForData() char* begin; char* end; - // Users often want to enter just "i_am_dummy" to find files "*i_am_dummy*". - // Therefore, we must inspect each item from the mask group and, if it lacks - // any wildcard or '.', surround it with asterisks. + // Users often want to enter just "i_am_dummy" to find files like "*i_am_dummy*". + // Therefore, we must inspect each item in the mask group and, if it contains neither + // a wildcard nor '.', surround it with asterisks. char* iterator = named; begin = Data.NamedText; while (1) @@ -1950,7 +1950,7 @@ void CFindDialog::StartSearch(WORD command) case CM_FIND_INTERSECT: { - // if this is a refine operation, copy data into the DataForRefine array + // if this is a refine operation, move the data to the DataForRefine array FoundFilesListView->TakeDataForRefine(); GrepData.Refine = 1; break; @@ -1993,7 +1993,7 @@ void CFindDialog::StartSearch(WORD command) GrepData.EOL_CRLF = Configuration.EOL_CRLF; GrepData.EOL_CR = Configuration.EOL_CR; GrepData.EOL_LF = Configuration.EOL_LF; - // GrepData.EOL_NULL = Configuration.EOL_NULL; // can't handle this with regexp :( + // GrepData.EOL_NULL = Configuration.EOL_NULL; // regexp cannot handle this GrepData.Regular = Data.RegularExpresions; GrepData.WholeWords = Data.WholeWords; if (Data.RegularExpresions) @@ -2087,7 +2087,7 @@ void CFindDialog::StopSearch() while (1) { BOOL oldCanClose = CanClose; - CanClose = FALSE; // don't allow closing while we are inside this method + CanClose = FALSE; // do not allow closing while this method is running if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { // message loop for messages from the grep thread @@ -2097,7 +2097,7 @@ void CFindDialog::StopSearch() CanClose = oldCanClose; if (GrepThread == NULL) - return; // DispatchMessage may call us again and we've already handled closing + return; // DispatchMessage may call us again, and closing has already been handled if (WaitForSingleObject(GrepThread, 100) != WAIT_TIMEOUT) break; } @@ -2106,7 +2106,7 @@ void CFindDialog::StopSearch() GrepThread = NULL; SearchInProgress = FALSE; - if (OKButton != NULL) // trigger the drop-down arrow + if (OKButton != NULL) // enable the drop-down arrow { DWORD flags = OKButton->GetFlags(); flags |= BTF_DROPDOWN; @@ -2487,7 +2487,7 @@ void CFindDialog::OnViewFileWith() MainWindow->GetActivePanel()->ViewFileWith(longName, FoundFilesListView->HWindow, &menuPoint, &handlerID, -1, -1); if (handlerID != 0xFFFFFFFF) { - if (SalamanderBusy) // almost impossible, but Salamander could be busy + if (SalamanderBusy) // unlikely, but Salamander could have become busy { Sleep(200); // give Salamander time-if we switched from the main window // the menu's message queue might still be running @@ -2534,7 +2534,7 @@ void CFindDialog::OnEditFileWith() MainWindow->GetActivePanel()->EditFileWith(longName, FoundFilesListView->HWindow, &menuPoint, &handlerID); if (handlerID != 0xFFFFFFFF) { - if (SalamanderBusy) // almost impossible, but Salamander could be busy + if (SalamanderBusy) // almost impossible, but someone could have kept Salamander busy { Sleep(200); // give Salamander time-if we switched from the main window // the menu's message queue might still be running @@ -2562,9 +2562,9 @@ void CFindDialog::OnUserMenu() MainWindow->FillUserMenu(&menu, FALSE); // keep customization disabled POINT p; GetListViewContextMenuPos(FoundFilesListView->HWindow, &p); - // another locking round (BeginUserMenuIconsInUse+EndUserMenuIconsInUse) will happen - // inside WM_USER_ENTERMENULOOP and WM_USER_LEAVEMENULOOP; it's nested and has no overhead, - // so we ignore it and don't try to fight it + // another locking round (BeginUserMenuIconsInUse+EndUserMenuIconsInUse) will occur + // in WM_USER_ENTERMENULOOP+WM_USER_LEAVEMENULOOP, but it is already nested and adds no overhead, + // so it is ignored and no special handling is needed DWORD cmd = menu.Track(MENU_TRACK_RETURNCMD, p.x, p.y, HWindow, NULL); UserMenuIconBkgndReader.EndUserMenuIconsInUse(); @@ -2746,7 +2746,7 @@ void CFindDialog::InsertDrives(HWND hEdit, BOOL network) int i = 1; while (i != 0) { - if (mask & i) // the drive is accessible + if (mask & i) // the drive is available { root[0] = drive; DWORD driveType = GetDriveType(root); @@ -2867,7 +2867,7 @@ BOOL CFindDialog::ManageHiddenShortcuts(const MSG* msg) } } } - return FALSE; // not our message + return FALSE; // message not handled here } void CFindDialog::SetFullRowSelect(BOOL fullRow) @@ -3086,7 +3086,7 @@ CFindDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) query = FALSE; else { - if (SearchInProgress) // stop searching immediately if the user wants + if (SearchInProgress) // stop searching immediately if the user wants to StopSearch(); } } @@ -3323,7 +3323,7 @@ CFindDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) StopSearch(); return TRUE; } - else // no, it is the start + else // no, this is a start request { if (!ValidateData() || !TransferData(ttDataFromWindow)) return TRUE; @@ -3859,7 +3859,7 @@ MENU_TEMPLATE_ITEM FindLookInBrowseMenu[] = if (SkipCharacter) // suppress the beep on Alt+Enter { SkipCharacter = FALSE; - return TRUE; // MSDN says we should return 0, but that beeps, so I am not sure + return TRUE; // MSDN says we should return 0, but that causes a beep } break; } @@ -3872,7 +3872,7 @@ MENU_TEMPLATE_ITEM FindLookInBrowseMenu[] = { case NM_DBLCLK: { - if (((LPNMITEMACTIVATE)lParam)->iItem >= 0) // double-click outside items does nothing + if (((LPNMITEMACTIVATE)lParam)->iItem >= 0) // double-click outside an item does not open anything OnOpen(TRUE); break; } @@ -3880,14 +3880,14 @@ MENU_TEMPLATE_ITEM FindLookInBrowseMenu[] = case NM_RCLICK: { int clickedIndex = ((LPNMITEMACTIVATE)lParam)->iItem; - if (clickedIndex >= 0) // right-click outside the item won't show the menu + if (clickedIndex >= 0) // right-click outside an item will not show the menu { BOOL controlPressed = (GetKeyState(VK_CONTROL) & 0x8000) != 0; BOOL altPressed = (GetKeyState(VK_MENU) & 0x8000) != 0; BOOL shiftPressed = (GetKeyState(VK_SHIFT) & 0x8000) != 0; - // when clicking outside the selection while holding Shift (Alt+Ctrl doesn't matter) or - // holding only Alt, the selection changes to the clicked item before the menu is opened + // when clicking outside the selection while holding Shift (Alt+Ctrl does not matter), or + // while holding only Alt, the selection changes to the clicked item before the menu opens HWND hListView = FoundFilesListView->HWindow; if ((shiftPressed || altPressed && !controlPressed) && (ListView_GetItemState(hListView, clickedIndex, LVIS_SELECTED) & LVIS_SELECTED) == 0) @@ -3936,7 +3936,7 @@ MENU_TEMPLATE_ITEM FindLookInBrowseMenu[] = CacheBitmap->CreateBmp(hDC, 1, 1); } if (CacheBitmap == NULL) - break; // out of memory; let the list view draw it; we're done + break; // out of memory; let the list view handle drawing; abort custom drawing RECT r; // rectangle around the sub item ListView_GetSubItemRect(FoundFilesListView->HWindow, cd->nmcd.dwItemSpec, cd->iSubItem, LVIR_BOUNDS, &r); @@ -3988,8 +3988,8 @@ MENU_TEMPLATE_ITEM FindLookInBrowseMenu[] = SelectObject(CacheBitmap->HMemDC, (HFONT)SendMessage(FoundFilesListView->HWindow, WM_GETFONT, 0, 0)); int oldTextColor = SetTextColor(CacheBitmap->HMemDC, GetSysColor(textColor)); - // DT_PATH_ELLIPSIS doesn't work on some strings and causing clipped text to be printed - // PathCompactPath() requires a copy in a local buffer but doesn't clip text + // DT_PATH_ELLIPSIS does not work for some strings and can cause clipped text to be drawn + // PathCompactPath() requires a copy in a local buffer, but it does not clip the text char buff[2 * MAX_PATH]; strncpy_s(buff, _countof(buff), item2->Path, _TRUNCATE); PathCompactPath(CacheBitmap->HMemDC, buff, r2.right - r2.left); @@ -4289,8 +4289,8 @@ MENU_TEMPLATE_ITEM FindLookInBrowseMenu[] = case WM_ACTIVATEAPP: { - if (wParam == FALSE) // when deactivated we leave directories shown in panels - { // so they can be deleted, dissconected, etc. by other software + if (wParam == FALSE) // when deactivated, we leave the directories shown in the panels + { // so other software can delete or disconnect them, etc. if (CanChangeDirectory()) SetCurrentDirectoryToSystem(); } diff --git a/src/finddlg2.cpp b/src/finddlg2.cpp index 934815360..875874c9c 100644 --- a/src/finddlg2.cpp +++ b/src/finddlg2.cpp @@ -438,7 +438,7 @@ void CFindTBHeader::StartFlashIcon() { StopFlash = FALSE; if (GetForegroundWindow() != HNotifyWindow) - SendMessage(HNotifyWindow, WM_USER_FLASHICON, 0, 0); // if we are not active, postpone flashing + SendMessage(HNotifyWindow, WM_USER_FLASHICON, 0, 0); // if we are not active, defer flashing until later else SetTimer(HWindow, IDT_FLASHICON, FLASH_ICON_DELAY, NULL); FlashIconCounter = FLASH_ICON_COUNT; @@ -1235,7 +1235,7 @@ BOOL CFindDialog::GetCommonPrefixPath(char* buffer, int bufferMax, int& commonPr pathLen = count; } if (count == 0) - return FALSE; // there is no common path part + return FALSE; // no common part of the path } } } while (index != -1); @@ -1394,10 +1394,10 @@ void CFindDialog::OnDrag(BOOL rightMouseButton) { // returns dwEffect == 0 for MOVE, see the "Handling Shell Data Transfer Scenarios" section // "Handling Optimized Move Operations": http://msdn.microsoft.com/en-us/library/windows/desktop/bb776904%28v=vs.85%29.aspx - // shortened: an optimized Move is performed, meaning no copy is made to the target followed by deletion - // of the original. this avoids accidentally deleting the source before it’s actually moved (which might not be moved yet), - // the operation returns DROPEFFECT_NONE or DROPEFFECT_COPY, - // so we implement this workaround + // shortened: an optimized Move is performed, meaning no copy to the target followed by deletion + // of the original is done, so the source does not accidentally delete the original before it + // is actually moved; the operation result is DROPEFFECT_NONE or DROPEFFECT_COPY, + // so we use this workaround if (!rightMouseButton && // right button has a menu: dropSource->LastEffect contains the effect before showing the menu, not the final one: the final effect (except for Move) is in dwEffect - for Move it is 0, same as for Cancel, so we cannot distinguish Move from Cancel and therefore we’d better not delete anything (dropSource->LastEffect & DROPEFFECT_MOVE)) { diff --git a/src/geticon.cpp b/src/geticon.cpp index cfd92ae58..2058db47f 100644 --- a/src/geticon.cpp +++ b/src/geticon.cpp @@ -66,7 +66,7 @@ BOOL SalGetIconFromPIDL(IShellFolder* psf, const char* path, LPCITEMIDLIST pidl, { BOOL ret = FALSE; - IExtractIconA* pxi = NULL; // if 'isIExtractIconW' is TRUE, this pointer is actually IExtractIconW + IExtractIconA* pxi = NULL; // if 'isIExtractIconW' is TRUE, this pointer is of type IExtractIconW BOOL isIExtractIconW = FALSE; HICON hIconSmall = NULL; HICON hIconLarge = NULL; @@ -227,7 +227,7 @@ BOOL SalGetIconFromPIDL(IShellFolder* psf, const char* path, LPCITEMIDLIST pidl, else hres = pxi->Extract(iconFile, iconIndex, &hIconLarge, &hIconSmall, MAKELONG(IconSizes[largeIconSize], IconSizes[ICONSIZE_16])); //TRACE_I(" SalGetIconFromPIDL() pxi->Extract() hIconLarge="<ToolTip->SetCurrentToolTip(HWindow, 1, -1); MainWindow->ToolTip->Show(r.left + xOffset, r.bottom, FALSE, TRUE, HWindow); - // note: Show has the parameter 'modal'==TRUE, so control returns here only after the tooltip is closed + // Show is called with modal == TRUE, so execution returns here only after the tooltip is closed. return TRUE; } @@ -988,7 +988,7 @@ CStaticText::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { if (wParam == TRUE) break; - // if someone hides us, we must dismiss the tooltip + // if we are hidden, we must dismiss the tooltip if (MainWindow != NULL && MainWindow->ToolTip != NULL && MainWindow->ToolTip->HWindow != NULL) MainWindow->ToolTip->Hide(); //PostMessage(MainWindow->ToolTip->HWindow, WM_CANCELMODE, 0, 0); @@ -1065,7 +1065,7 @@ CStaticText::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) PAINTSTRUCT ps; HANDLES(BeginPaint(HWindow, &ps)); - // if we have a bitmap,we will draw into it, otherwise directly to the screen + // if we have a bitmap, draw into it; otherwise draw directly to the screen HDC hDC; if (Bitmap != NULL) hDC = Bitmap->HMemDC; @@ -1121,8 +1121,8 @@ CStaticText::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) else drawFlags |= DT_LEFT; // because ClearType spills beyond the control and leaves stray colored dots, we must - // clip everything; the issue is visible in the Plugins Manager Salamander 2.51 when scrolling - // the plugin list, leaving a red dot before the URL + // clip everything; the issue is visible in Salamander 2.51's Plugins Manager when scrolling + // the plugin list up and down: a red dot remains before the URL // if (!ClipDraw) drawFlags |= DT_NOCLIP; @@ -1281,15 +1281,15 @@ BOOL CHyperLink::ExecuteIt() void CHyperLink::OnContextMenu(int x, int y) { - /* used by the export_mnu.py script that generates salmenu.mnu for the Translator + /* used by the export_mnu.py script, which generates salmenu.mnu for Translator keep synchronized with the InsertMenu() call below... -MENU_TEMPLATE_ITEM HyperLinkMenu[] = -{ - {MNTT_PB, 0 - {MNTT_IT, IDS_COPYTOCLIPBOARD - {MNTT_PE, 0 -}; -*/ + MENU_TEMPLATE_ITEM HyperLinkMenu[] = + { + {MNTT_PB, 0 + {MNTT_IT, IDS_COPYTOCLIPBOARD + {MNTT_PE, 0 + }; + */ HMENU hMenu = CreatePopupMenu(); InsertMenu(hMenu, 0, MF_BYPOSITION, 1, LoadStr(IDS_COPYTOCLIPBOARD)); DWORD cmd = TrackPopupMenuEx(hMenu, TPM_RETURNCMD | TPM_LEFTALIGN | TPM_RIGHTBUTTON, @@ -1771,7 +1771,7 @@ int CButton::HitTest(LPARAM lParam) RECT r = ClientRect; r.left = r.right - GetDropPartWidth() - 1; if (PtInRect(&r, p)) - return 2; // drop down + return 2; // drop-down part } return 1; // button @@ -2953,10 +2953,10 @@ CAnimate::IsGood() void CAnimate::Paint(HDC hdc) { - // just to be safe, we synchronize access to the bitmap + // just to be safe, synchronize access to the bitmap HANDLES(EnterCriticalSection(&GDICriticalSection)); - // if no DC is provided, we obtain our own + // if no DC is provided, obtain our own HDC hDC; if (hdc == NULL) hDC = HANDLES(GetDC(HWindow)); @@ -3046,8 +3046,8 @@ CAnimate::ThreadF(void *param) handles[0] = animate->HTerminateEvent; // must be at index zero because it has priority handles[1] = animate->HRunEvent; - // raise the thread priority so the animation doesn't buffer - // we can afford it because it consumes almost no time + // raise the thread priority so the animation does not stutter + // we can afford it because it takes almost no time SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); while (TRUE) @@ -3055,9 +3055,9 @@ CAnimate::ThreadF(void *param) DWORD wait = WaitForMultipleObjects(2, handles, FALSE, INFINITE); if (wait == WAIT_OBJECT_0) - break; // we need to terminate the thread + break; // terminate the thread - if (animate->SleepThread) // we should stop the animation + if (animate->SleepThread) // stop the animation { animate->FirstFrame(); // move to the first frame ResetEvent(animate->HRunEvent); // and disable running @@ -3067,8 +3067,8 @@ CAnimate::ThreadF(void *param) animate->Paint(); // move to the next one animate->NextFrame(); - // 1000ms / 40ms = 25 frames per second, just like in a movie - WaitForSingleObject(animate->HTerminateEvent, 40); // if we should exit, we wll not wait unnecessarily + // 1000 ms / 40 ms = 25 frames per second, like in a movie + WaitForSingleObject(animate->HTerminateEvent, 40); // if we are terminating, do not wait here unnecessarily } TRACE_I("End"); return 0; @@ -3089,7 +3089,7 @@ CAnimate::AuxThreadEH(void *param) { TRACE_I("Thread in CAnimate: calling ExitProcess(1)."); // ExitProcess(1); - TerminateProcess(GetCurrentProcess(), 1); // harder exit (this call still performs some operations) + TerminateProcess(GetCurrentProcess(), 1); // more forceful exit return 1; } #endif // CALLSTK_DISABLE @@ -3341,7 +3341,7 @@ void CondenseStaticTexts(HWND hWindow, int* staticsArr) while (staticsArr[count] != 0) count++; if (count < 2) - return; // there isnothing to do + return; // nothing to do HFONT hFont = (HFONT)SendDlgItemMessage(hWindow, staticsArr[0], WM_GETFONT, 0, 0); HDC hDC = HANDLES(GetDC(hWindow)); @@ -3388,7 +3388,7 @@ BOOL CALLBACK FindHorizLines(HWND hwnd, LPARAM lParam) { RECT r; GetClientRect(hwnd, &r); - if (r.bottom == 0) // horizontal line 0 points high + if (r.bottom == 0) // horizontal line with zero height { LONG style = GetWindowLong(hwnd, GWL_STYLE); if ((style & SS_TYPEMASK) == SS_ETCHEDHORZ) @@ -3426,7 +3426,7 @@ struct CDataForFindHorizLineLabel BOOL CALLBACK FindHorizLineLabel(HWND hwnd, LPARAM lParam) { CDataForFindHorizLineLabel* data = (CDataForFindHorizLineLabel*)lParam; - if (data->Line != hwnd) // skip the line for which we search a label + if (data->Line != hwnd) // skip the line whose label we are looking for { RECT r; GetWindowRect(hwnd, &r); @@ -3454,7 +3454,7 @@ BOOL CALLBACK FindHorizLineLabel(HWND hwnd, LPARAM lParam) } else { - if (stricmp(className, "Button") == 0) // it's a button (check box, radio button, or push button) + if (stricmp(className, "Button") == 0) // this is a button (check box, radio button, or push button) { if (((style & BS_TYPEMASK) == BS_CHECKBOX || (style & BS_TYPEMASK) == BS_AUTOCHECKBOX || @@ -3491,7 +3491,7 @@ struct CDataForFindGroupBoxLabel BOOL CALLBACK FindGroupBoxLabel(HWND hwnd, LPARAM lParam) { CDataForFindGroupBoxLabel* data = (CDataForFindGroupBoxLabel*)lParam; - if (data->GroupBox != hwnd) // skip the group box for which we search a label + if (data->GroupBox != hwnd) // skip the group box whose label we are looking for { RECT r; GetWindowRect(hwnd, &r); @@ -3595,7 +3595,7 @@ void ArrangeHorizontalLines(HWND hWindow) -lf.lfHeight < 16 ? 20 : // < 150% DPI -lf.lfHeight < 21 ? 25 - : 27; // < 200% DPI : == 200% DPI + : 27; // >= 200% DPI if (p2.x + (data.LineRect.right - data.LineRect.left) > p.x + boxSize + txtR.right + 2 * spaceWidth) { MoveWindow(data.Label, p.x, p.y, boxSize + txtR.right + spaceWidth, labelRect.bottom - labelRect.top, TRUE); diff --git a/src/gui.h b/src/gui.h index 206ffb89b..a6ae0b77b 100644 --- a/src/gui.h +++ b/src/gui.h @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once @@ -7,18 +8,18 @@ // // CProgressBar // -// Trida je vzdy alokovana (CObjectOrigin origin = ooAllocated) +// The class is always allocated (CObjectOrigin origin = ooAllocated) class CProgressBar : public CWindow { public: - // hDlg je parent window (dialog nebo okno) - // ctrlID je ID child okna + // hDlg is the parent window (dialog or window) + // ctrlID is the child window ID CProgressBar(HWND hDlg, int ctrlID); ~CProgressBar(); - // SetProgress lze volat z libovolneho threadu, vnitrne se zasila WM_USER_SETPROGRESS - // thread progress bary vsak musi bezet + // SetProgress can be called from any thread; internally it posts WM_USER_SETPROGRESS + // the thread progress bars themselves must, however, be running void SetProgress(DWORD progress, const char* text = NULL); void SetProgress2(const CQuadWord& progressCurrent, const CQuadWord& progressTotal, const char* text = NULL); @@ -37,59 +38,59 @@ class CProgressBar : public CWindow protected: int Width, Height; DWORD Progress; - CBitmap* Bitmap; // bitmapa pro memDC -> cache paintu - int BarX; // Xova souradnice obdelniku pro neznamy progress (pro Progress==-1) - BOOL MoveBarRight; // jede obdelnik vpravo? - DWORD SelfMoveTime; // 0: po zavolani SetProgress(-1) se obdelnicek pohne pouze o jeden dilek (0 je implicitni hodnota) - // vic jak 0: cas v [ms], po ktery se jeste budeme hybat po zavolani SetProgress(-1) - DWORD SelfMoveTicks; // ulozena hodnota GetTickCount() behem posledniho zavolani SetSelfMoveTime() - DWORD SelfMoveSpeed; // rychlost pohybu obdelnicku: hodnota je v [ms] a udava cas, po kterem se obdelnicek pohne - // minimum je 10ms, default hodnota je 50ms -- tedy 20 posunu za vterinu - // pozor na nizke hodnoty, samotna animace pak dokaze znatelne vytizit procesor - BOOL TimerIsRunning; // bezi timer? - char* Text; // pokud je ruzny od NULL, bude zobrazen misto cisla - HFONT HFont; // font pro progress bar + CBitmap* Bitmap; // bitmap for memDC -> paint cache + int BarX; // X coordinate of the rectangle for unknown progress (for Progress == -1) + BOOL MoveBarRight; // is the rectangle moving to the right? + DWORD SelfMoveTime; // 0: after calling SetProgress(-1), the rectangle moves by only one step (0 is the default value) + // >0: time in [ms] for which it continues moving after SetProgress(-1) is called + DWORD SelfMoveTicks; // stored GetTickCount() value from the last call to SetSelfMoveTime() + DWORD SelfMoveSpeed; // rectangle movement speed: the value is in [ms] and specifies after what time the rectangle moves + // the minimum is 10 ms, the default value is 50 ms, i.e. 20 moves per second + // beware of low values, the animation itself can then noticeably load the CPU + BOOL TimerIsRunning; // is the timer running? + char* Text; // if not NULL, it is displayed instead of the number + HFONT HFont; // font for the progress bar }; //**************************************************************************** // // CStaticText // -// Trida je vzdy alokovana (CObjectOrigin origin = ooAllocated) +// The class is always allocated (CObjectOrigin origin = ooAllocated) class CStaticText : public CWindow { public: - // hDlg je parent window (dialog nebo okno) - // ctrlID je ID child okna - // flags je kombinaci hodnot z rodiny STF_* (shared\spl_gui.h) + // hDlg is the parent window (dialog or window) + // ctrlID is the child window ID + // flags is a combination of values from the STF_* family (shared\spl_gui.h) CStaticText(HWND hDlg, int ctrlID, DWORD flags); ~CStaticText(); - // nastavi Text, vraci TRUE pri uspechu a FALSE pri nedostatku pameti + // sets Text; returns TRUE on success and FALSE if memory is insufficient BOOL SetText(const char* text); - // pozor, vraceny Text muze byt NULL + // note: the returned Text may be NULL const char* GetText() { return Text; } - // nastavi Text (pokud zacina nebo konci na mezeru, da do dvojitych uvozovek), - // vraci TRUE pri uspechu a FALSE pri nedostatku pameti + // sets Text (if it starts or ends with a space, it is wrapped in double quotes), + // returns TRUE on success and FALSE if memory is insufficient BOOL SetTextToDblQuotesIfNeeded(const char* text); - // na nekterych filesystemech muze byt jiny oddelovac casti cesty - // musi byt ruzny od '\0'; + // some filesystems may use a different path-component separator + // it must be different from '\0' void SetPathSeparator(char separator); - // priradi text, ktery bude zobrazen jako tooltip + // assigns the text that will be shown as the tooltip BOOL SetToolTipText(const char* text); - // priradi okno a id, kteremu se pri zobrazeni tooltipu zasle WM_USER_TTGETTEXT + // assigns the window and ID to which WM_USER_TTGETTEXT is sent when the tooltip is shown void SetToolTip(HWND hNotifyWindow, DWORD id); - // pokud je nastaveno na TRUE, tooltip lze vyvolat kliknutim na text nebo - // stisknutim klaves Up/Down/Space, ma-li control focus - // tootltip se pak zobrazi tesne pod textem a zustane zobrazen - // implicitne je nastaveno na FALSE + // if set to TRUE, the tooltip can be triggered by clicking the text or + // pressing Up/Down/Space when the control has focus + // the tooltip is then shown just below the text and remains visible + // by default it is set to FALSE void EnableHintToolTip(BOOL enable); // void UpdateControl(); @@ -100,37 +101,37 @@ class CStaticText : public CWindow void PrepareForPaint(); BOOL TextHitTest(POINT* screenCursorPos); - int GetTextXOffset(); // na zaklade promennych Alignment, Width a TextWidth vraci X posunuti textu + int GetTextXOffset(); // returns the X text offset based on Alignment, Width, and TextWidth void DrawFocus(HDC hDC); BOOL ToolTipAssigned(); BOOL ShowHint(); - DWORD Flags; // flagy pro chovani controlu - char* Text; // alokovany text - int TextLen; // delka retezce - char* Text2; // alokovany text obshujici vypustku; pouziva se se pouze s STF_END_ELLIPSIS nebo STF_PATH_ELLIPSIS - int Text2Len; // delka Text2 - int* AlpDX; // pole delek substringu; pouziva se se pouze s STF_END_ELLIPSIS nebo STF_PATH_ELLIPSIS - int TextWidth; // sirka textu v bodech - int TextHeight; // vyska textu v bodech - int Allocated; // velikost alokovaneho bufferu 'Text' a 'AlpDX' - int Width, Height; // rozmery staticu - CBitmap* Bitmap; // cache pro kresleni; pouziva se pouze s STF_CACHED_PAINT - HFONT HFont; // handlu fontu pouzivany ro kresleni textu - BOOL DestroyFont; // pokud je HFont alokovany, je TRUE, jinak je FALSE - BOOL ClipDraw; // je treba clipnout kresleni, protoze bychom vylezli ven - BOOL Text2Draw; // budeme kreslit z bufferu obsahujici vypustku + DWORD Flags; // flags controlling the control behavior + char* Text; // allocated text + int TextLen; // string length + char* Text2; // allocated text containing the ellipsis; used only with STF_END_ELLIPSIS or STF_PATH_ELLIPSIS + int Text2Len; // length of Text2 + int* AlpDX; // array of substring lengths; used only with STF_END_ELLIPSIS or STF_PATH_ELLIPSIS + int TextWidth; // text width in pixels + int TextHeight; // text height in pixels + int Allocated; // size of the allocated buffer for 'Text' and 'AlpDX' + int Width, Height; // dimensions of the static control + CBitmap* Bitmap; // drawing cache; used only with STF_CACHED_PAINT + HFONT HFont; // font handle used for drawing the text + BOOL DestroyFont; // if HFont is allocated, it is TRUE; otherwise it is FALSE + BOOL ClipDraw; // drawing must be clipped because it would go outside otherwise + BOOL Text2Draw; // the buffer containing the ellipsis will be drawn int Alignment; // 0=left, 1=center, 2=right - char PathSeparator; // oddelovac casti cesty; implicitne '\\' - BOOL MouseIsTracked; // instalovali jsme hlidani opusteni mysi - // podpora pro tooltips - char* ToolTipText; // retezec, ktery bude zobrazen jako nas tooltip - HWND HToolTipNW; // notifikacni okno - DWORD ToolTipID; // a ID pod kterym se ma tool tip dotazat na text - BOOL HintMode; // mame tooltip zobrazovat jako Hint? - WORD UIState; // zobrazovani akceleratoru + char PathSeparator; // path-component separator; '\\' by default + BOOL MouseIsTracked; // we enabled mouse-leave tracking + // tooltip support + char* ToolTipText; // string that will be shown as our tooltip + HWND HToolTipNW; // notification window + DWORD ToolTipID; // and the ID under which the tooltip should ask for the text + BOOL HintMode; // should the tooltip be shown as a Hint? + WORD UIState; // accelerator display state }; //**************************************************************************** @@ -141,9 +142,9 @@ class CStaticText : public CWindow class CHyperLink : public CStaticText { public: - // hDlg je parent window (dialog nebo okno) - // ctrlID je ID child okna - // flags je kombinaci hodnot z rodiny STF_* (shared\spl_gui.h) + // hDlg is the parent window (dialog or window) + // ctrlID is the child window ID + // flags is a combination of values from the STF_* family (shared\spl_gui.h) CHyperLink(HWND hDlg, int ctrlID, DWORD flags = STF_UNDERLINE | STF_HYPERLINK_COLOR); void SetActionOpen(const char* file); @@ -156,8 +157,8 @@ class CHyperLink : public CStaticText BOOL ExecuteIt(); protected: - char File[MAX_PATH]; // pokud je ruzny od 0, predava se do ShellExecute - WORD Command; // pokud je ruzny od 0, posti se pri akci + char File[MAX_PATH]; // if not zero, it is passed to ShellExecute + WORD Command; // if not zero, it is posted on action HWND HDialog; // parent dialog }; @@ -165,8 +166,8 @@ class CHyperLink : public CStaticText // // CColorRectangle // -// vykresli celou plochu objektu barvou Color -// kombinovat s WS_EX_CLIENTEDGE +// paints the entire object area with Color +// combine with WS_EX_CLIENTEDGE // class CColorRectangle : public CWindow @@ -231,24 +232,24 @@ class CButton : public CWindow BOOL Captured; BOOL Space; RECT ClientRect; - // podpora pro tooltips - BOOL MouseIsTracked; // instalovali jsme hlidani opusteni mysi - char* ToolTipText; // retezec, ktery bude zobrazen jako nas tooltip - HWND HToolTipNW; // notifikacni okno - DWORD ToolTipID; // a ID pod kterym se ma tool tip dotazat na text - DWORD DropDownUpTime; // cas v [ms], kdy byl odmackunt drop down, pro ochranu pred novym zamacknutim - // podpora pro XP Theme + // tooltip support + BOOL MouseIsTracked; // we enabled mouse-leave tracking + char* ToolTipText; // string that will be shown as our tooltip + HWND HToolTipNW; // notification window + DWORD ToolTipID; // and the ID under which the tooltip should ask for the text + DWORD DropDownUpTime; // time in [ms] when the drop-down was released, to guard against a new press + // XP Theme support BOOL Hot; - WORD UIState; // zobrazovani akceleratoru + WORD UIState; // accelerator display state public: CButton(HWND hDlg, int ctrlID, DWORD flags, CObjectOrigin origin = ooAllocated); ~CButton(); - // priradi text, ktery bude zobrazen jako tooltip + // assigns the text that will be shown as the tooltip BOOL SetToolTipText(const char* text); - // priradi okno a id, kteremu se pri zobrazeni tooltipu zasle WM_USER_TTGETTEXT + // assigns the window and ID to which WM_USER_TTGETTEXT is sent when the tooltip is shown void SetToolTip(HWND hNotifyWindow, DWORD id); DWORD GetFlags(); @@ -259,7 +260,7 @@ class CButton : public CWindow virtual void PaintFace(HDC hdc, const RECT* rect, BOOL enabled); - int HitTest(LPARAM lParam); // vraci 0: nikde; 1: tlacitko; 2: drop down + int HitTest(LPARAM lParam); // returns 0: nowhere; 1: button; 2: drop-down void PaintFrame(HDC hDC, const RECT* r, BOOL down); void PaintDrop(HDC hDC, const RECT* r, BOOL enabled); int GetDropPartWidth(); @@ -274,7 +275,7 @@ class CButton : public CWindow // // CColorArrowButton // -// pozadi s textem, za kterym je jeste sipka - slouzi pro rozbaleni menu +// background with text followed by an arrow; used to expand the menu // class CColorArrowButton : public CButton @@ -320,9 +321,9 @@ class CToolbarHeader : public CWindow HIMAGELIST HHotImageList; HIMAGELIST HGrayImageList; #endif - DWORD ButtonMask; // pouzita tlacitka - HWND HNotifyWindow; // kam posilam comandy - WORD UIState; // zobrazovani akceleratoru + DWORD ButtonMask; // buttons in use + HWND HNotifyWindow; // where commands are sent + WORD UIState; // accelerator display state public: CToolbarHeader(HWND hDlg, int ctrlID, HWND hAlignWindow, DWORD buttonMask); @@ -350,50 +351,50 @@ class CToolbarHeader : public CWindow class CAnimate: public CWindow { protected: - HBITMAP HBitmap; // bitmapa ze ktere tahame jednotliva policka animace - int FramesCount; // pocet policek v bitmape - int FirstLoopFrame; // pokud jedeme ve smycce, z konce prechazime na toto policko - SIZE FrameSize; // rozmer policka v bodech - CRITICAL_SECTION GDICriticalSection; // kriticka sekce pro pristup ke GDI prostredkum - CRITICAL_SECTION DataCriticalSection; // kriticka sekce pro pristup k datum + HBITMAP HBitmap; // bitmap from which we take the individual animation frames + int FramesCount; // number of frames in the bitmap + int FirstLoopFrame; // when looping, we jump from the end back to this frame + SIZE FrameSize; // frame size in pixels + CRITICAL_SECTION GDICriticalSection; // critical section for access to GDI resources + CRITICAL_SECTION DataCriticalSection; // critical section for data access HANDLE HThread; - HANDLE HRunEvent; // pokud je signed, animacni thread bezi - HANDLE HTerminateEvent; // pokud je signed, thread se ukonci + HANDLE HRunEvent; // if signed, the animation thread is running + HANDLE HTerminateEvent; // if signed, the thread terminates COLORREF BkColor; - // ridici promenne, prijdou ke slovu kdyz HRunEvent signed - BOOL SleepThread; // thread se ma uspat, HRunEvent bude resetnut + // control variables used when HRunEvent is signed + BOOL SleepThread; // the thread should sleep, HRunEvent will be reset - int CurrentFrame; // zero-based index prave zobrazeneho policka + int CurrentFrame; // zero-based index of the currently displayed frame int NestedCount; - BOOL MouseIsTracked; // instalovali jsme hlidani opusteni mysi + BOOL MouseIsTracked; // we enabled mouse-leave tracking public: - // 'hBitmap' je bitmapa ze ktere vykreslujeme policka pri animaci; - // policka musi byt pod sebou a musi mit konstantni vysku - // 'framesCount' udava celkovy pocet policek v bitmape - // 'firstLoopFrame' zero-based index policka, kam se pri cyklicke - // animaci vracime po dosazeni konce + // 'hBitmap' is the bitmap from which we draw the frames during animation; + // the frames must be stacked vertically and must have constant height + // 'framesCount' specifies the total number of frames in the bitmap + // 'firstLoopFrame' zero-based frame index to which we return after reaching + // the end during cyclic animation CAnimate(HBITMAP hBitmap, int framesCount, int firstLoopFrame, COLORREF bkColor, CObjectOrigin origin = ooAllocated); - BOOL IsGood(); // dopadnul dobre konstruktor? + BOOL IsGood(); // did the constructor complete successfully? - void Start(); // pokud neanimujeme, zacneme - void Stop(); // zastavi animaci a zobrazi uvodni policko - void GetFrameSize(SIZE *sz); // vraci rozmer v bodech potrebny pro zobrazeni policka + void Start(); // if not animating, start it + void Stop(); // stops the animation and shows the initial frame + void GetFrameSize(SIZE *sz); // returns the size in pixels needed to display a frame protected: virtual LRESULT WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam); - void Paint(HDC hdc = NULL); // zobraz soucasne policko; pokud je hdc NULL, vytahni si DC okna - void FirstFrame(); // nastav Frame na uvodni policko - void NextFrame(); // nastav Frame na dalsi policko; preskakuj uvodni sekvenci + void Paint(HDC hdc = NULL); // displays the current frame; if hdc is NULL, obtain the window DC + void FirstFrame(); // sets Frame to the initial frame + void NextFrame(); // sets Frame to the next frame; skip the initial sequence - // tela threadu + // thread bodies static unsigned ThreadF(void *param); static unsigned AuxThreadEH(void *param); static DWORD WINAPI AuxThreadF(void *param); - // ThreadF bude friend, aby mohl pristupovat na nase data + // ThreadF is a friend so it can access our data friend static unsigned ThreadF(void *param); }; */ @@ -416,51 +417,52 @@ BOOL ChangeToIconButton(HWND hParent, int ctrlID, int iconID); // **************************************************************************** // VerticalAlignChildToChild // -// slouzi k zarovnani "browse" tlacitka za editline / combobox (v resource workshopu je problem se trefit s tlacitkem za combobox) -// upravi velikost a pozici child okna 'alignID' tak, aby sedelo ve stejne vysce (a bylo stejne vysoke) jako child 'toID' +// used to align the "browse" button next to an edit line / combobox +// (in Resource Workshop it is hard to place the button correctly next to a combobox) +// adjusts the size and position of child window 'alignID' so that it sits at the same height +// (and has the same height) as child 'toID' void VerticalAlignChildToChild(HWND hParent, int alignID, int toID); // // **************************************************************************** // CondenseStaticTexts // -// sesune static texty tak, ze budou tesne navazovat - vzdalenost mezi nimi bude -// sire mezery dialog fontu; 'staticsArr' je pole IDcek staticu ukoncene nulou +// moves static texts so that they follow each other closely; the distance between them +// will equal the width of a space in the dialog font; 'staticsArr' is an array of static IDs terminated by zero void CondenseStaticTexts(HWND hWindow, int* staticsArr); // // **************************************************************************** // ArrangeHorizontalLines // -// najde horizontalni cary a dorazi je zprava na text, na ktery navazuji -// navic najde checkboxy a radioboxy, ktere tvori labely groupboxum a zkrati -// je podle jejich textu a aktualniho pisma v dialogu (eliminuje zbytecne -// mezery vznikle kvuli ruznym DPI obrazovky) +// finds horizontal lines and extends them from the right up to the text they follow +// it also finds checkboxes and radio buttons that serve as groupbox labels and shortens +// them according to their text and the current dialog font (eliminating unnecessary +// gaps caused by different display DPI settings) void ArrangeHorizontalLines(HWND hWindow); // // **************************************************************************** // GetWindowFontHeight // -// pro hWindow ziska aktualni font a vrati jeho vysku +// gets the current font for hWindow and returns its height int GetWindowFontHeight(HWND hWindow); // // **************************************************************************** // GetWindowFontHeight // -// vytvori imagelist obsahujici dva stavy checkboxu (unchecked a checked) -// a vrati jeho handle; 'itemSize' je sirka a vyska jedne polozky v bodech +// creates an imagelist containing the two checkbox states (unchecked and checked) +// and returns its handle; 'itemSize' is the width and height of one item in pixels HIMAGELIST CreateCheckboxImagelist(int itemSize); // // **************************************************************************** // SalLoadIcon // -// nacte ikonu urcenou 'hInst' a 'iconName', vrati jeji handle nebo NULL v pripade -// chyby; 'iconSize' udava pozadovanou velikost ikony; funkce je High DPI ready -// a vrati jeho handle; 'itemSize' je sirka a vyska jedne polozky v bodech +// loads the icon specified by 'hInst' and 'iconName' and returns its handle, or NULL on error; +// 'iconSize' specifies the requested icon size; the function is High DPI ready // -// Poznamka: stare API LoadIcon() neumi ikony vetsich velikosti, proto zavadime tuto -// funkci, ktera cte ikony pomoci noveho LoadIconWithScaleDown() +// Note: the old LoadIcon() API cannot handle larger icon sizes, so we introduce this +// function, which loads icons using the newer LoadIconWithScaleDown() HICON SalLoadIcon(HINSTANCE hInst, LPCTSTR iconName, CIconSizeEnum iconSize); diff --git a/src/icncache.cpp b/src/icncache.cpp index c30b69a86..3130647cc 100644 --- a/src/icncache.cpp +++ b/src/icncache.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -10,8 +11,8 @@ #include "geticon.h" #include "logo.h" -// melo by byt nasobkem hodnoty IL_ITEMS_IN_ROW -// aby se plne vyuzil prostor v bitmape +// should be a multiple of IL_ITEMS_IN_ROW +// to fully use the space in the bitmap #define ICONS_IN_LIST 100 // @@ -21,11 +22,11 @@ CIconCache::CIconCache() : TDirectArray(50, 30), - IconsCache(10, 5), // jedna polozka je CIconList drzici ICONS_IN_LIST ikonek - ThumbnailsCache(1, 20) // ziskavani thumbnailu je pomale, relokace je v tom hracka + IconsCache(10, 5), // one item is a CIconList holding ICONS_IN_LIST icons + ThumbnailsCache(1, 20) // obtaining thumbnails is slow, relocation is trivial by comparison { IconsCount = 0; - IconSize = ICONSIZE_COUNT; // zatim nenastaveno; pokus o pridani ikonky bez predchoziho volani SetIconSize() zpusobi TRACE_E + IconSize = ICONSIZE_COUNT; // not set yet; trying to add an icon without calling SetIconSize() first triggers TRACE_E DataIfaceForFS = NULL; } @@ -35,12 +36,12 @@ CIconCache::~CIconCache() } inline int CompareDWORDS(const char* s1, const char* s2, int length) -{ // porovna nejvyse 'length' DWORDu +{ // compares at most 'length' DWORDs // int res; const char* end = s1 + length; while (s1 <= end) { - // if ((res = *(DWORD *)s1 - *(DWORD *)s2) != 0) return res; // takhle to nejde (zkus si 0x8 a 0x0 ve 4-bitovych cislech) + // if ((res = *(DWORD *)s1 - *(DWORD *)s2) != 0) return res; // this does not work (try 0x8 and 0x0 as 4-bit numbers) if (*(DWORD*)s1 > *(DWORD*)s2) return 1; else @@ -56,12 +57,12 @@ inline int CompareDWORDS(const char* s1, const char* s2, int length) void CIconCache::SortArray(int left, int right, CPluginDataInterfaceEncapsulation* dataIface) { - if (dataIface != NULL) // jde o pitFromPlugin: nechame plugin, aby polozky porovnal sam (musi jit o porovnani - { // beze shod zadnych dvou polozek listingu) + if (dataIface != NULL) // this is pitFromPlugin: let the plugin compare the items itself (the comparison must not treat any two listing items as equal) + { // with no two identical listing items) DataIfaceForFS = dataIface; BOOL ok = TRUE; int i; - for (i = left; i <= right; i++) // jeden paranoicky testik + for (i = left; i <= right; i++) // one paranoid check { if (Data[i].GetFSFileData() == NULL) { @@ -74,7 +75,7 @@ void CIconCache::SortArray(int left, int right, CPluginDataInterfaceEncapsulatio SortArrayForFSInt(left, right); DataIfaceForFS = NULL; } - else // klasicke razeni podle jmen + else // standard sorting by name { SortArrayInt(left, right); } @@ -106,7 +107,8 @@ void CIconCache::SortArrayInt(int left, int right) } } while (i <= j); - // nasledujici "hezky" kod jsme nahradili kodem podstatne setricim stack (max. log(N) zanoreni rekurze) + // The following "nice" code was replaced with code that saves substantially more stack + // space (maximum recursion depth log(N)). // if (left < j) SortArrayInt(left, j); // if (i < right) SortArrayInt(i, right); @@ -114,7 +116,7 @@ void CIconCache::SortArrayInt(int left, int right) { if (i < right) { - if (j - left < right - i) // je potreba seradit obe "poloviny", tedy do rekurze posleme tu mensi, tu druhou zpracujeme pres "goto" + if (j - left < right - i) // Both halves need to be sorted: recurse into the smaller one and process the other via goto. { SortArrayInt(left, j); left = i; @@ -168,7 +170,7 @@ void CIconCache::SortArrayForFSInt(int left, int right) } } while (i <= j); - // nasledujici "hezky" kod jsme nahradili kodem podstatne setricim stack (max. log(N) zanoreni rekurze) + // The following "nice" code was replaced with code that uses significantly less stack (maximum recursion depth log(N)). // if (left < j) SortArrayForFSInt(left, j); // if (i < right) SortArrayForFSInt(i, right); @@ -176,7 +178,7 @@ void CIconCache::SortArrayForFSInt(int left, int right) { if (i < right) { - if (j - left < right - i) // je potreba seradit obe "poloviny", tedy do rekurze posleme tu mensi, tu druhou zpracujeme pres "goto" + if (j - left < right - i) // Both halves need to be sorted, so recurse into the smaller one and process the other using goto. { SortArrayForFSInt(left, j); left = i; @@ -208,7 +210,7 @@ void CIconCache::SortArrayForFSInt(int left, int right) BOOL CIconCache::GetIndex(const char* name, int& index, CPluginDataInterfaceEncapsulation* dataIface, const CFileData* file) { - if (Count == 0 || dataIface != NULL && file == NULL) // overime platnost 'file' + if (Count == 0 || dataIface != NULL && file == NULL) // verify that 'file' is valid { if (dataIface != NULL && file == NULL) TRACE_E("CIconCache::GetIndex(): 'file' may not be NULL when 'dataIface' is not NULL! item=" << name); @@ -216,8 +218,8 @@ BOOL CIconCache::GetIndex(const char* name, int& index, CPluginDataInterfaceEnca return FALSE; } - if (dataIface != NULL) // jde o pitFromPlugin: nechame plugin, aby polozky porovnal sam (musi jit o porovnani - { // beze shod zadnych dvou polozek listingu) + if (dataIface != NULL) // this is pitFromPlugin: let the plugin compare the items itself (the comparison must not treat any two listing items as equal) + { // with no two identical listing items) int l = 0, r = Count - 1, m; int res; while (1) @@ -232,34 +234,34 @@ BOOL CIconCache::GetIndex(const char* name, int& index, CPluginDataInterfaceEnca "for item: " << At(m).NameAndData); index = 0; - return FALSE; // chyba -> vratime treba: nenalezeno, vlozit na zacatek pole + return FALSE; // error -> return as if not found: insert at the beginning of the array } - if (res == 0) // nalezeno + if (res == 0) // found { index = m; return TRUE; } else if (res > 0) { - if (l == r || l > m - 1) // nenalezeno + if (l == r || l > m - 1) // not found { - index = m; // mel by byt na teto pozici + index = m; // it should be at this position return FALSE; } r = m - 1; } else { - if (l == r) // nenalezeno + if (l == r) // not found { - index = m + 1; // mel by byt az za touto pozici + index = m + 1; // it should be just after this position return FALSE; } l = m + 1; } } } - else // klasicke hledani podle jmena + else // classic search by name { int length = (int)strlen(name); int l = 0, r = Count - 1, m; @@ -268,25 +270,25 @@ BOOL CIconCache::GetIndex(const char* name, int& index, CPluginDataInterfaceEnca { m = (l + r) / 2; res = CompareDWORDS(At(m).NameAndData, name, length); - if (res == 0) // nalezeno + if (res == 0) // found { index = m; return TRUE; } else if (res > 0) { - if (l == r || l > m - 1) // nenalezeno + if (l == r || l > m - 1) // not found { - index = m; // mel by byt na teto pozici + index = m; // it should be at this position return FALSE; } r = m - 1; } else { - if (l == r) // nenalezeno + if (l == r) // not found { - index = m + 1; // mel by byt az za touto pozici + index = m + 1; // it should be just after this position return FALSE; } l = m + 1; @@ -307,31 +309,31 @@ void CIconCache::Release() DestroyMembers(); IconsCount = 0; - // destrukce raw dat z ThumbnailsCache + // destroy the raw data from ThumbnailsCache for (i = 0; i < ThumbnailsCache.Count; i++) { CThumbnailData* data = &ThumbnailsCache[i]; if (data->Bits != NULL) - free(data->Bits); // alokovano v CSalamanderThumbnailMaker::RenderToThumbnailData() + free(data->Bits); // allocated in CSalamanderThumbnailMaker::RenderToThumbnailData() } ThumbnailsCache.DestroyMembers(); } void CIconCache::Destroy() { - // uvonime alokovana data a pole samotne + // free the allocated data and the array itself Release(); - // destrukce imagelistu z IconsCache + // destroy the image lists from IconsCache IconsCache.DestroyMembers(); } void CIconCache::ColorsChanged() { CALL_STACK_MESSAGE1("CIconCache::ColorsChanged()"); - // tato funkce je volana pri zmene barev nebo barevne hloubky obrazovky - // druhy pripad neni reseny -- bylo by treba znovu konstruovat bitmapy - // v imagelistech pro aktualni barevnou hloubku + // this function is called when the screen colors or color depth change + // the second case is not handled; it would be necessary to reconstruct the bitmaps + // in the image lists for the current color depth COLORREF bkColor = GetCOLORREF(CurrentColors[ITEM_BK_NORMAL]); int i; for (i = 0; i < IconsCache.Count; i++) @@ -341,13 +343,13 @@ void CIconCache::ColorsChanged() il->SetBkColor(bkColor); } - // thumbnaily je potreba prekreslit, pokud se zmenila barva pozadi, budou se ikonky s pruhlednymi - // castmi kreslit do nove barvy pozadi + // thumbnails need to be redrawn if the background color changed; icons with transparent + // parts will be drawn onto the new background color for (i = 0; i < Count; i++) { CIconData* icon = &At(i); - if (icon->GetFlag() == 5 /* o.k. thumbnail */) - icon->SetFlag(6 /* stara verze thumbnailu */); + if (icon->GetFlag() == 5 /* valid thumbnail */) + icon->SetFlag(6 /* old thumbnail version */); } } @@ -355,7 +357,7 @@ int CIconCache::AllocIcon(CIconList** iconList, int* iconListIndex) { SLOW_CALL_STACK_MESSAGE1("CIconCache::AllocIcon()"); int cache = IconsCount / ICONS_IN_LIST; // cache - int index = IconsCount % ICONS_IN_LIST; // index v ramci teto cache + int index = IconsCount % ICONS_IN_LIST; // index within this cache if (cache >= IconsCache.Count) { if (cache > IconsCache.Count) @@ -408,11 +410,11 @@ int CIconCache::AllocThumbnail() { CALL_STACK_MESSAGE1("CIconCache::AllocThumbnail()"); - // stuktura pro drzeni thumbnailu + // structure for holding thumbnails CThumbnailData data; memset(&data, 0, sizeof(CThumbnailData)); - // zaradime jej do seznamu + // add it to the list int index = ThumbnailsCache.Add(data); if (!ThumbnailsCache.IsGood()) { @@ -420,7 +422,7 @@ int CIconCache::AllocThumbnail() return -1; } - // vratime index pridaneho prvku + // returns the index of the added item return index; } @@ -446,7 +448,7 @@ BOOL CIconCache::GetIcon(int iconIndex, CIconList** iconList, int* iconListIndex if (iconIndex >= 0 && iconIndex < IconsCount) { int cache = iconIndex / ICONS_IN_LIST; // cache - int index = iconIndex % ICONS_IN_LIST; // index v ramci cache + int index = iconIndex % ICONS_IN_LIST; // index within the cache if (cache < IconsCache.Count) { *iconList = IconsCache[cache]; @@ -473,8 +475,8 @@ void CIconCache::GetIconsAndThumbsFrom(CIconCache* icons, CPluginDataInterfaceEn int index1 = 0; int index2 = 0; - if (dataIface != NULL) // jde o pitFromPlugin: nechame plugin, aby polozky porovnal sam (musi jit o porovnani - { // beze shod zadnych dvou polozek listingu) + if (dataIface != NULL) // This is pitFromPlugin: let the plugin compare the items itself. + { // with no two identical listing items) const CFileData *file1, *file2; if (index1 < Count) @@ -489,7 +491,7 @@ void CIconCache::GetIconsAndThumbsFrom(CIconCache* icons, CPluginDataInterfaceEn } } else - return; // neni co spojovat + return; // nothing to merge if (index2 < icons->Count) { @@ -503,12 +505,12 @@ void CIconCache::GetIconsAndThumbsFrom(CIconCache* icons, CPluginDataInterfaceEn } } else - return; // neni co spojovat + return; // nothing to merge int res; while (1) { res = dataIface->CompareFilesFromFS(file1, file2); - if (res == 0) // shodne -> provedeme kopii (ikony a masky) + if (res == 0) // identical -> copy them (icons and masks) { CIconList* srcIconList; int srcIconListIndex; @@ -518,13 +520,13 @@ void CIconCache::GetIconsAndThumbsFrom(CIconCache* icons, CPluginDataInterfaceEn DWORD flag = icons->At(index2).GetFlag(); - if ((flag == 1 || flag == 2) && // platna nebo stara ikona - At(index1).GetFlag() == 0 && // zajima nas ikona (pokud doslo k prepnuti na thumbnail, starou ikonu nepotrebujeme) + if ((flag == 1 || flag == 2) && // valid or old icon + At(index1).GetFlag() == 0 && // we care about the icon (if it switched to a thumbnail, the old icon is no longer needed) GetIcon(At(index1).GetIndex(), &dstIconList, &dstIconListIndex) && icons->GetIcon(icons->At(index2).GetIndex(), &srcIconList, &srcIconListIndex)) { dstIconList->Copy(dstIconListIndex, srcIconList, srcIconListIndex); - At(index1).SetFlag((flag == 1 && transferIconsAndThumbnailsAsNew) ? 1 : 2); // ted uz je to stara (nebo platna/nova) verze ikony + At(index1).SetFlag((flag == 1 && transferIconsAndThumbnailsAsNew) ? 1 : 2); // now it is the old (or valid/new) icon version } } @@ -542,7 +544,7 @@ void CIconCache::GetIconsAndThumbsFrom(CIconCache* icons, CPluginDataInterfaceEn } } else - break; // uz neni co spojovat + break; // nothing left to merge } if (res == 0 || res > 0) // index2++ @@ -559,7 +561,7 @@ void CIconCache::GetIconsAndThumbsFrom(CIconCache* icons, CPluginDataInterfaceEn } } else - break; // uz neni co spojovat + break; // nothing left to merge } } } @@ -574,17 +576,17 @@ void CIconCache::GetIconsAndThumbsFrom(CIconCache* icons, CPluginDataInterfaceEn length = (int)strlen(name1); } else - return; // neni co spojovat + return; // nothing to merge if (index2 < icons->Count) name2 = icons->At(index2).NameAndData; else - return; // neni co spojovat + return; // nothing to merge int res; while (1) { res = CompareDWORDS(name1, name2, length); - if (res == 0) // shodne -> provedeme kopii (ikony a masky) || thumbnailu + if (res == 0) // match -> copy the icons and masks, or the thumbnail { CIconList* srcIconList; int srcIconListIndex; @@ -594,33 +596,33 @@ void CIconCache::GetIconsAndThumbsFrom(CIconCache* icons, CPluginDataInterfaceEn DWORD flag = icons->At(index2).GetFlag(); - if ((flag == 1 || flag == 2) && // platna nebo stara ikona - At(index1).GetFlag() == 0 && // zajima nas ikona (pokud doslo k prepnuti na thumbnail, starou ikonu nepotrebujeme) + if ((flag == 1 || flag == 2) && // valid or old icon + At(index1).GetFlag() == 0 && // we care about the icon (if it switched to a thumbnail, the old icon is no longer needed) GetIcon(At(index1).GetIndex(), &dstIconList, &dstIconListIndex) && icons->GetIcon(icons->At(index2).GetIndex(), &srcIconList, &srcIconListIndex)) { dstIconList->Copy(dstIconListIndex, srcIconList, srcIconListIndex); - At(index1).SetFlag((flag == 1 && transferIconsAndThumbnailsAsNew) ? 1 : 2); // ted uz je to stara (nebo platna/nova) verze ikony + At(index1).SetFlag((flag == 1 && transferIconsAndThumbnailsAsNew) ? 1 : 2); // now it is the old (or valid/new) icon version } else { CThumbnailData* srcThumbnailData; CThumbnailData* tgtThumbnailData; - if ((flag == 5 || flag == 6) && // platny nebo stary thumbnail - At(index1).GetFlag() == 4 && // zajima nas thumbnail (pokud doslo k prepnuti na ikonu, stary thumbnail nepotrebujeme) + if ((flag == 5 || flag == 6) && // valid or old thumbnail + At(index1).GetFlag() == 4 && // we care about the thumbnail (if it switched to an icon, the old thumbnail is no longer needed) GetThumbnail(At(index1).GetIndex(), &tgtThumbnailData) && icons->GetThumbnail(icons->At(index2).GetIndex(), &srcThumbnailData)) { - // stary thumbnail neni treba kopirovat -- staci predat jeho - // geometrii a raw data do ciloveho thumbnailu - *tgtThumbnailData = *srcThumbnailData; // predame stara data do nove cache - srcThumbnailData->Bits = NULL; // stara cache zanika a nesmi se dealokovat data + // the old thumbnail does not need to be copied; it is enough to pass its + // geometry and raw data to the target thumbnail + *tgtThumbnailData = *srcThumbnailData; // pass the old data to the new cache + srcThumbnailData->Bits = NULL; // the old cache is going away and must not deallocate the data int newFlag = 6; - // pokud kopirujeme platny thumbnail, zkontrolujeme znamku souboru (size+date), pripadne - // zkopirovany thumbnail oznacime rovnou jako platny (hrozba zmeny souboru beze zmeny - // size+date je miziva a rychlostni zisk je obrovsky) + // if we are copying a valid thumbnail, check the file stamp (size+date); if appropriate, + // mark the copied thumbnail as valid immediately (the risk of the file changing without + // changing size+date is negligible, while the speed gain is huge) if (flag == 5 && !forceReloadThumbnails) { if (transferIconsAndThumbnailsAsNew) @@ -628,7 +630,7 @@ void CIconCache::GetIconsAndThumbsFrom(CIconCache* icons, CPluginDataInterfaceEn else { int offset = length + 4; - offset -= (offset & 0x3); // offset % 4 (zarovnani po ctyrech bytech) + offset -= (offset & 0x3); // offset % 4 (4-byte alignment) if (*(CQuadWord*)(name1 + offset) == *(CQuadWord*)(name2 + offset) && CompareFileTime((FILETIME*)(name1 + offset + sizeof(CQuadWord)), (FILETIME*)(name2 + offset + sizeof(CQuadWord))) == 0) @@ -637,7 +639,7 @@ void CIconCache::GetIconsAndThumbsFrom(CIconCache* icons, CPluginDataInterfaceEn } } } - At(index1).SetFlag(newFlag); // ted uz je to stara (nebo platna/nova) verze thumbnailu + At(index1).SetFlag(newFlag); // now it is the old (or valid/new) thumbnail version } } } @@ -650,7 +652,7 @@ void CIconCache::GetIconsAndThumbsFrom(CIconCache* icons, CPluginDataInterfaceEn length = (int)strlen(name1); } else - break; // uz neni co spojovat + break; // nothing left to merge } if (res == 0 || res > 0) // index2++ @@ -658,7 +660,7 @@ void CIconCache::GetIconsAndThumbsFrom(CIconCache* icons, CPluginDataInterfaceEn if (++index2 < icons->Count) name2 = icons->At(index2).NameAndData; else - break; // uz neni co spojovat + break; // nothing left to merge } } } @@ -671,10 +673,10 @@ void CIconCache::SetIconSize(CIconSizeEnum iconSize) TRACE_E("CIconCache::SetIconSize() unexpected iconSize==ICONSIZE_COUNT"); return; } - if (iconSize == IconSize) // pokud se nemeni velikost, neni co resit + if (iconSize == IconSize) // if the size is not changing, there is nothing to do return; - // zahodime soucasne ikonky + // discard the current icons int i; for (i = 0; i < Count; i++) { @@ -738,7 +740,7 @@ BOOL GetIconFromAssocAux(BOOL initFlagAndIndexes, HKEY root, const char* keyName { type[0] = 0; - // file-type retezec ziskame jako value "" podklice keyName + // get the file-type string as the value "" of the keyName subkey if (HANDLES_Q(RegOpenKey(root, keyNameBuf, &openKey)) == ERROR_SUCCESS) { LONG typeSize = MAX_PATH; @@ -748,11 +750,11 @@ BOOL GetIconFromAssocAux(BOOL initFlagAndIndexes, HKEY root, const char* keyName } } - if (size - 1 + 7 <= MAX_PATH) // test na moznost otevirani pres asociace + if (size - 1 + 7 <= MAX_PATH) // test whether opening via associations is possible { memmove(keyNameBuf + size - 1, "\\Shell", 7); if (HANDLES_Q(RegOpenKey(root, keyNameBuf, &openKey)) == ERROR_SUCCESS) - { // obsahuje-li "\\shell" nejaky podklic, da se otvirat (asociace na Enter) + { // if "\\shell" contains any subkey, it can be opened (association for Enter) DWORD keys; if (RegQueryInfoKey(openKey, NULL, NULL, NULL, &keys, NULL, NULL, NULL, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) @@ -767,7 +769,7 @@ BOOL GetIconFromAssocAux(BOOL initFlagAndIndexes, HKEY root, const char* keyName if (size - 1 + 21 <= MAX_PATH) { memmove(keyNameBuf + size - 1, "\\ShellEx\\IconHandler", 21); - // obsahuje-li "\\ShellEx\\IconHandler", musi se tahat ze souboru + // if "\\ShellEx\\IconHandler" is present, the icon must be loaded from the file if (HANDLES_Q(RegOpenKey(root, keyNameBuf, &openKey)) == ERROR_SUCCESS) { found = TRUE; @@ -783,7 +785,7 @@ BOOL GetIconFromAssocAux(BOOL initFlagAndIndexes, HKEY root, const char* keyName if (HANDLES_Q(RegOpenKey(root, keyNameBuf, &openKey)) == ERROR_SUCCESS) { char buf[MAX_PATH]; - size = MAX_PATH; // ziskani cesty k ikone + size = MAX_PATH; // get the path to the icon DWORD type2 = REG_SZ; DWORD err = SalRegQueryValueEx(openKey, "", 0, &type2, (LPBYTE)buf, (LPDWORD)&size); @@ -803,7 +805,7 @@ BOOL GetIconFromAssocAux(BOOL initFlagAndIndexes, HKEY root, const char* keyName else strcpy(iconLocation, buf); - // odstranime uvozovky v pripade "\"jmeno_souboru\",cislo_ikony" (napr. "\"C:\\Program Files\\VideoLAN\\VLC\\vlc.exe\",0") + // remove quotes in the case "\"file_name\",icon_number" (for example "\"C:\\Program Files\\VideoLAN\\VLC\\vlc.exe\",0") char* num = strrchr(iconLocation, ','); if (num != NULL) { @@ -817,15 +819,15 @@ BOOL GetIconFromAssocAux(BOOL initFlagAndIndexes, HKEY root, const char* keyName char* numBeg = numEnd + 1; while (*++numEnd >= '0' && *numEnd <= '9') ; - if (numBeg < numEnd && *numEnd == 0 && // cislo ikony je za posledni carkou - *iconLocation == '"' && num - 1 > iconLocation && *(num - 1) == '"') // na zacatku a pred carkou jsou uvozovky - { // odstranime uvozovky + if (numBeg < numEnd && *numEnd == 0 && // the icon number is after the last comma + *iconLocation == '"' && num - 1 > iconLocation && *(num - 1) == '"') // there are quotes at the beginning and before the comma + { // remove the quotes memmove(iconLocation, iconLocation + 1, (num - 1) - (iconLocation + 1)); memmove(num - 2, num, numEnd - num + 1); } } - char* s = buf; // rozliseni typu "%1" od "...%promenna%..." + char* s = buf; // distinguish "%1" from "...%variable%..." while (*s != 0) { if (*s == '%') @@ -835,7 +837,7 @@ BOOL GetIconFromAssocAux(BOOL initFlagAndIndexes, HKEY root, const char* keyName { while (*s != 0 && *s != ' ' && *s != '%') s++; - if (*s != '%') // neni to env. promenna -> dynamicky typ + if (*s != '%') // not an environment variable -> dynamic type { data.SetIndexAll(-2); break; @@ -879,10 +881,10 @@ void CAssociations::Release() void CAssociations::Destroy() { - // uvonime alokovana data a pole samotne + // free the allocated data and the array itself Release(); - // destrukce imagelistu z IconsCache + // destroy the image lists from IconsCache int i; for (i = 0; i < ICONSIZE_COUNT; i++) Icons[i].IconsCache.DestroyMembers(); @@ -891,9 +893,9 @@ void CAssociations::Destroy() void CAssociations::ColorsChanged() { CALL_STACK_MESSAGE1("CAssociations::ColorsChanged()"); - // tato funkce je volana pri zmene barev nebo barevne hloubky obrazovky - // druhy pripad neni reseny -- bylo by treba znovu konstruovat bitmapy - // v imagelistech pro aktualni barevnou hloubku + // this function is called when the screen colors or color depth change + // the second case is not handled; it would be necessary to reconstruct the bitmaps + // in the image lists for the current color depth COLORREF bkColor = GetCOLORREF(CurrentColors[ITEM_BK_NORMAL]); int j; for (j = 0; j < ICONSIZE_COUNT; j++) @@ -906,7 +908,7 @@ void CAssociations::ColorsChanged() il->SetBkColor(bkColor); } } - // FIXME: stacilo by nastavovat pozadi pouze pro patricny iconlist + // FIXME: it would be enough to set the background only for the relevant icon list int i; for (i = 0; i < ICONSIZE_COUNT; i++) SimpleIconLists[i]->SetBkColor(bkColor); @@ -927,25 +929,25 @@ BOOL CAssociations::GetIndex(const char* name, int& index) { m = (l + r) / 2; res = CompareDWORDS(At(m).ExtensionAndData, name, length); - if (res == 0) // nalezeno + if (res == 0) // found { index = m; return TRUE; } else if (res > 0) { - if (l == r || l > m - 1) // nenalezeno + if (l == r || l > m - 1) // not found { - index = m; // mel by byt na teto pozici + index = m; // it should be at this position return FALSE; } r = m - 1; } else { - if (l == r) // nenalezeno + if (l == r) // not found { - index = m + 1; // mel by byt az za touto pozici + index = m + 1; // it should be just after this position return FALSE; } l = m + 1; @@ -957,7 +959,7 @@ int CAssociations::AllocIcon(CIconList** iconList, int* iconListIndex, CIconSize { CALL_STACK_MESSAGE1("CAssociations::AllocIcon()"); int cache = Icons[iconSize].IconsCount / ICONS_IN_LIST; // cache - int index = Icons[iconSize].IconsCount % ICONS_IN_LIST; // index v ramci teto cache + int index = Icons[iconSize].IconsCount % ICONS_IN_LIST; // index within this cache if (cache >= Icons[iconSize].IconsCache.Count) { if (cache > Icons[iconSize].IconsCache.Count) @@ -1008,7 +1010,7 @@ BOOL CAssociations::GetIcon(int iconIndex, CIconList** iconList, int* iconListIn if (iconIndex >= 0 && iconIndex < Icons[iconSize].IconsCount) { int cache = iconIndex / ICONS_IN_LIST; // cache - int index = iconIndex % ICONS_IN_LIST; // index v ramci cache + int index = iconIndex % ICONS_IN_LIST; // index within the cache if (cache < Icons[iconSize].IconsCache.Count) { *iconList = Icons[iconSize].IconsCache[cache]; @@ -1054,7 +1056,8 @@ void CAssociations::SortArray(int left, int right) } } while (i <= j); - // nasledujici "hezky" kod jsme nahradili kodem podstatne setricim stack (max. log(N) zanoreni rekurze) + // We replaced the following "nice" code with code that uses substantially less stack space + // // (maximum recursion depth of log(N)). // if (left < j) SortArray(left, j); // if (i < right) SortArray(i, right); @@ -1062,7 +1065,7 @@ void CAssociations::SortArray(int left, int right) { if (i < right) { - if (j - left < right - i) // je potreba seradit obe "poloviny", tedy do rekurze posleme tu mensi, tu druhou zpracujeme pres "goto" + if (j - left < right - i) // Both "halves" must be sorted, so recurse into the smaller one and process the other via "goto" { SortArray(left, j); left = i; @@ -1099,13 +1102,13 @@ void CAssociations::InsertData(const char* /*origin*/, int index, BOOL overwrite // ": type=" << (type == NULL ? "" : type)); size = (LONG)(s - e) + 4; - size -= (size & 0x3); // size % 4 (zarovnani po ctyrech bytech) + size -= (size & 0x3); // size % 4 (alignment to four bytes) int iLen = (int)strlen(iconLocation) + 1; data.ExtensionAndData = (char*)malloc(size + iLen); - memcpy(data.ExtensionAndData, e, size); // pripona + zarovnani nul + + memcpy(data.ExtensionAndData, e, size); // extension + null padding + memcpy(data.ExtensionAndData + size, iconLocation, iLen); // icon-location if (type[0] != 0) - data.Type = DupStr(type); // chyba -> jen se neukaze file-type + data.Type = DupStr(type); // error -> only the file type stays hidden else data.Type = NULL; if (overwriteItem) @@ -1122,28 +1125,28 @@ void CAssociations::InsertData(const char* /*origin*/, int index, BOOL overwrite void CAssociations::ReadAssociations(BOOL showWaitWnd) { - //--- nahozeni dialogu cekani + hodin + //--- bring up the wait dialog and hourglass HCURSOR oldCur; HWND parent = (MainWindow != NULL) ? MainWindow->HWindow : NULL; - // wait okenko zlobilo: - // pokud dam nad souborem Open With a zvolim napriklad NOTEPAD, ten se otevre - // potom se rozesle notifikace o zmene asociaci SHCNE_ASSOCCHANGED - // v dusledku se zavola tato fce, ktera zobrazi okenko a vytahne ho nahoru - // s nim vytahne celeho Salamandera, proto ho docasne zakazuji + // The wait window was problematic: + // if I use Open With on a file and choose, for example, NOTEPAD, it opens, + // then SHCNE_ASSOCCHANGED notifications are broadcast for the association change, + // which calls this function, shows the wait window, and pulls it to the front, + // taking the whole Salamander window with it, so I disable it temporarily CWaitWindow waitWnd(parent, IDS_READINGASSOCIATIONS, FALSE, ooStatic); BOOL closeDialog = FALSE; if (!ExistSplashScreen()) { if (showWaitWnd) - waitWnd.Create(); //j.r. pro ladeni shortcuty z desktopu + waitWnd.Create(); // j.r. for debugging desktop shortcuts oldCur = SetCursor(LoadCursor(NULL, IDC_WAIT)); closeDialog = TRUE; } else IfExistSetSplashScreenText(LoadStr(IDS_STARTUP_ASSOCIATIONS)); - //--- vycisteni pole + cache + //--- clear the array and cache Release(); - //--- projiti registry zaznamu o classech (extenzich) + //--- iterate through the registry records for classes (extensions) char ext[MAX_PATH + 4]; char extType[MAX_PATH]; char *s, *e; @@ -1162,8 +1165,8 @@ void CAssociations::ReadAssociations(BOOL showWaitWnd) systemFileAssoc = NULL; } - // Windows 2000 a novejsi maji jeste "Open With..." asociace ulozeny pro kazdeho usera zvlast - // v klici HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts + // Windows 2000 and later also store "Open With..." associations separately for each user + // in HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts HKEY explorerFileExts; if (HANDLES_Q(RegOpenKey(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts", &explorerFileExts)) != ERROR_SUCCESS) @@ -1175,13 +1178,13 @@ void CAssociations::ReadAssociations(BOOL showWaitWnd) LONG enumRet; FILETIME ft; while (1) - { // postupne enumnuti vsech pripon + { // enumerate all extensions one by one DWORD extS = MAX_PATH; if ((enumRet = RegEnumKeyEx(HKEY_CLASSES_ROOT, i, ext, &extS, NULL, NULL, NULL, &ft)) == ERROR_SUCCESS) - { // otevreni klice pripony + { // open the extension key if (ext[0] == '.' && HANDLES_Q(RegOpenKey(HKEY_CLASSES_ROOT, ext, &extKey)) == ERROR_SUCCESS) { - size = MAX_PATH; // ziskani typu asociace + size = MAX_PATH; // get the association type iconLocation[0] = 0; data.SetFlag(0); data.SetIndexAll(-1); @@ -1190,37 +1193,37 @@ void CAssociations::ReadAssociations(BOOL showWaitWnd) BOOL addExt = (SalRegQueryValue(extKey, "", extType, &size) == ERROR_SUCCESS && size > 1); if (addExt) { - // test na typ ikony (staticka/dynamicka viz .h) + // test the icon type (static/dynamic, see .h) tryPerceivedType = !GetIconFromAssocAux(FALSE, HKEY_CLASSES_ROOT, extType, size, data, iconLocation, type); } else tryPerceivedType = TRUE; if (tryPerceivedType && systemFileAssoc != NULL) { - // nejdrive zkusime najit 'ext' pod klicem SystemFileAssociations + // first try to find 'ext' under the SystemFileAssociations key if (GetIconFromAssocAux(FALSE, systemFileAssoc, ext, (LONG)strlen(ext) + 1, data, iconLocation, NULL)) addExt = TRUE; else - { // zkusime jeste klic z hodnoty PerceivedType (je-li definovana) + { // also try the key from the PerceivedType value, if it is defined size = MAX_PATH; if (SalRegQueryValueEx(extKey, "PerceivedType", NULL, NULL, (BYTE*)extType, (DWORD*)&size) == ERROR_SUCCESS && size > 1) { - extType[MAX_PATH - 1] = 0; // pro jistotu (hodnota nemusi byt typu string, pak muze chybet null-terminator) + extType[MAX_PATH - 1] = 0; // just in case (the value may not be a string, so the null terminator may be missing) if (GetIconFromAssocAux(FALSE, systemFileAssoc, extType, (LONG)strlen(extType) + 1, data, iconLocation, NULL)) addExt = TRUE; } } } if (addExt) - { // prevod ext. na mala pismena + pridani do pole - e = ext + 1; // preskok '.' + { // convert the extension to lowercase and add it to the array + e = ext + 1; // skip '.' s = e; while (*s != 0) { *s = LowerCase[*s]; s++; } - *(DWORD*)s = 0; // nulovani konce stringu + *(DWORD*)s = 0; // zero the end of the string InsertData("", Count, FALSE, e, s, data, size, iconLocation, type); } @@ -1231,41 +1234,41 @@ void CAssociations::ReadAssociations(BOOL showWaitWnd) { if (enumRet != ERROR_NO_MORE_ITEMS) { - // u jednoho usera (Bernard Vander Beken ) sem prijde - // jedna chyba ERROR_MORE_DATA, a pak spousta ERROR_OUTOFMEMORY, ma Microsoft Windows Server 2003, - // Standard Edition Service Pack 2 (Build 3790), zvetseni bufferu na 10000 nepomaha, nutne - // ukoncit enumeraci uz pri prvni chybe, jinak zacne cyklit a zarat pamet (zrejme jde - // o interni chybu Windowsu), nikdo dalsi to nehlasil, takze to dal neresime + // For one reported user, this returns + // one ERROR_MORE_DATA and then many ERROR_OUTOFMEMORY errors on Microsoft Windows Server 2003, + // Standard Edition Service Pack 2 (Build 3790). Increasing the buffer to 10000 does not help; + // enumeration must be stopped at the first error, otherwise it starts looping and eating memory + // (apparently an internal Windows bug). Nobody else reported it, so we do not investigate further. _snprintf_s(errBuf, _TRUNCATE, LoadStr(IDS_UNABLETOGETASSOC), GetErrorText(enumRet)); SalMessageBox(parent, errBuf, LoadStr(IDS_UNABLETOGETASSOCTITLE), MB_OK | MB_ICONEXCLAMATION); } - break; // konec enumerace + break; // end of enumeration } i++; } if (Count > 1) SortArray(0, Count - 1); - // Windows XP maji asociace (viz PerceivedType) ulozeny jeste v klici HKEY_CLASSES_ROOT\SystemFileAssociations, - // nacteme dosud nezname pripony jeste z tohoto klice + // Windows XP also stores associations (see PerceivedType) under HKEY_CLASSES_ROOT\SystemFileAssociations, + // so load any extensions that are still unknown from this key as well if (systemFileAssoc != NULL) { i = 0; while (1) - { // postupne enumnuti vsech pripon + { // enumerate all extensions one by one DWORD extS = MAX_PATH; if ((enumRet = RegEnumKeyEx(systemFileAssoc, i, ext, &extS, NULL, NULL, NULL, &ft)) == ERROR_SUCCESS) - { // otevreni klice pripony + { // open the extension key if (ext[0] == '.') { - e = ext + 1; // preskok '.' + e = ext + 1; // skip '.' s = ext; while (*++s != 0) *s = LowerCase[*s]; - *(DWORD*)s = 0; // nulovani konce stringu + *(DWORD*)s = 0; // zero the end of the string int index; - if (!GetIndex(e, index)) // nenalezeno, ma smysl zkoumat + pripadne pridat + if (!GetIndex(e, index)) // not found; it makes sense to check and add it if needed { if (GetIconFromAssocAux(TRUE, systemFileAssoc, ext, (LONG)strlen(ext) + 1, data, iconLocation, NULL)) { @@ -1278,15 +1281,15 @@ void CAssociations::ReadAssociations(BOOL showWaitWnd) { if (enumRet != ERROR_NO_MORE_ITEMS) { - // u jednoho usera (Bernard Vander Beken ) sem prijde - // jedna chyba ERROR_MORE_DATA, a pak spousta ERROR_OUTOFMEMORY, ma Microsoft Windows Server 2003, - // Standard Edition Service Pack 2 (Build 3790), zvetseni bufferu na 10000 nepomaha, nutne - // ukoncit enumeraci uz pri prvni chybe, jinak zacne cyklit a zrat pamet (zrejme jde - // o interni chybu Windowsu), nikdo dalsi to nehlasil, takze to dal neresime + // For one reported user, this returns + // one ERROR_MORE_DATA and then many ERROR_OUTOFMEMORY errors on Microsoft Windows Server 2003, + // Standard Edition Service Pack 2 (Build 3790). Increasing the buffer to 10000 does not help; + // enumeration must be stopped at the first error, otherwise it starts looping and eating memory + // (apparently an internal Windows bug). Nobody else reported it, so we do not investigate further. _snprintf_s(errBuf, _TRUNCATE, LoadStr(IDS_UNABLETOGETASSOC), GetErrorText(enumRet)); SalMessageBox(parent, errBuf, LoadStr(IDS_UNABLETOGETASSOCTITLE), MB_OK | MB_ICONEXCLAMATION); } - break; // konec enumerace + break; // end of enumeration } i++; } @@ -1296,46 +1299,46 @@ void CAssociations::ReadAssociations(BOOL showWaitWnd) { i = 0; while (1) - { // postupne enumnuti vsech pripon + { // enumerate all extensions one by one DWORD extS = MAX_PATH; if (RegEnumKeyEx(explorerFileExts, i, ext, &extS, NULL, NULL, NULL, &ft) == ERROR_SUCCESS) - { // otevreni klice pripony + { // open the extension key if (ext[0] == '.' && HANDLES_Q(RegOpenKey(explorerFileExts, ext, &extKey)) == ERROR_SUCCESS) { - e = ext + 1; // preskok '.' + e = ext + 1; // skip '.' s = ext; while (*++s != 0) *s = LowerCase[*s]; - *(DWORD*)s = 0; // nulovani konce stringu + *(DWORD*)s = 0; // zero the end of the string int index; BOOL found = GetIndex(e, index); if (WindowsVistaAndLater && HANDLES_Q(RegOpenKey(extKey, "UserChoice", &openKey)) == ERROR_SUCCESS) - { // zkusime, jestli neni asociovana pres klic UserChoice, pokud ano, je to neprioritnejsi zaznam, pripadne tedy prepiseme jiz existujici asociaci - size = MAX_PATH; // ziskani typu asociace + { // try whether it is associated through the UserChoice key; if so, it is the highest-priority record, so overwrite any association already found + size = MAX_PATH; // get the association type if (SalRegQueryValueEx(openKey, "Progid", NULL, NULL, (BYTE*)extType, (DWORD*)&size) == ERROR_SUCCESS && size > 1) { - extType[MAX_PATH - 1] = 0; // pro jistotu (hodnota nemusi byt typu string, pak muze chybet null-terminator) + extType[MAX_PATH - 1] = 0; // just in case (the value may not be a string, so the null terminator may be missing) if (GetIconFromAssocAux(TRUE, HKEY_CLASSES_ROOT, extType, (LONG)strlen(extType) + 1, data, iconLocation, type)) { - InsertData("UserChoice: ", index, found, e, s, data, size, iconLocation, type); // found==TRUE znamena prepis jiz nalezene asociace tou z UserChoice + InsertData("UserChoice: ", index, found, e, s, data, size, iconLocation, type); // found==TRUE means overwriting the association already found with the one from UserChoice found = TRUE; } } HANDLES(RegCloseKey(openKey)); } - if (!found) // zkusime jeste, jestli neni asociovana pres klic OpenWithProgids + if (!found) // Check whether it is associated through the OpenWithProgids key { if (WindowsVistaAndLater && HANDLES_Q(RegOpenKey(extKey, "OpenWithProgids", &openKey)) == ERROR_SUCCESS) { DWORD j = 0; - size = MAX_PATH; // ziskani typu asociace + size = MAX_PATH; // get the association type while (RegEnumValue(openKey, j++, extType, (DWORD*)&size, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) - { // postupne enumnuti vsech typu asociaci + { // enumerate all association types one by one if (extType[0] != 0) { - extType[MAX_PATH - 1] = 0; // pro jistotu (hodnota nemusi byt typu string, pak muze chybet null-terminator) + extType[MAX_PATH - 1] = 0; // just in case (the value may not be a string, so the null terminator may be missing) if (GetIconFromAssocAux(TRUE, HKEY_CLASSES_ROOT, extType, (LONG)strlen(extType) + 1, data, iconLocation, type)) { @@ -1344,7 +1347,7 @@ void CAssociations::ReadAssociations(BOOL showWaitWnd) break; } } - size = MAX_PATH; // ziskani typu asociace + size = MAX_PATH; // get the association type } HANDLES(RegCloseKey(openKey)); } @@ -1352,15 +1355,15 @@ void CAssociations::ReadAssociations(BOOL showWaitWnd) if (SalRegQueryValueEx(extKey, "Application", NULL, NULL, NULL, NULL) == ERROR_SUCCESS) { - if (found) // nalezeno, nastavime, ze ma asociaci + if (found) // found, mark that it has an association { CAssociationData* iconData = &(At(index)); - iconData->SetFlag(1); // soubory s touto priponou jdou otevirat - // iconData->SetIndexAll(-1); // prepnuti na statickou ikonu zlobi s CDR a CPT Corelackymi soubory s nahledy v ikonach, radsi nechame ikonu v nastaveni z HKEY_CLASSES_ROOT + iconData->SetFlag(1); // files with this extension can be opened + // iconData->SetIndexAll(-1); // switching to a static icon causes problems for CDR and CPT Corel files with thumbnails in their icons, so leave the icon configured in HKEY_CLASSES_ROOT } - else // nenalezeno, vlozime jako statickou ikonu + else // not found, insert it as a static icon { - data.SetFlag(1); // soubory s touto priponou jdou otevirat + data.SetFlag(1); // files with this extension can be opened data.SetIndexAll(-1); InsertData("FileExts: Application: ", index, FALSE, e, s, data, size, "", ""); @@ -1370,13 +1373,13 @@ void CAssociations::ReadAssociations(BOOL showWaitWnd) } } else - break; // konec enumerace + break; // end of enumeration i++; } HANDLES(RegCloseKey(explorerFileExts)); } - // pridani pevnych ikonek vsech velikosti do cache-bitmap CAssociations + // add fixed icons of all sizes to the CAssociations cache bitmap int iconSize; for (iconSize = 0; iconSize < ICONSIZE_COUNT; iconSize++) { @@ -1440,8 +1443,8 @@ BOOL CAssociations::IsAssociated(char* ext, BOOL& addtoIconCache, CIconSizeEnum { int i = At(index).GetIndex(iconSize); if (i == -1) - At(index).SetIndex(-3, iconSize); // nenactena -> nacitana - addtoIconCache = (i == -1 || i == -2); // dynamicka nebo nenactena/nenacitana staticka + At(index).SetIndex(-3, iconSize); // not loaded -> loading + addtoIconCache = (i == -1 || i == -2); // dynamic or static not loaded/not loading return At(index).GetFlag() != 0; } else @@ -1460,7 +1463,7 @@ BOOL CAssociations::IsAssociatedStatic(char* ext, const char*& iconLocation, CIc if (i == -1) { At(index).SetIndex(-3, iconSize); // nenactena -> nacitana - iconLocation = At(index).ExtensionAndData; // nenactena/nenacitana staticka + iconLocation = At(index).ExtensionAndData; // unloaded static item } else iconLocation = NULL; diff --git a/src/icncache.h b/src/icncache.h index 3ecb1848b..3eec99ef2 100644 --- a/src/icncache.h +++ b/src/icncache.h @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once @@ -11,29 +12,29 @@ class CIconData { public: - char* NameAndData; // alokovano po DWORDech, konce nulovane (kvuli porovnavani); - // pro Flag==3 (i pro ==1, nasleduje-li po ==3) navic pripojen string s icon-location; - // pro Flag==4,5,6 navic pripojena znamka souboru (CQuadWord Size + FILETIME LastWrite) - // a seznam rozhrani CPluginInterfaceForThumbLoaderEncapsulation - // vsech pluginu, ktere umi vytvorit thumbnail pro soubor 'NameAndData', seznam je ukoncen - // NULLem) - const CFileData* FSFileData; // ukazatel na CFileData souboru (jen u FS s typem ikon pitFromPlugin), jinak NULL + char* NameAndData; // allocated on DWORD boundaries, null-terminated at the end (for comparison); + // for Flag==3 (and for ==1 if it follows ==3), a string with icon-location is also appended; + // for Flag==4,5,6, the file stamp (CQuadWord Size + FILETIME LastWrite) is also appended, + // along with the list of CPluginInterfaceForThumbLoaderEncapsulation interfaces for all + // plugins that can create a thumbnail for file 'NameAndData'; the list is terminated + // with NULL) + const CFileData* FSFileData; // pointer to CFileData for the file (only for FS with icon type pitFromPlugin), otherwise NULL private: - DWORD Index : 28; // >= 0 index do cache ikon nebo thumbnailu (index musi byt < 134217728); -1 -> nenactene; - // pri Flag==0,1,2,3 jde o index do cache ikon; - // pri Flag==4,5,6 jde o index do cache thumbnailu - DWORD ReadingDone : 1; // 1 = uz jsme se pokouseli nacist (i neuspesne), 0 = jeste jsme nenacitali - DWORD Flag : 3; // flag k danemu typu, v CIconCache: - // ikony: 0 - nenactene, 1 - o.k., 2 - stara verze, 3 - ikona zadana pomoci icon-location - // thumbnaily: 4 - nenactene, 5 - o.k., 6 - stara verze (nebo nekvalitni/mensi) + DWORD Index : 28; // >= 0 index into the icon or thumbnail cache (must be < 134217728); -1 -> not loaded; + // for Flag==0,1,2,3 this is an index into the icon cache; + // for Flag==4,5,6 this is an index into the thumbnail cache + DWORD ReadingDone : 1; // 1 = we already tried to load it (even unsuccessfully), 0 = we have not tried yet + DWORD Flag : 3; // flag for the given type, in CIconCache: + // icons: 0 - not loaded, 1 - OK, 2 - old version, 3 - icon specified via icon-location + // thumbnails: 4 - not loaded, 5 - OK, 6 - old version (or poor-quality/smaller) public: int GetIndex() { int index = Index; if (index & 0x08000000) - index |= 0xF0000000; // neumi 28-bit int na 32-bit int ... + index |= 0xF0000000; // sign-extend 28-bit int to 32-bit int ... return index; } @@ -57,17 +58,17 @@ class CIconData // // -// reprezentuje jeden thumbnail v CIconCache::ThumbnailsCache -// protoze pri vetsim mnozstvi handlu bitmap dochazi k tuhnuti procesu, -// je lepsi drzet bitmapy jako RAW data +// Represents one thumbnail in CIconCache::ThumbnailsCache. +// Because a larger number of bitmap handles can make the process stall, +// it is better to keep the bitmaps as RAW data. // struct CThumbnailData { - WORD Width; // rozmery thumbnailu + WORD Width; // thumbnail dimensions WORD Height; - WORD Planes; // urcuji "geometrii" dat (tyto dva parametry bychom mohli vypustit, - WORD BitsPerPixel; // ale vzniklo by riziko pri prepnuti barevne hloubky) - DWORD* Bits; // raw data device dependent bitmapy; format neznamy + WORD Planes; // define the data "geometry" (we could omit these two parameters, + WORD BitsPerPixel; // but that would introduce a risk when switching color depth) + DWORD* Bits; // raw data of a device-dependent bitmap; format unknown }; // @@ -81,47 +82,47 @@ class CIconCache : public TDirectArray // // Icons // - TIndirectArray IconsCache; // pole bitmap slouzici jako cache na ikonky - int IconsCount; // pocet zaplnenych mist v bitmapach (ikon) - CIconSizeEnum IconSize; // jakou velikost ikonek drzime? + TIndirectArray IconsCache; // array of bitmaps used as the icon cache + int IconsCount; // number of occupied slots in the icon bitmaps + CIconSizeEnum IconSize; // which icon size do we keep? // // Thumbnails // - TDirectArray ThumbnailsCache; // pole bitmap slouzici jako cache na thumbnaily + TDirectArray ThumbnailsCache; // array of bitmaps used as the thumbnail cache - CPluginDataInterfaceEncapsulation* DataIfaceForFS; // jen pro interni pouziti v SortArray() + CPluginDataInterfaceEncapsulation* DataIfaceForFS; // for internal use in SortArray() only public: - // 'forAssociations' slouzi k dimenzovani velikosti (base/delta) pole; u asociaci se predpoklada vetsi + // 'forAssociations' is used to size the array (base/delta); associations are expected to be larger CIconCache(); ~CIconCache(); - void Release(); // uvolneni celeho pole + invalidate cache - void Destroy(); // uvolneni celeho pole + cache + void Release(); // release the entire array + invalidate cache + void Destroy(); // release the entire array + cache - // seradi pole pro rychle vyhledavani; 'dataIface' je NULL krome pripadu, kdy jde - // o ptPluginFS s ikonami typu pitFromPlugin + // Sorts the array for fast lookup; 'dataIface' is NULL except when this is + // ptPluginFS with icons of type pitFromPlugin. void SortArray(int left, int right, CPluginDataInterfaceEncapsulation* dataIface); - // vraci "nalezeno ?" a index polozky nebo kam se ma vlozit (razene pole); - // 'name' musi byt zarovnane po DWORDech (pouziva se jen pokud je 'dataIface' NULL); - // 'file' jsou file-data souboru/adresare 'name' (pouziva se jen pokud neni 'dataIface' - // NULL); 'dataIface' je NULL krome pripadu, kdy jde o ptPluginFS s ikonami typu + // Returns "found?" and the item index, or the insertion position (sorted array); + // 'name' must be DWORD-aligned (used only if 'dataIface' is NULL); + // 'file' is the file-data for file/directory 'name' (used only if 'dataIface' is + // not NULL); 'dataIface' is NULL except when this is ptPluginFS with icons of type // pitFromPlugin BOOL GetIndex(const char* name, int& index, CPluginDataInterfaceEncapsulation* dataIface, const CFileData* file); - // nakopiruje si zname ikonky a thumbnaily (stara a nova cache musi byt serazene !) - // v pripade thumbnailu preda geometrii a raw data obrazku (CThumbnailData::Bits) - // do nove cache; ve stare nastavi Bits=NULL, aby pri destrukci nedoslo k dealokaci; - // 'dataIface' je NULL krome pripadu, kdy jde u stare i nove cache o ptPluginFS - // s ikonami typu pitFromPlugin + // Copies known icons and thumbnails (the old and new caches must be sorted!) + // In the thumbnail case, passes the image geometry and raw image data + // (CThumbnailData::Bits) to the new cache; sets Bits=NULL in the old cache to avoid + // deallocation during destruction; 'dataIface' is NULL except when both old and new + // caches are ptPluginFS with icons of type pitFromPlugin void GetIconsAndThumbsFrom(CIconCache* icons, CPluginDataInterfaceEncapsulation* dataIface, BOOL transferIconsAndThumbnailsAsNew = FALSE, BOOL forceReloadThumbnails = FALSE); - // musi prekreslit zakladni sadu ikon s novym pozadim + // Must redraw the base icon set with the new background. void ColorsChanged(); //////////////// @@ -129,14 +130,14 @@ class CIconCache : public TDirectArray // Icons methods // - // allokuje misto pro ikonku; vraci jeji index nebo -1 pri chybe - // promenne 'iconList' a 'iconListIndex' mohou byt NULL (pak nejsou nastavovany) - // jinak 'iconList' vraci ukazatel na CIconList, ktery nese ikonu a 'iconListIndex' - // je index v ramci tohoto imagelistu. + // Allocates space for an icon; returns its index or -1 on error. + // Variables 'iconList' and 'iconListIndex' may be NULL (then they are not set). + // Otherwise, 'iconList' returns a pointer to the CIconList carrying the icon and + // 'iconListIndex' is the index within that image list. int AllocIcon(CIconList** iconList, int* imageIconIndex); - // vrati v 'iconList' ukazatel na IconList a v 'iconListIndex' pozici ikonky - // 'iconIndex' (vracene z AllocIcon); + // Returns in 'iconList' a pointer to IconList and in 'iconListIndex' the icon position + // for 'iconIndex' (returned by AllocIcon); BOOL GetIcon(int iconIndex, CIconList** iconList, int* iconListIndex); //////////////// @@ -144,22 +145,22 @@ class CIconCache : public TDirectArray // Thumbnails methods // - // alokuje misto pro thumbnail na konci pole ThumbnailsCache - // pokud je vse OK, vraci index, ktery thumbnailu odpovida - // pri chybe vrati -1 + // Allocates space for a thumbnail at the end of the ThumbnailsCache array. + // If everything is OK, returns the index corresponding to that thumbnail. + // On error, returns -1. int AllocThumbnail(); - // vrati v 'thumbnailData' ukazatel na polozku - // 'index' (vracena z AllocThumbnail); + // Returns in 'thumbnailData' a pointer to the item + // 'index' (returned by AllocThumbnail); BOOL GetThumbnail(int index, CThumbnailData** thumbnailData); void SetIconSize(CIconSizeEnum iconSize); CIconSizeEnum GetIconSize() { return IconSize; } protected: - // jen pro interni pouziti + // For internal use only. void SortArrayInt(int left, int right); - // jen pro interni pouziti + // For internal use only. void SortArrayForFSInt(int left, int right); }; @@ -170,19 +171,19 @@ class CIconCache : public TDirectArray struct CAssociationIndexAndFlag { - DWORD Index : 31; // >= 0 index; -1 nenactene; -2 dynamicke (ikona v souboru); -3 nacitane (-1 -> -3) - DWORD Flag : 1; // jde *.ExtensionAndData otevrit ? + DWORD Index : 31; // >= 0 index; -1 not loaded; -2 dynamic (icon in file); -3 loading (-1 -> -3) + DWORD Flag : 1; // can *.ExtensionAndData be opened? }; class CAssociationData { public: - char* ExtensionAndData; // alokovano po DWORDech, konce nulovane (kvuli porovnavani); - // extension + navic pripojen string s icon-location; - char* Type; // retezec file-type; misto "" je NULL (setrime pamet) + char* ExtensionAndData; // allocated on DWORD boundaries, null-terminated at the end (for comparison); + // extension + additionally appended string with icon-location; + char* Type; // file-type string; NULL is used instead of "" (to save memory) private: - // pro kazdy rozmer ikon potrebujeme par Index+Flag + // We need an Index+Flag pair for each icon size. CAssociationIndexAndFlag IndexAndFlag[ICONSIZE_COUNT]; public: @@ -195,7 +196,7 @@ class CAssociationData } DWORD index = IndexAndFlag[iconSize].Index; if (index & 0x40000000) - index |= 0x80000000; // neumi 31-bit int na 32-bit int ... + index |= 0x80000000; // sign-extend 31-bit int to 32-bit int ... return index; } @@ -226,7 +227,7 @@ class CAssociationData // CAssociations // -#define ASSOC_ICON_NO_ASSOC 0 // pevne ikonky v cache-bitmape CAssociations +#define ASSOC_ICON_NO_ASSOC 0 // fixed icons in the CAssociations cache bitmap #define ASSOC_ICON_SOME_FILE 1 #define ASSOC_ICON_SOME_EXE 2 #define ASSOC_ICON_SOME_DIR 3 @@ -235,8 +236,8 @@ class CAssociationData struct CAssociationsIcons { public: - TIndirectArray IconsCache; // pole bitmap slouzici jako cache na ikonky - int IconsCount; // pocet zaplnenych mist v bitmapach (ikon) + TIndirectArray IconsCache; // array of bitmaps used as the icon cache + int IconsCount; // number of occupied slots in the icon bitmaps public: CAssociationsIcons() : IconsCache(10, 5) @@ -254,43 +255,43 @@ class CAssociations : public TDirectArray CAssociations(); ~CAssociations(); - void Release(); // uvolneni celeho pole + invalidate cache - void Destroy(); // uvolneni celeho pole + cache + void Release(); // release the entire array + invalidate cache + void Destroy(); // release the entire array + cache - // vsechny -3 -> -1 + // all -3 -> -1 // void SetAllReadingToUnread(); - // seradi pole pro rychle vyhledavani + // Sorts the array for fast lookup. void SortArray(int left, int right); - // vraci "nalezeno ?" a index polozky nebo kam se ma vlozit (razene pole); - // 'name' musi byt zarovnane po DWORDech ; + // Returns "found?" and the item index, or the insertion position (sorted array); + // 'name' must be DWORD-aligned; BOOL GetIndex(const char* name, int& index); - // allokuje misto pro ikonku; vraci jeji index nebo -1 pri chybe - // promenne 'iconList' a 'iconListIndex' mohou byt NULL (pak nejsou nastavovany) - // jinak 'iconList' vraci ukazatel na CIconList, ktery nese ikonu a 'iconListIndex' - // je index v ramci tohoto imagelistu. + // Allocates space for an icon; returns its index or -1 on error. + // Variables 'iconList' and 'iconListIndex' may be NULL (then they are not set). + // Otherwise, 'iconList' returns a pointer to the CIconList carrying the icon and + // 'iconListIndex' is the index within that image list. int AllocIcon(CIconList** iconList, int* imageIconIndex, CIconSizeEnum iconSize); - // vrati v 'iconList' ukazatel na IconList a v 'iconListIndex' pozici ikonky - // 'iconIndex' (vracene z AllocIcon); + // Returns in 'iconList' a pointer to IconList and in 'iconListIndex' the icon position + // for 'iconIndex' (returned by AllocIcon); BOOL GetIcon(int iconIndex, CIconList** iconList, int* iconListIndex, CIconSizeEnum iconSize); - // musi prekreslit zakladni sadu ikon s novym pozadim + // Must redraw the base icon set with the new background. void ColorsChanged(); void ReadAssociations(BOOL showWaitWnd); - // ext musi byt zarovnan po DWORDech + // ext must be DWORD-aligned BOOL IsAssociated(char* ext, BOOL& addtoIconCache, CIconSizeEnum iconSize); BOOL IsAssociatedStatic(char* ext, const char*& iconLocation, CIconSizeEnum iconSize); BOOL IsAssociated(char* ext); protected: - // pomocna metoda + // Helper method. void InsertData(const char* origin, int index, BOOL overwriteItem, char* e, char* s, CAssociationData& data, LONG& size, const char* iconLocation, const char* type); }; -extern CAssociations Associations; // zde jsou zalozeny nactene asociace +extern CAssociations Associations; // loaded associations are stored here diff --git a/src/iconlist.cpp b/src/iconlist.cpp index ddfa7c2fb..f731f574e 100644 --- a/src/iconlist.cpp +++ b/src/iconlist.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -10,13 +11,13 @@ // CIconList // -// udava pocet polozek v jedne radce; po vzoru W2K davame 4; -// asi pro vetsi rychlost provadenych operaci? +// Specifies the number of items in one row; following the W2K model, we use 4; +// probably for better performance of the operations performed. const int IL_ITEMS_IN_ROW = 4; -#define IL_TYPE_NORMAL 0 // bezna ikona, kterou lze vykreslit pres BitBlt -#define IL_TYPE_XOR 1 // ikona obsahujici oblasti, ktere je treba XORovat -#define IL_TYPE_ALPHA 2 // ikona obsahujici alfa kanal +#define IL_TYPE_NORMAL 0 // regular icon that can be drawn with BitBlt +#define IL_TYPE_XOR 1 // icon containing areas that must be XOR-ed +#define IL_TYPE_ALPHA 2 // icon containing an alpha channel HDC CIconList::HMemDC = NULL; HBITMAP CIconList::HOldBitmap = NULL; @@ -101,8 +102,8 @@ BOOL CIconList::CreateOrEnlargeTmpImage(int width, int height) { if (HTmpImage == NULL || TmpImageWidth < width || TmpImageHeight < height) { - // !!! Pozor, pri pouzivani BITMAPV4HEADER u Petra padal Salamander v ICM32.DLL, - // stary BITMAPINFOHEADER zjevne staci + // !!! Warning: when Petr used BITMAPV4HEADER, Salamander crashed in ICM32.DLL; + // the older BITMAPINFOHEADER is evidently sufficient BITMAPINFOHEADER bmhdr; memset(&bmhdr, 0, sizeof(bmhdr)); bmhdr.biSize = sizeof(bmhdr); @@ -121,7 +122,7 @@ BOOL CIconList::CreateOrEnlargeTmpImage(int width, int height) } if (HTmpImage != NULL) - HANDLES(DeleteObject(HTmpImage)); // pokud existuje stara bitmapa, zrusime ji + HANDLES(DeleteObject(HTmpImage)); // if an old bitmap exists, delete it HTmpImage = hBmp; TmpImageRaw = (DWORD*)lpBits; @@ -153,12 +154,12 @@ BOOL CIconList::Create(int imageWidth, int imageHeight, int imageCount) HANDLES(LeaveCriticalSection(&CriticalSection)); return FALSE; } - ZeroMemory(ImageFlags, sizeof(BYTE) * imageCount); // bez alfa kanalu + ZeroMemory(ImageFlags, sizeof(BYTE) * imageCount); // no alpha channel int bmpWidth = imageWidth * min(imageCount, IL_ITEMS_IN_ROW); int bmpHeight = imageHeight * ((imageCount + IL_ITEMS_IN_ROW - 1) / IL_ITEMS_IN_ROW); - // pomocne DC, abychom mohli vytvorit kompatibilni bitmapu + // helper DC so that we can create a compatible bitmap HDC hDC = HANDLES(GetDC(NULL)); if (hDC == NULL) { @@ -185,7 +186,7 @@ BOOL CIconList::Create(int imageWidth, int imageHeight, int imageCount) } MemDCLocks++; - // pokud jeste neexistuje cache/mask bitmapa nebo je mala, vytvorime ji + // If the cache/mask bitmap does not exist yet or is too small, create it if (!CreateOrEnlargeTmpImage(imageWidth, imageHeight)) { HANDLES(ReleaseDC(NULL, hDC)); @@ -194,8 +195,8 @@ BOOL CIconList::Create(int imageWidth, int imageHeight, int imageCount) return FALSE; } - // !!! Pozor, pri pouzivani BITMAPV4HEADER u Petra padal Salamander v ICM32.DLL, - // stary BITMAPINFOHEADER zjevne staci + // !!! Warning: when Petr used BITMAPV4HEADER, Salamander crashed in ICM32.DLL; + // the older BITMAPINFOHEADER is evidently sufficient BITMAPINFOHEADER bmhdr; memset(&bmhdr, 0, sizeof(bmhdr)); bmhdr.biSize = sizeof(bmhdr); @@ -239,7 +240,7 @@ BOOL CIconList::CreateFromImageList(HIMAGELIST hIL, int requiredImageSize) return FALSE; } - // vytahneme geometrii image listu + // get the image list geometry int count = ImageList_GetImageCount(hIL); if (count == 0) { @@ -265,7 +266,7 @@ BOOL CIconList::CreateFromImageList(HIMAGELIST hIL, int requiredImageSize) if (!Create(cx, cy, count)) return FALSE; - // j.r. tady by se dalo optimalizovat: misto predavani po ikonach predat pres ImageList_Draw + // j.r. This could be optimized here: instead of passing icons one by one, pass them via ImageList_Draw if (count > 20) { TRACE_E("CIconList::CreateFromImageList(): Let me know that you need so many icons, it would deserve some optimizations here. Jan."); @@ -288,20 +289,20 @@ BOOL CIconList::CreateFromImageList(HIMAGELIST hIL, int requiredImageSize) return TRUE; } -// Pokud mam pod W2K desktop 32bpp, dostavam XP ikonky s alfa kanalem neorezane, -// tedy vcetne alfa kanalu. Pokud prepnu desktop na 16bpp, je alfa kanal orezany (nulovany). -// Pokud tedy ApplyMaskToImage dostane ikonku vcetne alfa kanalu, vrati typ -// IL_TYPE_ALPHA a Salamander bude korektne zobrazovat tyto ikony i pod OS < XP +// If the desktop is running at 32 bpp under W2K, XP icons are obtained with the alpha channel intact, +// including the alpha channel itself. If the desktop is switched to 16 bpp, the alpha channel is clipped (zeroed). +// If `ApplyMaskToImage` therefore receives an icon including the alpha channel, it returns +// `IL_TYPE_ALPHA` and Salamander will display these icons correctly even on OS versions older than XP BYTE CIconList::ApplyMaskToImage(int index, BYTE forceXOR) { HANDLES(EnterCriticalSection(&CriticalSection)); - // souradnice v bodech v HImage + // coordinates in pixels in HImage int iX = ImageWidth * (index % IL_ITEMS_IN_ROW); int iY = ImageHeight * (index / IL_ITEMS_IN_ROW); - // prohledneme celou ikonku a urcime o jaky typ se jedna (NORMAL, XOR, ALPHA) + // scan the entire icon and determine which type it is (NORMAL, XOR, ALPHA) BYTE type = IL_TYPE_NORMAL; if (forceXOR) type = IL_TYPE_XOR; @@ -323,8 +324,8 @@ BYTE CIconList::ApplyMaskToImage(int index, BYTE forceXOR) if ((*maskPtr != 0) && (*ptr != 0)) { type = IL_TYPE_XOR; - // to ze je ikonka kandidat na XOR jeste neznamena, - // ze nebude ALPHA, takze nemuzeme vypadnout + // The fact that the icon is a candidate for XOR does not yet mean + // that it will not be ALPHA, so we cannot exit early } ptr++; maskPtr++; @@ -337,9 +338,9 @@ BYTE CIconList::ApplyMaskToImage(int index, BYTE forceXOR) SKIP: if (type == IL_TYPE_NORMAL) { - // pripravime si barvu pozadi ve spravnem formatu + // prepare the background color in the correct format DWORD bkClr = GetRValue(BkColor) << 16 | GetGValue(BkColor) << 8 | GetBValue(BkColor); - // pruhledne oblasti masky preneseme do alfa kanalu + // transfer the transparent mask areas into the alpha channel int row; for (row = 0; row < ImageHeight; row++) { @@ -350,13 +351,13 @@ BYTE CIconList::ApplyMaskToImage(int index, BYTE forceXOR) { if (*maskPtr != 0) { - // zcela pruhledna oblast - // alfa kanal je v nejvyssim bytu, nastavime na 00, zbytek bude barva pozadi + // fully transparent area + // the alpha channel is in the highest byte; set it to 00, the rest will be the background color *ptr = bkClr; } else { - *ptr |= 0xFF000000; // oblast nastavime jako nepruhlednou + *ptr |= 0xFF000000; // mark the area as opaque } ptr++; maskPtr++; @@ -374,7 +375,7 @@ BYTE CIconList::ApplyMaskToImage(int index, BYTE forceXOR) for (col = 0; col < ImageWidth; col++) { if (*maskPtr == 0) - *ptr |= 0xFF000000; // nepruhledna oblast + *ptr |= 0xFF000000; // opaque area ptr++; maskPtr++; @@ -392,7 +393,7 @@ CIconList::DumpToTrace(int index, BOOL dumpMask) { HANDLES(EnterCriticalSection(&CriticalSection)); - // souradnice v bodech v HImage + // coordinates in points in HImage int iX = ImageWidth * (index % IL_ITEMS_IN_ROW); int iY = ImageHeight * (index / IL_ITEMS_IN_ROW); @@ -458,19 +459,19 @@ BOOL CIconList::ReplaceIcon(int index, HICON hIcon) int iX = ImageWidth * (index % IL_ITEMS_IN_ROW); int iY = ImageHeight * (index / IL_ITEMS_IN_ROW); - // kontrola parametru + // Parameter validation if (index < 0 || index >= ImageCount) { TRACE_E("CIconList::ReplaceIcon(): Index is out of range! index=" << index); goto BAIL; } - // pokud je treba, provedeme resize ikonky - // Honza: pod W10 mi zacalo volani CopyImage padat v debug x64 verzi, pokud byl povolen LR_COPYFROMRESOURCE flag - // FIXME: provest audit, zda je tento downscale jeste potreba, kdyz SalLoadIcon() nove vola LoadIconWithScaleDown() + // Resize the icon if needed. + // Honza: On Windows 10, CopyImage() started crashing for me in the debug x64 build when the LR_COPYFROMRESOURCE flag was enabled. + // FIXME: Audit whether this downscale is still needed now that SalLoadIcon() calls LoadIconWithScaleDown(). hIcon = (HICON)CopyImage(hIconOrig, IMAGE_ICON, ImageWidth, ImageHeight, /*LR_COPYFROMRESOURCE | */ LR_COPYRETURNORG); - // vytahneme z handlu ikony jeji MASK a COLOR bitmapy + // Extract the MASK and COLOR bitmaps from the icon handle if (!GetIconInfo(hIcon, &ii)) { TRACE_E("GetIconInfo() failed!"); @@ -485,36 +486,36 @@ BOOL CIconList::ReplaceIcon(int index, HICON hIcon) goto BAIL; } - // pokud se jedna o b&w ikonu, mela by mit sudou vysku + // if this is a b&w icon, it should have an even height if (ii.hbmColor == NULL && (bm.bmHeight & 1) == 1) { TRACE_E("CIconList::ReplaceIcon() Icon has wrong MASK height"); goto BAIL; } - // ikonka by mela mit stejne rozmery, jako ma nase polozka + // the icon should have the same dimensions as our item if (bm.bmWidth != ImageWidth || (ii.hbmColor == NULL && bm.bmHeight != ImageHeight * 2) || (ii.hbmColor != NULL && bm.bmHeight != ImageHeight)) TRACE_E("CIconList::ReplaceIcon() Icon has wrong size: bmWidth=" << bm.bmWidth << " bmHeight=" << bm.bmHeight); - // potrebujeme dostatecny prostor pro masku + // enough space for the mask if (!CreateOrEnlargeTmpImage(bm.bmWidth, bm.bmHeight)) goto BAIL; - hSrcDC = HANDLES(CreateCompatibleDC(NULL)); // pomocne dc pro bitblt + hSrcDC = HANDLES(CreateCompatibleDC(NULL)); // helper DC for BitBlt hOldSrcBmp = (HBITMAP)SelectObject(hSrcDC, ii.hbmMask); // ii.hbmMask -> HTmpImage SelectObject(HMemDC, HTmpImage); BitBlt(HMemDC, 0, 0, ImageWidth, ImageHeight, hSrcDC, 0, 0, SRCCOPY); - // ii.hbmColor -> HImage (pokud je hbmColor==NULL, lezi XOR cast ve spodni polovine hbmMask + // ii.hbmColor -> HImage (if hbmColor == NULL, the XOR part is in the lower half of hbmMask) if (ii.hbmColor != NULL) SelectObject(hSrcDC, ii.hbmColor); SelectObject(HMemDC, HImage); BitBlt(HMemDC, iX, iY, ImageWidth, ImageHeight, hSrcDC, 0, (ii.hbmColor != NULL) ? 0 : ImageHeight, SRCCOPY); - GdiFlush(); // podle MSDN je treba zavolat nez zacneme pristupovat na raw data + GdiFlush(); // according to MSDN, this must be called before we start accessing raw data // TRACE_I("counter: "<= ImageCount) { TRACE_E("CIconList::GetIcon: index is out of range!"); return NULL; } - // vytvorime B&W masku + barevnou bitmapu dle obrazovky + // create a B&W mask plus a screen-format color bitmap HDC hDC = HANDLES(GetDC(NULL)); HBITMAP hMask = HANDLES(CreateBitmap(ImageWidth, ImageHeight, 1, 1, NULL)); HBITMAP hColor = HANDLES(CreateCompatibleBitmap(hDC, ImageWidth, ImageHeight)); @@ -581,7 +582,7 @@ CIconList::GetIcon(int index) BYTE type = ImageFlags[index]; - // do HTmpImage pripravime COLOR cast ikonky + // prepare the COLOR part of the icon in HTmpImage int row; for (row = 0; row < ImageHeight; row++) { @@ -593,14 +594,14 @@ CIconList::GetIcon(int index) DWORD argb = *imagePtr; BYTE alpha = (BYTE)((argb & 0xFF000000) >> 24); - if (type == IL_TYPE_ALPHA) // az na XP a novejsich systemech vracime ikony s alphou + if (type == IL_TYPE_ALPHA) // on Windows XP and later, return icons with alpha { *tmpPtr = argb; } else { - // v pruhledne oblasti je barva pozadi image listu, ale my tam - // musime dodat cernou barvu, aby fungoval XOR mechanismus kresleni + // the transparent area contains the image list background color, but we + // must put black there so that the XOR drawing mechanism works if (alpha != 0) *tmpPtr = argb; else @@ -612,7 +613,7 @@ CIconList::GetIcon(int index) } } - // preneseme HTmpImage do hColor + // copy HTmpImage into hColor SelectObject(HMemDC, HTmpImage); hDC = HANDLES(CreateCompatibleDC(NULL)); HBITMAP hOldBmp = (HBITMAP)SelectObject(hDC, hColor); @@ -620,7 +621,7 @@ CIconList::GetIcon(int index) SelectObject(hDC, hMask); - // do HTmpImage pripravime MASK cast ikonky + // Prepare the icon mask in HTmpImage for (row = 0; row < ImageHeight; row++) { DWORD* imagePtr = ImageRaw + iX + (iY + row) * BitmapWidth; @@ -638,7 +639,7 @@ CIconList::GetIcon(int index) } } - // preneseme HTmpImage do hMask + // Copy HTmpImage to hMask BitBlt(hDC, 0, 0, ImageWidth, ImageHeight, HMemDC, 0, 0, SRCCOPY); // if (Dump) @@ -647,13 +648,13 @@ CIconList::GetIcon(int index) // DumpToTrace(index, TRUE); // } - // zameteme + // clean up SelectObject(hDC, hOldBmp); HANDLES(DeleteDC(hDC)); HANDLES(LeaveCriticalSection(&CriticalSection)); - // z hColor + hMask vytvorime ikonku + // create an icon from hColor + hMask ICONINFO ii; ii.fIcon = TRUE; ii.xHotspot = 0; @@ -661,7 +662,7 @@ CIconList::GetIcon(int index) ii.hbmColor = hColor; ii.hbmMask = hMask; HICON hIcon; - hIcon = CreateIconIndirect(&ii); // nesmi byt v handles, vyvazi ikonku ven ze Salamandera + hIcon = CreateIconIndirect(&ii); // must not be in handles; transfers the icon out of Salamander HANDLES(DeleteObject(hColor)); HANDLES(DeleteObject(hMask)); @@ -671,14 +672,14 @@ CIconList::GetIcon(int index) BOOL CIconList::Draw(int index, HDC hDC, int x, int y, COLORREF blendClr, DWORD flags) { - // kontrola parametru + // parameter validation if (index < 0 || index >= ImageCount) { TRACE_E("CIconList::Draw() Index is out of range! index=" << index << " ImageCount=" << ImageCount); return FALSE; } - if (flags & IL_DRAW_MASK) // maska se pouziva pri drag&dropu, napriklad u shared adesaru, viz StateImageList_Draw() + if (flags & IL_DRAW_MASK) // The mask is used during drag and drop, for example for shared folders; see StateImageList_Draw(). return DrawMask(hDC, x, y, index, RGB(0, 0, 0), RGB(255, 255, 255)); if (flags & IL_DRAW_BLEND) return AlphaBlend(hDC, x, y, index, BkColor, blendClr); @@ -712,21 +713,21 @@ BOOL CIconList::DrawMask(HDC hDC, int x, int y, int index, COLORREF fgColor, COL { HANDLES(EnterCriticalSection(&CriticalSection)); - // souradnice v bodech v HImage + // coordinates in pixels in HImage int iX = ImageWidth * (index % IL_ITEMS_IN_ROW); int iY = ImageHeight * (index / IL_ITEMS_IN_ROW); //DumpToTrace(index); - // sosneme data z obrazovky do HTmpImage - // nase DrawMask pouze nastavuje cerne body v miste masky, abychom mohli snadno mergovat s overlayem - // pri volani z StateImageList_Draw(); pokud bude casem treba zobrazovat dalsi overlay, bude to chtit - // udelat v StateImageList_Draw() merger na zaklade boolovskych bitblt operaci a tato metoda by pak - // mohla nastavovat take fgColor; odpadla by podminka *** dole + // Copy the screen data into HTmpImage + // Our `DrawMask` only sets black pixels at the mask locations so that it can be merged easily with the overlay + // when called from `StateImageList_Draw()`; if support for another overlay is ever needed, it will be necessary + // to implement the merge in `StateImageList_Draw()` using boolean `BitBlt` operations, and this method could then + // also set `fgColor`; the `***` condition below would no longer be needed SelectObject(HMemDC, HTmpImage); BitBlt(HMemDC, 0, 0, ImageWidth, ImageHeight, hDC, x, y, SRCCOPY); - // budeme kreslit do HTmpImage + // draw into HTmpImage int row; for (row = 0; row < ImageHeight; row++) { @@ -739,7 +740,7 @@ BOOL CIconList::DrawMask(HDC hDC, int x, int y, int index, COLORREF fgColor, COL BYTE alpha = (BYTE)((argb & 0xFF000000) >> 24); DWORD clr = (alpha == 0) ? bkColor : fgColor; - if (alpha != 0) // *** viz komentar nahore + if (alpha != 0) // *** see comment above *tmpPtr = clr; imagePtr++; @@ -747,7 +748,7 @@ BOOL CIconList::DrawMask(HDC hDC, int x, int y, int index, COLORREF fgColor, COL } } - // vykreslime HTmpImage do obrazovky + // draw HTmpImage to the screen // SelectObject(HMemDC, HTmpImage); BitBlt(hDC, x, y, ImageWidth, ImageHeight, HMemDC, 0, 0, SRCCOPY); @@ -759,11 +760,11 @@ BOOL CIconList::DrawXOR(HDC hDC, int x, int y, int index, COLORREF bkColor) { HANDLES(EnterCriticalSection(&CriticalSection)); - // souradnice v bodech v HImage + // coordinates in pixels in HImage int iX = ImageWidth * (index % IL_ITEMS_IN_ROW); int iY = ImageHeight * (index / IL_ITEMS_IN_ROW); - // budeme kreslit do HTmpImage + // draw into HTmpImage BYTE bkR = GetRValue(bkColor); BYTE bkG = GetGValue(bkColor); BYTE bkB = GetBValue(bkColor); @@ -789,7 +790,7 @@ BOOL CIconList::DrawXOR(HDC hDC, int x, int y, int index, COLORREF bkColor) } } - // vykreslime HTmpImage do obrazovky + // draw HTmpImage to the screen SelectObject(HMemDC, HTmpImage); BitBlt(hDC, x, y, ImageWidth, ImageHeight, HMemDC, 0, 0, SRCCOPY); @@ -801,11 +802,11 @@ BOOL CIconList::DrawALPHA(HDC hDC, int x, int y, int index, COLORREF bkColor) { HANDLES(EnterCriticalSection(&CriticalSection)); - // souradnice v bodech v HImage + // coordinates in pixels in HImage int iX = ImageWidth * (index % IL_ITEMS_IN_ROW); int iY = ImageHeight * (index / IL_ITEMS_IN_ROW); - // v prvni fazi preneseme data do HMask + // in the first phase, transfer the data into HMask SelectObject(HMemDC, HTmpImage); BYTE bkR = GetRValue(bkColor); @@ -844,7 +845,7 @@ BOOL CIconList::DrawALPHA(HDC hDC, int x, int y, int index, COLORREF bkColor) } } - // vykreslime HTmpImage do obrazovky + // draw HTmpImage to the screen BitBlt(hDC, x, y, ImageWidth, ImageHeight, HMemDC, 0, 0, SRCCOPY); HANDLES(LeaveCriticalSection(&CriticalSection)); @@ -856,14 +857,14 @@ BOOL CIconList::DrawALPHALeaveBackground(HDC hDC, int x, int y, int index) { HANDLES(EnterCriticalSection(&CriticalSection)); - // souradnice v bodech v HImage + // coordinates in pixels in HImage int iX = ImageWidth * (index % IL_ITEMS_IN_ROW); int iY = ImageHeight * (index / IL_ITEMS_IN_ROW); - // v prvni fazi preneseme z ciloveho DC data do HMask + // in the first phase, transfer data from the target DC into HMask SelectObject(HMemDC, HTmpImage); BitBlt(HMemDC, 0, 0, ImageWidth, ImageHeight, hDC, x, y, SRCCOPY); - GdiFlush(); // podle MSDN je treba zavolat nez zacneme pristupovat na raw data + GdiFlush(); // according to MSDN, this must be called before we start accessing raw data /* BYTE bkR = GetRValue(bkColor); @@ -905,7 +906,7 @@ BOOL CIconList::DrawALPHALeaveBackground(HDC hDC, int x, int y, int index) } } - // vykreslime HTmpImage do obrazovky + // draw HTmpImage to the screen BitBlt(hDC, x, y, ImageWidth, ImageHeight, HMemDC, 0, 0, SRCCOPY); HANDLES(LeaveCriticalSection(&CriticalSection)); @@ -917,14 +918,14 @@ BOOL CIconList::DrawAsAlphaLeaveBackground(HDC hDC, int x, int y, int index, COL { HANDLES(EnterCriticalSection(&CriticalSection)); - // souradnice v bodech v HImage + // coordinates in pixels in HImage int iX = ImageWidth * (index % IL_ITEMS_IN_ROW); int iY = ImageHeight * (index / IL_ITEMS_IN_ROW); - // v prvni fazi preneseme z ciloveho DC data do HMask + // in the first phase, transfer data from the target DC into HMask SelectObject(HMemDC, HTmpImage); BitBlt(HMemDC, 0, 0, ImageWidth, ImageHeight, hDC, x, y, SRCCOPY); - GdiFlush(); // podle MSDN je treba zavolat nez zacneme pristupovat na raw data + GdiFlush(); // according to MSDN, this must be called before we start accessing raw data BYTE fgR = GetRValue(fgColor); BYTE fgG = GetGValue(fgColor); @@ -939,7 +940,7 @@ BOOL CIconList::DrawAsAlphaLeaveBackground(HDC hDC, int x, int y, int index, COL for (col = 0; col < ImageWidth; col++) { DWORD argb = *imagePtr; - BYTE alpha = 255 - (BYTE)(argb & 0x000000FF); // vsechny kanaly nesou stejnou hodnotu, kterou mame povazovat za alpha kanal + BYTE alpha = 255 - (BYTE)(argb & 0x000000FF); // all channels carry the same value, which should be treated as the alpha channel if (alpha != 0) { BYTE bkR = (BYTE)((*tmpPtr & 0x00FF0000) >> 16); @@ -956,7 +957,7 @@ BOOL CIconList::DrawAsAlphaLeaveBackground(HDC hDC, int x, int y, int index, COL } } - // vykreslime HTmpImage do obrazovky + // draw HTmpImage to the screen BitBlt(hDC, x, y, ImageWidth, ImageHeight, HMemDC, 0, 0, SRCCOPY); HANDLES(LeaveCriticalSection(&CriticalSection)); @@ -968,18 +969,18 @@ BOOL CIconList::AlphaBlend(HDC hDC, int x, int y, int index, COLORREF bkColor, C { HANDLES(EnterCriticalSection(&CriticalSection)); - // souradnice v bodech v HImage + // coordinates in pixels in HImage int iX = ImageWidth * (index % IL_ITEMS_IN_ROW); int iY = ImageHeight * (index / IL_ITEMS_IN_ROW); - // jde o variantu, kde je treba XORovat? + // Is this the variant that needs XORing? BOOL xorType = ImageFlags[index] == IL_TYPE_XOR; - // v prvni pripravime raw data pro HTmpImage + // in the first phase, prepare raw data for HTmpImage int bitsPerPixel = GetCurrentBPP(hDC); if (bitsPerPixel <= 8) { - // 256 barev nebo mene: misto blendeni prekryvame sachovnici + // 256 colors or less: overlay a checkerboard instead of blending DWORD bkClrOpaque = GetRValue(bkColor) << 16 | GetGValue(bkColor) << 8 | GetBValue(bkColor); DWORD bkClr; if (fgColor != CLR_NONE) @@ -999,7 +1000,7 @@ BOOL CIconList::AlphaBlend(HDC hDC, int x, int y, int index, COLORREF bkColor, C if (xorType && alpha == 0) { - // XOR && pruhledna oblast + // XOR && transparent area BYTE bkR = GetRValue(bkColor); BYTE bkG = GetGValue(bkColor); BYTE bkB = GetBValue(bkColor); @@ -1010,7 +1011,7 @@ BOOL CIconList::AlphaBlend(HDC hDC, int x, int y, int index, COLORREF bkColor, C { if (alpha == 0) { - // pruhledna oblast + // transparent area argb = bkClrOpaque; } else @@ -1032,7 +1033,7 @@ BOOL CIconList::AlphaBlend(HDC hDC, int x, int y, int index, COLORREF bkColor, C } else { - // vice nez 256 barev: blednime pomoci alfa kanalu + // more than 256 colors: fade using the alpha channel BYTE bkR = GetRValue(bkColor); BYTE bkG = GetGValue(bkColor); BYTE bkB = GetBValue(bkColor); @@ -1051,7 +1052,7 @@ BOOL CIconList::AlphaBlend(HDC hDC, int x, int y, int index, COLORREF bkColor, C if (xorType && alpha == 0) { - // XOR && pruhledna oblast + // XOR && transparent area *tmpPtr = (DWORD)bkR << 16 | (DWORD)bkG << 8 | (DWORD)bkB; *tmpPtr ^= (argb & 0x00FFFFFF); } @@ -1086,7 +1087,7 @@ BOOL CIconList::AlphaBlend(HDC hDC, int x, int y, int index, COLORREF bkColor, C } } - // vykreslime HTmpImage do obrazovky + // draw HTmpImage to the screen SelectObject(HMemDC, HTmpImage); BitBlt(hDC, x, y, ImageWidth, ImageHeight, HMemDC, 0, 0, SRCCOPY); @@ -1112,7 +1113,7 @@ BOOL CIconList::SetBkColor(COLORREF bkColor) int index; for (index = 0; index < ImageCount; index++) { - if (ImageFlags[index] != IL_TYPE_NORMAL) // pouze u normalnich ikon ma smysl nastavovat barvu pozadi + if (ImageFlags[index] != IL_TYPE_NORMAL) // setting the background color only makes sense for normal icons continue; int iX = ImageWidth * (index % IL_ITEMS_IN_ROW); @@ -1145,7 +1146,7 @@ CIconList::GetBkColor() BOOL CIconList::Copy(int dstIndex, CIconList* srcIL, int srcIndex) { - // kontrola parametru + // Check parameters if (dstIndex < 0 || dstIndex >= ImageCount) { TRACE_E("CIconList::Copy: dstIndex is out of range!"); @@ -1167,9 +1168,9 @@ BOOL CIconList::Copy(int dstIndex, CIconList* srcIL, int srcIndex) return FALSE; } - // verze kopirovani pomoci primeho pristupu k datum, vyhodou by mela byt - // vyssi rychlost a naprosto identicka kopie (fce BitBlt by mohla zahazovat - // alpha kanal) + // copy variant using direct access to the data; the advantage should be + // higher speed and a completely identical copy (the BitBlt function could drop + // the alpha channel) HANDLES(EnterCriticalSection(&CriticalSection)); int srcX = ImageWidth * (srcIndex % IL_ITEMS_IN_ROW); int srcY = ImageHeight * (srcIndex / IL_ITEMS_IN_ROW); @@ -1192,7 +1193,7 @@ BOOL CIconList::Copy(int dstIndex, CIconList* srcIL, int srcIndex) ImageFlags[dstIndex] = srcIL->ImageFlags[srcIndex]; HANDLES(LeaveCriticalSection(&CriticalSection)); - // verze kopirovani pomoci BitBlt + // BitBlt-based copy variant // HDC hSrcMemDC = HANDLES(CreateCompatibleDC(NULL)); // if (hSrcMemDC == NULL) // { @@ -1223,11 +1224,11 @@ BOOL CIconList::CreateFromBitmap(HBITMAP hBitmap, int imageCount, COLORREF trans int cx = bmp.bmWidth / imageCount; int cy = bmp.bmHeight; - // naalokujeme bitmapu + // allocate the bitmap if (!Create(cx, cy, imageCount)) return FALSE; - // po radcich do ni pridame prouzky ze zdrojove bitmapy + // add strips from the source bitmap row by row int index = 0; while (index < imageCount) { @@ -1303,9 +1304,9 @@ BOOL CIconList::CopyFromBitmapIternal(int dstIndex, HBITMAP hSrcBitmap, int srcI BitBlt(HMemDC, dstX, dstY, ImageWidth * imageCount, ImageHeight, hSrcMemDC, srcX, srcY, SRCCOPY); ImageFlags[dstIndex] = IL_TYPE_NORMAL; - GdiFlush(); // podle MSDN je treba zavolat nez zacneme pristupovat na raw data + GdiFlush(); // according to MSDN, this must be called before we start accessing raw data - // podle transparentni barvy nastavime alpha kanal + // set the alpha channel according to the transparent color int row; for (row = dstY; row < dstY + ImageHeight; row++) { @@ -1400,7 +1401,7 @@ BOOL CIconList::ConvertToGrayscale(BOOL forceAlphaForBW) BYTE brightness = GetGrayscaleFromRGB(r, g, b); if (forceAlphaForBW) { - // pokud jde vystup do BW bitmapy, nastavime prah mezi bilou a cernou (odladeno na Vista ikonkach v user menu) + // if the output goes to a B&W bitmap, set the threshold between white and black (tuned on Vista icons in the user menu) if (alpha < 200) alpha = 0; if (brightness > 240) @@ -1430,49 +1431,49 @@ CIconList::GetImageList() return hIL; /* - // vytahnu rozmery bitmapy - HDC hDC = HANDLES(GetDC(NULL)); - BITMAPINFO bi; - memset(&bi, 0, sizeof(bi)); - bi.bmiHeader.biSize = sizeof(bi.bmiHeader); - bi.bmiHeader.biBitCount = 0; // nechceme paletu + // get the bitmap dimensions + HDC hDC = HANDLES(GetDC(NULL)); + BITMAPINFO bi; + memset(&bi, 0, sizeof(bi)); + bi.bmiHeader.biSize = sizeof(bi.bmiHeader); + bi.bmiHeader.biBitCount = 0; // palette not needed - if (!GetDIBits(hDC, - hSrc, - 0, 0, - NULL, - &bi, - DIB_RGB_COLORS)) - { - TRACE_E("GetDIBits failed"); - if (hDC != NULL) HANDLES(ReleaseDC(NULL, hDC)); - return NULL; - } + if (!GetDIBits(hDC, + hSrc, + 0, 0, + NULL, + &bi, + DIB_RGB_COLORS)) + { + TRACE_E("GetDIBits failed"); + if (hDC != NULL) HANDLES(ReleaseDC(NULL, hDC)); + return NULL; + } - if (bi.bmiHeader.biSizeImage == 0) - { - TRACE_E("bi.bmiHeader.biSizeImage == 0"); - if (hDC != NULL) HANDLES(ReleaseDC(NULL, hDC)); - return NULL; - } - if (hDC != NULL) HANDLES(ReleaseDC(NULL, hDC)); + if (bi.bmiHeader.biSizeImage == 0) + { + TRACE_E("bi.bmiHeader.biSizeImage == 0"); + if (hDC != NULL) HANDLES(ReleaseDC(NULL, hDC)); + return NULL; + } + if (hDC != NULL) HANDLES(ReleaseDC(NULL, hDC)); - HIMAGELIST hIL = ImageList_Create(16, 16, GetImageListColorFlags() | ILC_MASK, 0, 1); - if (hIL != NULL) - { - // funkce ImageList_AddMasked nici pruhlednou barvu v hSrc, proto - // pridame ikonky postupne a pomalu - int count = bi.bmiHeader.biWidth / 16; - int i; - for (i = 0; i < count; i++) - { - HICON hIcon = GetIconFromDIB(hSrc, i); - ImageList_AddIcon(hIL, hIcon); - HANDLES(DestroyIcon(hIcon)); - } - } - return hIL; -*/ + HIMAGELIST hIL = ImageList_Create(16, 16, GetImageListColorFlags() | ILC_MASK, 0, 1); + if (hIL != NULL) + { + // the ImageList_AddMasked function destroys the transparent color in hSrc, so + // add the icons one by one, slowly + int count = bi.bmiHeader.biWidth / 16; + int i; + for (i = 0; i < count; i++) + { + HICON hIcon = GetIconFromDIB(hSrc, i); + ImageList_AddIcon(hIL, hIcon); + HANDLES(DestroyIcon(hIcon)); + } + } + return hIL; + */ } //**************************************************************************** @@ -1750,7 +1751,7 @@ HBITMAP LoadRawPNGBitmap(const void* rawPNG, DWORD rawPNGSize, DWORD flags) if (result >= 0) { HBITMAP hBitmap = LoadPNGBitmapCreateDIB(&png, buff, buffSize, flags); - png_free_data(&png); // release palette, etc allocated in png_get_data + png_free_data(&png); // release the palette, etc. allocated by png_get_data if (buff[buffSize] != 0xfe) { TRACE_E("Memory corrupted!!!"); @@ -1851,7 +1852,7 @@ BOOL CIconList::CreateFromRawPNG(const void* rawPNG, DWORD rawPNGSize, int image int row; for (row = 0; row < ImageHeight; row++) { - // souradnice v bodech v HImage + // coordinates in pixels in HImage int iX = ImageWidth * (index % IL_ITEMS_IN_ROW); int iY = ImageHeight * (index / IL_ITEMS_IN_ROW); @@ -1886,7 +1887,7 @@ BOOL CIconList::CreateFromRawPNG(const void* rawPNG, DWORD rawPNGSize, int image int row; for (row = 0; row < ImageHeight; row++) { - // souradnice v bodech v HImage + // coordinates in pixels in HImage int iX = ImageWidth * (index % IL_ITEMS_IN_ROW); int iY = ImageHeight * (index / IL_ITEMS_IN_ROW); @@ -1922,7 +1923,7 @@ BOOL CIconList::CreateFromRawPNG(const void* rawPNG, DWORD rawPNGSize, int image int row; for (row = 0; row < ImageHeight; row++) { - // souradnice v bodech v HImage + // coordinates in pixels in HImage int iX = ImageWidth * (index % IL_ITEMS_IN_ROW); int iY = ImageHeight * (index / IL_ITEMS_IN_ROW); @@ -1959,7 +1960,7 @@ BOOL CIconList::CreateFromRawPNG(const void* rawPNG, DWORD rawPNGSize, int image int row; for (row = 0; row < ImageHeight; row++) { - // souradnice v bodech v HImage + // coordinates in pixels in HImage int iX = ImageWidth * (index % IL_ITEMS_IN_ROW); int iY = ImageHeight * (index / IL_ITEMS_IN_ROW); @@ -1998,7 +1999,7 @@ BOOL CIconList::CreateFromRawPNG(const void* rawPNG, DWORD rawPNGSize, int image int row; for (row = 0; row < ImageHeight; row++) { - // souradnice v bodech v HImage + // coordinates in pixels in HImage int iX = ImageWidth * (index % IL_ITEMS_IN_ROW); int iY = ImageHeight * (index / IL_ITEMS_IN_ROW); @@ -2062,7 +2063,7 @@ struct CPNGBitmapWriteCallbackData { BYTE* RawPNGIterator; DWORD FreeSpace; - // navratove hodnoty + // return values BOOL NotEnoughSpace; DWORD Size; }; @@ -2090,7 +2091,7 @@ unsigned PNGBitmapWriteCallback(void* input, size_t size, size_t numel, void* us BOOL CIconList::SaveToPNG(BYTE** rawPNG, DWORD* rawPNGSize) { - // pripravime ikony do jednoho dlouheho radku + // prepare the icons in one long row DWORD* buff = (DWORD*)malloc(ImageWidth * ImageCount * ImageHeight * 4); int index; for (index = 0; index < ImageCount; index++) @@ -2098,7 +2099,7 @@ BOOL CIconList::SaveToPNG(BYTE** rawPNG, DWORD* rawPNGSize) int row; for (row = 0; row < ImageHeight; row++) { - // souradnice v bodech ve zdroji + // coordinates in pixels in the source int iX = ImageWidth * (index % IL_ITEMS_IN_ROW); int iY = ImageHeight * (index / IL_ITEMS_IN_ROW); BYTE* srcPtr = (BYTE*)ImageRaw + iX * 4 + (iY + row) * BitmapWidth * 4; @@ -2119,7 +2120,7 @@ BOOL CIconList::SaveToPNG(BYTE** rawPNG, DWORD* rawPNGSize) } CPNGBitmapWriteCallbackData callbackData; - callbackData.FreeSpace = ImageWidth * ImageCount * ImageHeight * 4 * 2; // radeji pripravim dvojnasobek pameti, tam se PNG MUSI vejit + callbackData.FreeSpace = ImageWidth * ImageCount * ImageHeight * 4 * 2; // allocate double the memory to be safe; the PNG must fit there callbackData.Size = 0; BYTE* output = (BYTE*)malloc(callbackData.FreeSpace); callbackData.RawPNGIterator = output; diff --git a/src/iconlist.h b/src/iconlist.h index 26e170e87..04e14f112 100644 --- a/src/iconlist.h +++ b/src/iconlist.h @@ -1,24 +1,28 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once /************************************************************************************ -Co lze vytahnout z HICON, ktere nam dodava OS? +What can we extract from the HICON handles provided by the OS? - Pomoci GetIconInfo() nam OS vrati kopie bitmap MASK a COLOR. Ty lze dale - zkoumat volanim GetObject(), pomoci ktere vytahneme geometrii a bervne usporadani. - Jedna se o kopie bitmap, nikoliv o bitmapy originalni, drzene uvnitr OS. MASK je - vzdy 1bitova bitmapa. COLOR je bitmapa kompatibilni s DC obrazovky. Neexistuje tedy - zpusob, jak z techto dat ziskat informace o realne barevne hloubce bitmapy COLOR. + Using GetIconInfo(), the OS returns copies of the MASK and COLOR bitmaps. We can + inspect them further with GetObject(), which lets us obtain their geometry and + color layout. These are bitmap copies, not the original bitmaps held inside the OS. + MASK is always a 1-bit bitmap. COLOR is a bitmap compatible with the screen DC. + There is therefore no way to determine the real color depth of the COLOR bitmap + from this data. - Specialni pripad jsou ikony ciste cernobile. Ty jsou predany cele v MASK, ktera - je pak 2x vyssi. COLOR je pak NULL. Horni polovina MASK bitmapy AND cast a spodni - polovina je XOR cast. Tento pripad lze snadno detekovat pomoci testu COLOR == NULL. + A special case is fully monochrome icons. They are passed entirely in MASK, which + is then twice as tall. COLOR is NULL in that case. The upper half of the MASK + bitmap is the AND part and the lower half is the XOR part. This case can be + detected easily by testing COLOR == NULL. - Od Windows XP existuje dalsi specialni pripad: ikony obsahujici ALFA kanal. Jedna - s o DIBy s barevnou hloubkou 32bitu, kde je kazdy bod slozen z ARGB slozek. + Since Windows XP there has been another special case: icons containing an alpha + channel. These are DIBs with 32-bit color depth, where each pixel consists of + ARGB components. @@ -28,52 +32,52 @@ Co lze vytahnout z HICON, ktere nam dodava OS? ************************************************************************************/ // -// Existuje potencialni prostor pro optimalizaci nasi implementace ImageListu. -// DIB bychom mohli drzet ve stejnem formatu, ve kterem jede obrazovka. BitBlt -// je potom udajne rychlejsi (neoveroval jsem) podle MSDN: +// There is potential room to optimize our ImageList implementation. +// We could keep the DIB in the same format as the display. According to MSDN, +// BitBlt is then reportedly faster, although I did not verify that: // http://support.microsoft.com/default.aspx?scid=kb;EN-US;230492 // (HOWTO: Retrieving an Optimal DIB Format for a Device) // -// Proti teto optimalizaci mluvi nekolik faktoru: -// - museli bychom v kodu podporit ruzne formaty dat (15, 16, 24, 32 bitu) -// - protoze vykreslujeme soucasne maximalne desitky ikonek, neni pro -// nas rychlost kresleni kriticka; nameril jsem tyto rychlosti kresleni: -// (100 000 krat se do obrazovky kreslil pres BitBlt DIB 16x16, 32bpp) -// rozliseni obrazovky celkova doba (W2K, Matrox G450) -// 32 bpp 0.40 s -// 24 bpp 0.80 s -// 16 bpp 0.65 s -// 8 bpp 1.16 s -// - Nejak bychom stejne museli drzet ikonky s ALFA kanalem, ktere jsou 32 bpp +// Several factors argue against that optimization: +// - we would have to support different data formats in the code (15, 16, 24, 32 bits) +// - because we draw at most a few dozen icons at once, drawing speed is not critical +// for us; I measured the following drawing speeds: +// (a 16x16, 32bpp DIB was drawn to the screen via BitBlt 100,000 times) +// screen resolution total time (W2K, Matrox G450) +// 32 bpp 0.40 s +// 24 bpp 0.80 s +// 16 bpp 0.65 s +// 8 bpp 1.16 s +// - we would still somehow need to keep icons with an ALPHA channel, which are 32 bpp // // -// Proc potrebujeme vlastni obdobu ImageList: +// Why do we need our own ImageList equivalent: // -// ImageList z CommonControls ma jeden zasadni problem: pokud jej pozadame, -// aby drzel DeviceDependentBitmapy, neumi zobrazit blendenou polozku. Misto -// toho ji sjede paternem. +// The CommonControls ImageList has one major problem: if we ask it to keep +// DeviceDependentBitmaps, it cannot display a blended item. Instead, it fills +// it with a pattern. // -// Pokud je drzena bitmapa DIB, blendeni slape skvele, ale vykresleni -// klasicke polozky je radove pomalejsi (konverze DIB->obrazovka). +// If a DIB bitmap is stored, blending works great, but drawing a normal item +// is orders of magnitude slower (DIB -> screen conversion). // -// Dale existuje riziko, ze v nekterych implementacich volani ImageList_SetBkColor -// fyzicky nezmeni drzenou bitmapu na zaklade masky, ale pouze nastavi vnitrni -// promennou. Samozrejme je pak kresleni pomalejsi, protoze je treba provadet -// maskovani. Testoval jsem pod W2K a funkce chodi spravne. +// There is also a risk that in some implementations, calling ImageList_SetBkColor +// does not physically modify the stored bitmap using the mask, but only updates an +// internal variable. Drawing is then naturally slower because masking has to be +// performed. I tested this under W2K and the function behaves correctly there. // -// Jedina moznost by byla v zachovani ImageListu pro drzeni dat a pouze blend -// preprogramovat. Problem ale nastava ve funkci ImageList_GetImageInfo, ktera -// umoznuje pristup k vnitrnim bitmapam Image/Mask. ImageList je ma neustale -// vybrane v MemDC, takze podle MSDN (Q131279: SelectObject() Fails After -// ImageList_GetImageInfo()) je jedinou moznosti napred volat CopyImage a teprve -// potom nad bitmapou pracovat. To by vedlo ne neskutecne pomale kresleni -// blendenych polozek. +// The only option would be to keep ImageList for data storage and reimplement only +// blending. The problem appears in ImageList_GetImageInfo, which provides access +// to the internal Image/Mask bitmaps. ImageList keeps them permanently selected in +// MemDC, so according to MSDN (Q131279: SelectObject() Fails After +// ImageList_GetImageInfo()) the only option is to call CopyImage first and only +// then work with the bitmap. That would lead to unbearably slow drawing of blended +// items. // -// Dalsim oriskem jsou pro ImageList ikony invert body. Ikona se sklada ze -// dvou bitmap: MASKA a COLORS. Maska se ANDuje do cile a pres ni se XORuji barvy. -// Diky XORovani tak muzou ikonky invertovat nektere sve casti. Vyuzivaji toho -// predevsim kurzory, viz WINDOWS\Cursors. +// Another difficulty for ImageList is icons with inverted pixels. An icon consists +// of two bitmaps: MASK and COLORS. The mask is AND-ed into the target and then the +// colors are XOR-ed through it. Thanks to XOR, icons can invert some of their +// parts. This is used mainly by cursors, see WINDOWS\\Cursors. // //****************************************************************************** @@ -81,79 +85,79 @@ Co lze vytahnout z HICON, ktere nam dodava OS? // CIconList // // -// Po vzoru W2K drzime polozky v bitmape siroke 4 polozky. Pravdepodobne -// budou operace nad takto orientovanou bitmapu rychlejsi. +// Following the W2K model, we keep items in a bitmap four items wide. Operations +// on a bitmap arranged like this will probably be faster. -#define IL_DRAW_BLEND 0x00000001 // z 50% bude pouzita barva blendClr -#define IL_DRAW_TRANSPARENT 0x00000002 // pri kresleni se zachova puvodni pozadi (pokud neni specifikovano, pouzije vyplni se pozadi definovanou barvou) -#define IL_DRAW_ASALPHA 0x00000004 // pouzije (invertovanou) barvu v BLUE kanalu jako alpha, pomoci ktere k pozadi primicha specifikovanou barvu popredi; zatim slouzi pro throbber -#define IL_DRAW_MASK 0x00000010 // vykreslit masku +#define IL_DRAW_BLEND 0x00000001 // blendClr will be used at 50% +#define IL_DRAW_TRANSPARENT 0x00000002 // drawing preserves the original background (unless specified otherwise, the background is filled with the defined color) +#define IL_DRAW_ASALPHA 0x00000004 // uses the (inverted) color in the BLUE channel as alpha, with which it mixes the specified foreground color into the background; currently used for the throbber +#define IL_DRAW_MASK 0x00000010 // draw the mask class CIconList : public CGUIIconListAbstract { private: - int ImageWidth; // rozmery jednoho obrazku + int ImageWidth; // dimensions of one image int ImageHeight; - int ImageCount; // pocet obrazku v bitmape - int BitmapWidth; // rozmery drzenych bitmap + int ImageCount; // number of images in the bitmap + int BitmapWidth; // dimensions of the stored bitmaps int BitmapHeight; - // obrazky jsou usporadany zleva doprava a shora dolu - HBITMAP HImage; // DIB, jeho raw data jsou v promenne ImageRaw - DWORD* ImageRaw; // ARGB hodnoty; Alfa: 0x00=pruhledna, 0xFF=nepruhledna, ostatni=castecna_pruhlednost(puze u IL_TYPE_ALPHA) - BYTE* ImageFlags; // pole o poctu prvku 'imageCount'; (IL_TYPE_xxx) + // images are laid out from left to right and top to bottom + HBITMAP HImage; // DIB; its raw data is in the ImageRaw variable + DWORD* ImageRaw; // ARGB values; Alpha: 0x00 = transparent, 0xFF = opaque, others = partial transparency (only for IL_TYPE_ALPHA) + BYTE* ImageFlags; // array with 'imageCount' elements; (IL_TYPE_xxx) - COLORREF BkColor; // aktualni barva pozadi (body kde je Alfa==0x00) + COLORREF BkColor; // current background color (pixels where Alpha == 0x00) - // sdilene promenne pres vsechny imagelisty -- setrime pameti - static HDC HMemDC; // sdilene mem dc - static HBITMAP HOldBitmap; // puvodni bitmapa - static HBITMAP HTmpImage; // cache pro paint + docasne uloziste masky - static DWORD* TmpImageRaw; // raw data od HTmpImage - static int TmpImageWidth; // rozmery HTmpImage v bodech - static int TmpImageHeight; // rozmery HTmpImage v bodech - static int MemDCLocks; // pro destrukci mem dc - static CRITICAL_SECTION CriticalSection; // synchronizace pristupu - static int CriticalSectionLocks; // pro konstrukci/destrukci CriticalSection + // shared variables across all image lists -- saves memory + static HDC HMemDC; // shared memory DC + static HBITMAP HOldBitmap; // original bitmap + static HBITMAP HTmpImage; // paint cache + temporary mask storage + static DWORD* TmpImageRaw; // raw data from HTmpImage + static int TmpImageWidth; // dimensions of HTmpImage in pixels + static int TmpImageHeight; // dimensions of HTmpImage in pixels + static int MemDCLocks; // for destroying the memory DC + static CRITICAL_SECTION CriticalSection; // access synchronization + static int CriticalSectionLocks; // for constructing/destroying CriticalSection public: - // BOOL Dump; // pokud je TRUE, dumpuji se raw data do TRACE + // BOOL Dump; // if TRUE, raw data is dumped to TRACE public: CIconList(); ~CIconList(); virtual BOOL WINAPI Create(int imageWidth, int imageHeight, int imageCount); - virtual BOOL WINAPI CreateFromImageList(HIMAGELIST hIL, int requiredImageSize = -1); // pokud je 'requiredImageSize' -1, pouzije se geometrie z hIL - virtual BOOL WINAPI CreateFromPNG(HINSTANCE hInstance, LPCTSTR lpBitmapName, int imageWidth); // nacte z resourcu PNG, musi jit o dlouhy prouzek jeden radek vysoky + virtual BOOL WINAPI CreateFromImageList(HIMAGELIST hIL, int requiredImageSize = -1); // if 'requiredImageSize' is -1, the geometry from hIL is used + virtual BOOL WINAPI CreateFromPNG(HINSTANCE hInstance, LPCTSTR lpBitmapName, int imageWidth); // loads PNG from resources; it must be a long strip one row high virtual BOOL WINAPI CreateFromRawPNG(const void* rawPNG, DWORD rawPNGSize, int imageWidth); - virtual BOOL WINAPI CreateFromBitmap(HBITMAP hBitmap, int imageCount, COLORREF transparentClr); // nasosne bitmapu (maximalne 256 barev), musi jit o dlouhy prouzek jeden radek vysoky + virtual BOOL WINAPI CreateFromBitmap(HBITMAP hBitmap, int imageCount, COLORREF transparentClr); // accepts a bitmap (up to 256 colors); it must be a long strip one row high virtual BOOL WINAPI CreateAsCopy(const CIconList* iconList, BOOL grayscale); virtual BOOL WINAPI CreateAsCopy(const CGUIIconListAbstract* iconList, BOOL grayscale); - // prevede icon list na cernobilou verzi + // converts the icon list to a grayscale version virtual BOOL WINAPI ConvertToGrayscale(BOOL forceAlphaForBW); - // zakomprimuje bitmapu do 32bitoveho PNG a alfa kanalem (jeden dlouhy radek) - // pokud se vse podari, vraci TRUE a ukazatel na alokovanou pamet, kterou je nutne potom dealokovat - // pri chybe vraci FALSE + // compresses the bitmap into a 32-bit PNG with an alpha channel (one long row) + // on success, returns TRUE and a pointer to allocated memory that must later be freed + // on error, returns FALSE virtual BOOL WINAPI SaveToPNG(BYTE** rawPNG, DWORD* rawPNGSize); virtual BOOL WINAPI ReplaceIcon(int index, HICON hIcon); - // vytvori ikonku z pozice 'index'; vraci jeji handle nebo NULL v pripade neuspechu - // vracenou ikonu je po pouziti treba destruovat pomoci API DestroyIcon + // creates an icon from position 'index'; returns its handle or NULL on failure + // the returned icon must be destroyed after use with the DestroyIcon API virtual HICON WINAPI GetIcon(int index); HICON GetIcon(int index, BOOL useHandles); - // vytvori imagelist (jeden radek, pocet sloupcu dle poctu polozek); vraci jeho handle nebo NULL v pripade neuspechu - // vraceny imagelist je po pouziti treba destruovat pomoci API ImageList_Destroy() + // creates an image list (one row, with the number of columns based on the number of items); returns its handle or NULL on failure + // the returned image list must be destroyed with the ImageList_Destroy() API after use virtual HIMAGELIST WINAPI GetImageList(); - // kopiruje jednu polozku ze 'srcIL' a pozice 'srcIndex' na pozici 'dstIndex' + // copies one item from 'srcIL' at position 'srcIndex' to position 'dstIndex' virtual BOOL WINAPI Copy(int dstIndex, CIconList* srcIL, int srcIndex); - // kopiruje jednu polozku z pozice 'srcIndex' do 'hDstImageList' na pozici 'dstIndex' + // copies one item from position 'srcIndex' into 'hDstImageList' at position 'dstIndex' // BOOL CopyToImageList(HIMAGELIST hDstImageList, int dstIndex, int srcIndex); virtual BOOL WINAPI Draw(int index, HDC hDC, int x, int y, COLORREF blendClr, DWORD flags); @@ -162,24 +166,24 @@ class CIconList : public CGUIIconListAbstract virtual COLORREF WINAPI GetBkColor(); private: - // pokud neexistuje, vytvori HTmpImage - // pokud HTmpImage existuje a je mensi nez 'width' x 'height', vytvori novy - // vraci TRUE v pripade uspechu, jinak vraci FALSE a zachovava minuly HTmpImage + // creates HTmpImage if it does not exist + // if HTmpImage exists and is smaller than 'width' x 'height', creates a new one + // returns TRUE on success; otherwise returns FALSE and keeps the previous HTmpImage BOOL CreateOrEnlargeTmpImage(int width, int height); - // vraci handle bitmapy prave vybrane v HMemDC - // pokud HMemDC neexistuje, vraci NULL + // returns the handle of the bitmap currently selected in HMemDC + // if HMemDC does not exist, returns NULL HBITMAP GetCurrentBitmap(); - // 'index' urcuje pozici ikonky v HImage - // vraci TRUE, pokud v obrazek 'index' v HImage obsahoval alfa kanal + // 'index' specifies the icon position in HImage + // returns TRUE if image 'index' in HImage contained an alpha channel BYTE ApplyMaskToImage(int index, BYTE forceXOR); - // pro ladici ucely -- zobrazi dump ARGB hodnot barevne bitmapy i masky + // for debugging purposes -- shows a dump of the ARGB values of both the color bitmap and the mask // void DumpToTrace(int index, BOOL dumpMask); - // renderovani bod po bodu a nasledny BitBlt je v RELEASE verzi - // pouze o 30% pomalejsi proti cistemu BitBlt + // point-by-point rendering followed by BitBlt is in the RELEASE build + // only about 30% slower than a plain BitBlt BOOL DrawALPHA(HDC hDC, int x, int y, int index, COLORREF bkColor); BOOL DrawXOR(HDC hDC, int x, int y, int index, COLORREF bkColor); @@ -190,13 +194,13 @@ class CIconList : public CGUIIconListAbstract void StoreMonoIcon(int index, WORD* mask); - // specialni podpurna funkce pro CreateFromBitmap(); nakopiruj z 'hSrcBitmap' - // zvoleny pocet polozek do 'dstIndex'; predpoklada, ze 'hSrcBitmap' bude dlouhy - // prouzek ikon, jeden radek vysoky - // transparentClr udava barvu, ktera se ma povazovat za pruhlednou - // predpoklada se, ze zdrojova bitmapa ma stejny rozmer ikonek jako ma cilova (ImageWidth, ImageHeight) - // jednim kopirovanim lze pracovat maximalne s jednim radkem cilove bitmapy, - // nelze napriklad nakopirovat data do dvou radku v cilove bitmape + // special helper for CreateFromBitmap(); copies the selected number of items + // from 'hSrcBitmap' into 'dstIndex'; assumes 'hSrcBitmap' is a long strip of + // icons one row high + // transparentClr specifies the color to be considered transparent + // assumes the source bitmap has the same icon dimensions as the target one (ImageWidth, ImageHeight) + // a single copy operation can work with at most one row of the target bitmap; + // for example, it cannot copy data into two rows in the target bitmap BOOL CopyFromBitmapIternal(int dstIndex, HBITMAP hSrcBitmap, int srcIndex, int imageCount, COLORREF transparentClr); }; diff --git a/src/inflate.cpp b/src/inflate.cpp index f651b39fc..1926aec4a 100644 --- a/src/inflate.cpp +++ b/src/inflate.cpp @@ -9,8 +9,8 @@ /* inflate.c -- modified by Lucas Cerman & Petr Solin version 1.1, Feb 2007 - based on file inflate.c distributed with infozip, - writen by Mark Adler + based on the inflate.c file distributed with Info-ZIP, + written by Mark Adler version c16b, 29 March 1998 */ /* @@ -78,7 +78,7 @@ end-of-block. Note however that the static length tree defines 288 codes just to fill out the Huffman codes. Codes 286 and 287 cannot be used though, since there is no length base or extra bits - defined for them. Similarily, there are up to 30 distance codes. + defined for them. Similarly, there are up to 30 distance codes. However, static trees define 32 codes (all 5 bits) to fill out the Huffman codes, but the last two had better not show up in the data. 7. Unzip can check dynamic Huffman blocks for complete code sets. @@ -141,7 +141,7 @@ int huft_build(CDecompressionObject* decompress, circular buffer. The index is updated simply by incrementing and then and'ing with 0x7fff (32K-1) (window size - 1). */ // sliding window is defined in CDecompressionObject and could be -// any size greater or equal 32K +// any size greater than or equal to 32K /* Tables for deflate from PKZIP's appnote.txt. */ /* Order of the bit length code lengths */ @@ -186,7 +186,7 @@ static const uch cpdext32[] = { #define MAXDISTS 30 #endif -/* And'ing with mask_bits[n] masks the lower n bits */ +/* ANDing with mask_bits[n] masks the lower n bits */ const ush mask_bits[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, @@ -200,16 +200,16 @@ const ush mask_bits[] = { DUMPBITS(j) where NEEDBITS makes sure that b has at least j bits in it, and - DUMPBITS removes the bits from b. The macros use the variable k - for the number of bits in b. Normally, b and k are register - variables for speed and are initialized at the begining of a + DUMPBITS removes the bits from b. The macros use the variable k + for the number of bits in b. Normally, b and k are register + variables for speed and are initialized at the beginning of a routine that uses these macros from a global bit buffer and count. - In order to not ask for more bits than there are in the compressed - stream, the Huffman tables are constructed to only ask for just - enough bits to make up the end-of-block code (value 256). Then no - bytes need to be "returned" to the buffer at the end of the last - block. See the huft_build() routine. + In order not to ask for more bits than there are in the compressed + stream, the Huffman tables are constructed to ask for just enough + bits to make up the end-of-block code (value 256). Then no bytes + need to be "returned" to the buffer at the end of the last block. + See the huft_build() routine. */ //this function should replace NEXTBYTE macro @@ -270,7 +270,7 @@ uch NextByte(CDecompressionObject* decompress) the longer codes. The time it costs to decode the longer codes is then traded against the time it takes to make longer tables. - This results of this trade are in the variables lbits and dbits + The results of this tradeoff are reflected in the variables lbits and dbits below. lbits is the number of bits the first level table for literal/ length codes can decode in one step, and dbits is the same thing for the distance codes. Subsequent tables are also less than or equal to @@ -287,7 +287,7 @@ uch NextByte(CDecompressionObject* decompress) than five bits, flat. The optimum values for speed end up being about one bit more than those, so lbits is 8+1 and dbits is 5+1. The optimum values may differ though from machine to machine, and - possibly even between compilers. Your mileage may vary. + possibly even between compilers. */ static const int lbits = 9; /* bits in base literal/length lookup table */ @@ -295,10 +295,10 @@ static const int dbits = 6; /* bits in base distance lookup table */ #ifndef ASM_INFLATECODES -/* inflate (decompress) the codes in a deflated (compressed) block. - Return an error code or zero if it all goes ok. */ +/* Inflate (decompress) the codes in a deflated (compressed) block. + Returns an error code, or zero on success. */ int inflate_codes(CDecompressionObject* decompress, - struct huft* tl, //literal/length + struct huft* tl, // literal/length decoder tables struct huft* td, //distance decoder tables int bl, int bd) //number of bits decoded by tl[] and td[] { @@ -323,7 +323,7 @@ int inflate_codes(CDecompressionObject* decompress, /* inflate the coded data */ ml = mask_bits[bl]; /* precompute masks for speed */ md = mask_bits[bd]; - while (1) /* do until end of block */ + while (1) /* Repeat until the end of the block */ { NEEDBITS((unsigned)bl, decompress) t = tl + ((unsigned)b & ml); @@ -408,7 +408,7 @@ int inflate_codes(CDecompressionObject* decompress, break; } - if (e == 31) /* it's the EOB signal */ + if (e == 31) /* end-of-block (EOB) code */ { /* sorry for this goto, but we have to exit two loops at once */ goto cleanup_decode; @@ -438,7 +438,7 @@ int inflate_codes(CDecompressionObject* decompress, #endif /* ASM_INFLATECODES */ -// "decompress" an inflated type 0 (stored) block. +// Decompress a type 0 (stored) block. int inflate_stored(CDecompressionObject* decompress) { unsigned n; // number of bytes in block @@ -447,7 +447,7 @@ int inflate_stored(CDecompressionObject* decompress) unsigned outBytes, inBytes; //temporary variables - // make local copies of globals + // make local copies of the decompressor state b = decompress->BitBuf; // initialize bit buffer k = decompress->BitCount; @@ -464,20 +464,20 @@ int inflate_stored(CDecompressionObject* decompress) return 1; // error in compressed data DUMPBITS(16) - /* old copy routine, the new should be faster (I hope so) - // read and output the compressed data - while (n--) - { - NEEDBITS(8, decompress) - decompress->SlideWin[w++] = (uch)b; - if (w == decompress->WinSize) - { - decompress->Flush(w); - w = 0; - } - DUMPBITS(8, decompress) - } -*/ + /* old copy routine; the new one should be faster + // read and output the uncompressed data + while (n--) + { + NEEDBITS(8, decompress) + decompress->SlideWin[w++] = (uch)b; + if (w == decompress->WinSize) + { + decompress->Flush(w); + w = 0; + } + DUMPBITS(8, decompress) + } + */ //copy bytes from input to the output while (n) @@ -501,7 +501,7 @@ int inflate_stored(CDecompressionObject* decompress) bytesLeft -= inBytes; decompress->WinPos += inBytes; outBytes -= inBytes; - if (!bytesLeft && outBytes) // longer input is needed, but we don't have it (everything is in decompress->Data) + if (!bytesLeft && outBytes) // More input is needed, but none is available (everything is in decompress->Data) { TRACE_I("inflate_stored: input error"); return 4; @@ -525,9 +525,9 @@ int inflate_stored(CDecompressionObject* decompress) return 0; } -// decompress an inflated type 1 (fixed Huffman codes) block. We should -// either replace this with a custom decoder, or at least precompute the -// Huffman tables. +// Decompress a type 1 (fixed Huffman codes) block. +// This should either be replaced with a custom decoder or at least have the +// Huffman tables precomputed. int inflate_fixed(CDecompressionObject* decompress) { // if first time, set up tables for fixed blocks @@ -543,7 +543,7 @@ int inflate_fixed(CDecompressionObject* decompress) l[i] = 9; for (; i < 280; i++) l[i] = 7; - for (; i < 288; i++) // make a complete, but wrong code set + for (; i < 288; i++) // make a complete but incorrect code set l[i] = 8; decompress->fixed_bl = 7; if ((i = huft_build(decompress, l, 288, 257, @@ -574,7 +574,7 @@ int inflate_fixed(CDecompressionObject* decompress) decompress->fixed_bl, decompress->fixed_bd) != 0; } -/* decompress an inflated type 2 (dynamic Huffman codes) block. */ +/* Decompress a type 2 (dynamic Huffman codes) block. */ int inflate_dynamic(CDecompressionObject* decompress) { int i; /* temporary variables */ @@ -589,7 +589,7 @@ int inflate_dynamic(CDecompressionObject* decompress) unsigned nb; /* number of bit length codes */ unsigned nl; /* number of literal/length codes */ unsigned nd; /* number of distance codes */ - unsigned ll[MAXLITLENS + MAXDISTS]; /* lit./length and distance code lengths */ + unsigned ll[MAXLITLENS + MAXDISTS]; /* literal/length and distance code lengths */ register ulg b; /* bit buffer */ register unsigned k; /* number of bits in bit buffer */ @@ -597,7 +597,7 @@ int inflate_dynamic(CDecompressionObject* decompress) b = decompress->BitBuf; k = decompress->BitCount; - /* read in table lengths */ + /* read the table lengths */ NEEDBITS(5, decompress) nl = 257 + ((unsigned)b & 0x1f); /* number of literal/length codes */ DUMPBITS(5) @@ -610,7 +610,7 @@ int inflate_dynamic(CDecompressionObject* decompress) if (nl > MAXLITLENS || nd > MAXDISTS) return 1; /* bad lengths */ - /* read in bit-length-code lengths */ + /* Read bit-length code lengths. */ for (j = 0; j < nb; j++) { NEEDBITS(3, decompress) @@ -620,7 +620,7 @@ int inflate_dynamic(CDecompressionObject* decompress) for (; j < 19; j++) ll[border[j]] = 0; - /* build decoding table for trees--single level, 7 bit lookup */ + /* build a decoding table for the trees -- single-level, 7-bit lookup */ bl = 7; i = huft_build(decompress, ll, 19, 19, NULL, NULL, &tl, &bl); if (bl == 0) /* no bit lengths */ @@ -740,13 +740,13 @@ int inflate_dynamic(CDecompressionObject* decompress) if (i = inflate_codes(decompress, tl, td, bl, bd)) TRACE_I("inflate_dynamic: error in inflate_codes"); - /* free the decoding tables, return */ + /* Free the decoding tables and return. */ huft_free(decompress, tl); huft_free(decompress, td); return i; } -/* decompress an inflated block */ +/* Decompress a deflated block */ int inflate_block(CDecompressionObject* decompress, int* e) // int *e; { @@ -758,12 +758,12 @@ int inflate_block(CDecompressionObject* decompress, int* e) b = decompress->BitBuf; k = decompress->BitCount; - /* read in last block bit */ + /* read the last-block bit */ NEEDBITS(1, decompress) *e = (int)b & 1; DUMPBITS(1) - /* read in block type */ + /* read the block type */ NEEDBITS(2, decompress) t = (unsigned)b & 3; DUMPBITS(2) @@ -785,7 +785,7 @@ int inflate_block(CDecompressionObject* decompress, int* e) return 2; } -//decompress an inflated entry +// Decompress a deflated entry int Inflate(CDecompressionObject* decompress) { CALL_STACK_MESSAGE1("Inflate()"); @@ -794,7 +794,7 @@ int Inflate(CDecompressionObject* decompress) /* #ifdef DEBUG - unsigned h = 0; // maximum struct huft's malloc'ed + unsigned h = 0; // maximum number of allocated struct huft instances #endif */ @@ -963,7 +963,7 @@ int huft_build(CDecompressionObject* decompress, if ((j = *p++) != 0) v[x[j]++] = i; } while (++i < n); - n = x[g]; /* set n to length of v */ + n = x[g]; /* set n to the length of v */ /* Generate the Huffman codes and for each, make the table entries */ x[0] = i = 0; /* first Huffman code is zero */ @@ -972,7 +972,7 @@ int huft_build(CDecompressionObject* decompress, w = l[-1] = 0; /* no bits decoded yet */ u[0] = (struct huft*)NULL; /* just to keep compilers happy */ q = (struct huft*)NULL; /* ditto */ - z = 0; /* ditto */ + z = 0; /* just to keep compilers happy */ /* go through the bit lengths (k already is bits in shortest code) */ for (; k <= g; k++) @@ -1002,9 +1002,9 @@ int huft_build(CDecompressionObject* decompress, if ((unsigned)w + j > el && (unsigned)w < el) j = el - w; /* make EOB code end at table */ z = 1 << j; /* table entries for j-bit table */ - l[h] = j; /* set table size in stack */ + l[h] = j; /* save table size on the stack */ - /* allocate and link in new table */ + /* allocate and link the new table */ if ((q = (struct huft*)malloc((z + 1) * sizeof(struct huft))) == (struct huft*)NULL) { diff --git a/src/jumplist.cpp b/src/jumplist.cpp index bfee26196..cd3442fee 100644 --- a/src/jumplist.cpp +++ b/src/jumplist.cpp @@ -21,8 +21,8 @@ DEFINE_PROPERTYKEY(PKEY_Title, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 2); DEFINE_PROPERTYKEY(PKEY_AppUserModel_IsDestListSeparator, 0x9F4C2855, 0x9F79, 0x4B39, 0xA8, 0xD0, 0xE1, 0xD4, 0x2D, 0xE1, 0xD5, 0xF3, 6); -// We want to link the unique process ID with the configuration -// (two different versions of Salamander may, for example, have different hot paths) +// Associate the unique process ID with the configuration +// (for example, two different versions of Salamander may have different hot paths) //const char *SALAMANDER_APP_ID = "OPENSAL.OpenSalamanderAppID." VERSINFO_xstr(VERSINFO_BUILDNUMBER); //typedef WINSHELLAPI HRESULT (WINAPI *FT_SetCurrentProcessExplicitAppUserModelID)(PCWSTR appID); @@ -170,7 +170,7 @@ HRESULT CreateShellLink(const char* path, const char* name, IShellLink** psl) lstrcpyn(desc, path, _countof(desc)); if (strlen(path) >= _countof(desc)) strcpy(desc + _countof(desc) - 4, "..."); // indicates the path has been truncated - ret->SetDescription(desc); // MAX_PATH+1 is the limit (at least on Windows 7 where I'm testing now); longer = the jump list won't show at all + ret->SetDescription(desc); // MAX_PATH+1 is the limit (at least on Windows 7, where this was tested); if it is longer, the jump list will not be shown ret->SetIconLocation("shell32.dll", -319); // this icon exists from Windows XP onwards // To set the link title, we require the property store of the link. @@ -284,7 +284,7 @@ void CreateJumpList() IID_PPV_ARGS(&pcdl)); if (SUCCEEDED(hr)) { - //important to setup App Id for the Jump List + // Important to set up the App ID for the Jump List //wchar_t appID[500]; //ConvertA2U(SALAMANDER_APP_ID, -1, appID, _countof(appID)); //hr = pcdl->SetAppID(appID); diff --git a/src/keyboard.cpp b/src/keyboard.cpp index 6a5a8d340..189a6346d 100644 --- a/src/keyboard.cpp +++ b/src/keyboard.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -148,7 +149,7 @@ BOOL IsSalHotKey(WORD hotKey) { case NONE: // up case CONTROL: // scroll up, keep cursor - case ALT: // up to selected item + case ALT: // move to the selected item case SHIFT: // select + up found = TRUE; } @@ -175,7 +176,7 @@ BOOL IsSalHotKey(WORD hotKey) { case NONE: // down case CONTROL: // scroll down, keep cursor - case ALT: // down to selected item + case ALT: // move down to the selected item case SHIFT: // select + down found = TRUE; } @@ -512,7 +513,7 @@ BOOL IsSalHotKey(WORD hotKey) switch (mods) { case NONE: // quick search/type in command line - case CONTROL: // files list + case CONTROL: // file list case ALT: // enter menu case SHIFT: // change drive found = TRUE; @@ -785,8 +786,8 @@ BOOL IsSalHotKey(WORD hotKey) case NONE: // edit case CONTROL: // sort by extension case ALT: // exit - case SHIFT: // edit new - case CONTROL_SHIFT: // edit width + case SHIFT: // edit new file + case CONTROL_SHIFT: // edit in wide mode found = TRUE; } break; @@ -986,12 +987,12 @@ BOOL IsSalHotKey(WORD hotKey) break; } - case 0xDC: // '\' + case 0xDC: // '\\' { switch (mods) { case NONE: // quick search/type in command line - case CONTROL: // root dir + case CONTROL: // go to the root directory found = TRUE; } break; diff --git a/src/lang/lang.rc2 b/src/lang/lang.rc2 index 66df709ee..0a742bcb2 100644 --- a/src/lang/lang.rc2 +++ b/src/lang/lang.rc2 @@ -1,4 +1,5 @@ -// +// CommentsTranslationProject: TRANSLATED +// // lang.rc2 - resources Microsoft Visual C++ does not edit directly // @@ -35,7 +36,7 @@ IDM_VIEWERMENU MENU MENUITEM "&Refresh\tCtrl+R", CM_REREADFILE MENUITEM SEPARATOR -// POZOR: pokud se zmeni index tohoto submenu, je potreba zmenit VIEWER_FILE_MENU_OTHFILESINDEX +// WARNING: if the index of this submenu changes, VIEWER_FILE_MENU_OTHFILESINDEX must also be updated POPUP "Ot&her Files" { MENUITEM "&Previous\tBackspace", CM_PREVFILE diff --git a/src/lang/texts.rc2 b/src/lang/texts.rc2 index 069bb047e..51a6d4d46 100644 --- a/src/lang/texts.rc2 +++ b/src/lang/texts.rc2 @@ -1,4 +1,5 @@ -#include "..\texts.rh2" +// CommentsTranslationProject: TRANSLATED +#include "..\texts.rh2" STRINGTABLE { @@ -1415,8 +1416,8 @@ STRINGTABLE IDS_GETCOMPRFILESIZEERROR, "Unable to get compressed file size for file: ""%s""\nError: %s\nDo you want to skip all similar errors?" - // pozor %s zde nesmi byt v uvozovkach, protoze bude obsahovat variabilni texty, - // ktere uvozovky budou mit + // Note: %s must not be in quotation marks here, because it will contain variable text + // that already includes quotation marks. IDS_CONFIRM_NTFSCOMPRESS, "Are you sure you want to compress %s?\n\nWarning: files and directories will be decrypted before compressing." IDS_CONFIRM_NTFSUNCOMPRESS, "Are you sure you want to uncompress %s?" IDS_CONFIRM_NTFSENCRYPT, "Are you sure you want to encrypt %s?\n\nWarning: files and directories will be uncompressed before encrypting." @@ -1451,7 +1452,7 @@ STRINGTABLE // // plural strings -- begin // -// znaky '<' a '>' ohranicuji oblast, kterou lze mysi prenest na clipboard +// the '<' and '>' characters mark the area that can be copied to the clipboard with the mouse IDS_PLURAL_X_BYTES, "{!}%s byte{s|0||1|s}" @@ -1484,6 +1485,7 @@ STRINGTABLE IDS_DLG_PLURAL_X_DIRS, "{!}%d Director{y|1|ies}" IDS_DLG_PLURAL_X_FILES_Y_DIRS, "{!}%d File{|1|s} and %d Director{y|1|ies}" +// Keep the original Czech plural examples below as reference data; do not translate this block. // IDS_PLURAL_X_FILES, "{!}%d {vybraný soubor|1|vybrané soubory|4|vybraných souborů}" // IDS_PLURAL_X_DIRS, "{!}%d {vybraný adresář|1|vybrané adresáře|4|vybraných adresářů}" // IDS_PLURAL_X_FILES_Y_DIRS, "{!}%d {vybraný soubor|1|vybrané soubory|4|vybraných souborů} a %d {vybraný adresář|1|vybrané adresáře|4|vybraných adresářů}" diff --git a/src/logo.cpp b/src/logo.cpp index ff491b560..6e452bb36 100644 --- a/src/logo.cpp +++ b/src/logo.cpp @@ -166,7 +166,7 @@ BOOL CSplashScreen::PrepareBitmap() svgGrad.AlphaBlend(hDC, 0, GradientY, gradSize.cx, Height - GradientY, SVGSTATE_ORIGINAL); svgHand.AlphaBlend(hDC, Width - handSize.cx, 0, handSize.cx, handSize.cy, SVGSTATE_ORIGINAL); - // fixed texts + // static text PaintText(SALAMANDER_TEXT_VERSION, VersionR.left, VersionR.top, @@ -457,7 +457,7 @@ CAboutDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (WindowsVistaAndLater) return (BOOL)(UINT_PTR)HGradientBkBrush; else - return (BOOL)(UINT_PTR)GetStockObject(NULL_BRUSH); // under XP this still worked fine + return (BOOL)(UINT_PTR)GetStockObject(NULL_BRUSH); // this still worked correctly on XP } break; } diff --git a/src/logo.h b/src/logo.h index 6bf4cd879..862f923d3 100644 --- a/src/logo.h +++ b/src/logo.h @@ -12,5 +12,5 @@ BOOL SplashScreenOpen(); // opens splash screen window void SplashScreenCloseIfExist(); // if window exists, closes it BOOL ExistSplashScreen(); // detects existence of splash screen window -HWND GetSplashScreenHandle(); // returns handle of splash screen, or NULL if it doesn't exist +HWND GetSplashScreenHandle(); // returns the splash screen handle, or NULL if it does not exist void IfExistSetSplashScreenText(const char* text); // if it exists, sets text that will be displayed immediately diff --git a/src/mainwnd.h b/src/mainwnd.h index 355e19c57..11f2fd744 100644 --- a/src/mainwnd.h +++ b/src/mainwnd.h @@ -212,7 +212,7 @@ class CHotPathItems int GetUnassignedHotPathIndex(); BOOL GetVisible(int index) { return Items[index].Visible; } - BOOL CleanName(char* name); // trims spaces and returns TRUE if the name is valid + BOOL CleanName(char* name); // trims spaces and returns TRUE if name is not empty BOOL SwapItems(int index1, int index2); // swaps two items in the array @@ -354,7 +354,7 @@ struct CDynString free(Buffer); } - BOOL Append(const char* str, int len); // returns TRUE on success; if 'len' is -1 the length is calculated using "len = strlen(str)" + BOOL Append(const char* str, int len); // returns TRUE on success; if 'len' is -1, "len = strlen(str)" is used const char* GetString() const { return Buffer; } }; @@ -403,7 +403,7 @@ class CMainWindow : public CMainWindowAncestor CUserMenuItems* UserMenuItems; CViewerMasks* ViewerMasks; - CRITICAL_SECTION ViewerMasksCS; // section used only for synchronizing access to 'ViewerMasks' (writes anywhere and reads outside the main thread) + CRITICAL_SECTION ViewerMasksCS; // critical section used only to synchronize access to 'ViewerMasks' (writes anywhere and reads outside the main thread) CViewerMasks* AltViewerMasks; CEditorMasks* EditorMasks; CHighlightMasks* HighlightMasks; @@ -441,7 +441,7 @@ class CMainWindow : public CMainWindowAncestor int ActivateSuspMode; // counter of WM_ACTIVATEAPP activations/deactivations; some messages may get lost - RECT WindowRect; // current window position + RECT WindowRect; // current window rectangle BOOL CaptionIsActive; // is the main window caption active? @@ -487,7 +487,7 @@ class CMainWindow : public CMainWindowAncestor void EnterViewerMasksCS() { HANDLES(EnterCriticalSection(&ViewerMasksCS)); } void LeaveViewerMasksCS() { HANDLES(LeaveCriticalSection(&ViewerMasksCS)); } - BOOL GetViewersAssoc(int wantedViewerType, CDynString* strViewerMasks); // helper: collects all masks associated with the given viewer type "wantedViewerType"; returns TRUE on success (when enough memory for the string) + BOOL GetViewersAssoc(int wantedViewerType, CDynString* strViewerMasks); // helper method: collects all masks associated with viewer type "wantedViewerType"; returns TRUE on success (if there is enough memory for the string) void ClearHistory(); // clears all histories @@ -503,7 +503,7 @@ class CMainWindow : public CMainWindowAncestor // these functions have no effect if CFilesWindow::CanBeFocused is not satisfied void ChangePanel(BOOL force = FALSE); // respects EditMode; activates the inactive panel; (ignores ZOOM if force is TRUE) - void FocusPanel(CFilesWindow* focus, BOOL testIfMainWndActive = FALSE); // clears EditMode because focus is put into the panel + void FocusPanel(CFilesWindow* focus, BOOL testIfMainWndActive = FALSE); // clears EditMode because it sets focus to the panel void FocusLeftPanel(); // calls FocusPanel for the left panel // compares directories in the left and right panels @@ -584,7 +584,7 @@ class CMainWindow : public CMainWindowAncestor BOOL ToggleBottomToolBar(); BOOL ToggleUserMenuToolBar(BOOL storePos = TRUE); BOOL ToggleHotPathsBar(BOOL storePos = TRUE); - // If 'twoDriveBars' is TRUE, the user wants two drive lists; otherwise only one + // If 'twoDriveBars' is TRUE, the user wants to toggle two drive bars; otherwise only one BOOL ToggleDriveBar(BOOL twoDriveBars, BOOL storePos = TRUE); void ToggleToolBarGrips(); @@ -675,7 +675,7 @@ class CMainWindow : public CMainWindowAncestor BOOL CanEnterHelpMode(); void OnContextHelp(); HWND SetHelpCapture(POINT point, BOOL* pbDescendant); - BOOL ProcessHelpMsg(MSG& msg, DWORD* pContext, HWND* hDirtyWindow); // hDirtyWindow: returns the window to which we sent WM_USER_HELP_MOUSEMOVE and that needs to receive WM_USER_HELP_MOUSELEAVE + BOOL ProcessHelpMsg(MSG& msg, DWORD* pContext, HWND* hDirtyWindow); // hDirtyWindow: returns the window to which WM_USER_HELP_MOUSEMOVE was sent and which needs to receive WM_USER_HELP_MOUSELEAVE void ExitHelpMode(); DWORD MapClientArea(POINT point); DWORD MapNonClientArea(int iHit); diff --git a/src/mainwnd1.cpp b/src/mainwnd1.cpp index f71f50329..ab21b8a5f 100644 --- a/src/mainwnd1.cpp +++ b/src/mainwnd1.cpp @@ -198,8 +198,8 @@ BOOL CHotPathItems::Save(HKEY hKey) if (*name == 0 && *path == 0 && visible == TRUE) { - // optimization: don't clutter the registry unless needed - // not ready for configuration merging, but neither is the rest of our configuration + // Optimization: do not write to the registry unless necessary + // Not ready for configuration merging, but neither is the rest of the configuration ClearKey(actKey); CloseKey(actKey); DeleteKey(hKey, keyName); @@ -238,7 +238,7 @@ BOOL CHotPathItems::Load(HKEY hKey) CleanName(name); if (GetValue(actKey, SALAMANDER_HOTPATHS_PATH, REG_SZ, path, HOTPATHITEM_MAXPATH)) { - if (Configuration.ConfigVersion < 47) // the old path limit was MAX_PATH, so it fits with expansion + if (Configuration.ConfigVersion < 47) // the old path was limited to MAX_PATH, so it still fits after expansion DuplicateDollars(path, HOTPATHITEM_MAXPATH); // if the path is long and contains '$', the end might be truncated; we ignore it } GetValue(actKey, SALAMANDER_HOTPATHS_VISIBLE, REG_DWORD, &visible, sizeof(DWORD)); @@ -267,7 +267,7 @@ BOOL CHotPathItems::Load1_52(HKEY hKey) itoa(i, keyName, 10); if (GetValue(hKey, keyName, REG_SZ, path, MAX_PATH)) { - DuplicateDollars(path, MAX_PATH); // if the path is long and contains '$', the end might be truncated; ignore it + DuplicateDollars(path, MAX_PATH); // if the path is long and contains '$', the end may be truncated; this is not addressed strcpy(name, path); } @@ -352,7 +352,7 @@ CMainWindow::CMainWindow() : ChangeNotifArray(3, 5) item = new CViewerMasksItem(); if (ViewerMasks != NULL && item != NULL) { - ViewerMasks->Add(item); // no critical section needed, we're in the constructor + ViewerMasks->Add(item); // no critical section needed; this is the constructor item->Set("*.htm;*.html;*.xml;*.mht", "", "", ""); item->ViewerType = -4; // IE viewer (4th plugin in the default configuration) } @@ -360,7 +360,7 @@ CMainWindow::CMainWindow() : ChangeNotifArray(3, 5) item = new CViewerMasksItem(); if (ViewerMasks != NULL && item != NULL) { - ViewerMasks->Add(item); // no critical section needed, we're in the constructor + ViewerMasks->Add(item); // no critical section is needed; this is the constructor item->Set("*.rpm", "", "", ""); item->ViewerType = -2; // TAR (2nd plugin in the default configuration) } @@ -368,7 +368,7 @@ CMainWindow::CMainWindow() : ChangeNotifArray(3, 5) item = new CViewerMasksItem(); if (ViewerMasks != NULL && item != NULL) { - ViewerMasks->Add(item); // no critical section needed, we're in the constructor + ViewerMasks->Add(item); // no critical section is needed; this is the constructor item->Set("*.*", "", "", ""); item->ViewerType = VIEWER_INTERNAL; // internal viewer } @@ -558,7 +558,7 @@ BOOL CMainWindow::TogglePluginsBar(BOOL storePos) if (!PluginsBar->CreateWnd(HTopRebar)) return FALSE; // IdleForceRefresh = TRUE; // force an update - // IdleRefreshStates = TRUE; // on next Idle, enforce a check on status variables + // IdleRefreshStates = TRUE; // on the next Idle, force a check of the state variables PluginsBar->CreatePluginButtons(); InsertPluginsBarBand(); ShowWindow(PluginsBar->HWindow, SW_SHOW); @@ -1182,7 +1182,7 @@ void CMainWindow::EditWindowSetDirectory() EditWindow->Enable(TRUE); // cached in EditWindow EditWindow->SetDirectory(dir); } - else // disable/hide edit-line + else // disable/hide the edit line { if (EditMode && panel != NULL) // release focus from command line before disabling it FocusPanel(panel, TRUE); @@ -1241,7 +1241,7 @@ void CMainWindow::SetUnescapedHotPath(int index, const char* path) lstrcpyn(HotPathSetBufferName, path, MAX_PATH); lstrcpyn(HotPathSetBufferPath, path, HOTPATHITEM_MAXPATH); DuplicateDollars(HotPathSetBufferPath, HOTPATHITEM_MAXPATH); - // open the HotPaths page and edit item index + // open the HotPaths page and start editing item index PostMessage(HWindow, WM_USER_CONFIGURATION, 1, index); } else @@ -1760,7 +1760,7 @@ void CMainWindow::GetFormatedPathForTitle(char* path) if (chars < pathLen) lastChars = chars; else - break; // end of path isn't a point of division;bug in GetNextDirectoryLineHotPath implementation + break; // end of path is not a split point; bug in GetNextDirectoryLineHotPath implementation } trimEnd = path + lastChars; } @@ -1813,7 +1813,7 @@ void CMainWindow::GetFormatedPathForTitle(char* path) if (chars < pathLen) lastChars = chars; else - break; // end of path isn't a point of division; bug in GetNextDirectoryLineHotPath implementation + break; // end of path is not a split point; bug in GetNextDirectoryLineHotPath implementation } if (lastChars > 0) { @@ -3053,7 +3053,7 @@ void CMainWindow_RefreshCommandStates(CMainWindow* obj) void CMainWindow::RefreshCommandStates() { - CMainWindow_RefreshCommandStates(this); // this hack exists because we can't obtain the object's method address (as a plain function we can) + CMainWindow_RefreshCommandStates(this); // this workaround exists because the address of an object method cannot be obtained here (unlike for a plain function) } void CMainWindow::OnEnterIdle() diff --git a/src/mainwnd2.cpp b/src/mainwnd2.cpp index 76fe3d8ee..7b46afb92 100644 --- a/src/mainwnd2.cpp +++ b/src/mainwnd2.cpp @@ -51,102 +51,102 @@ // 21 = 2.5b6 only to transfer plug-in configuration from version 2.5b5(a) // 22 = 2.5b6 panel filters - unified into one history // 23 = 2.5b6 new panel view (Tiles) -// 24 = 2.5b7 only to transfer plug-in configuration from version 2.5b6 -// 25 = 2.5b7 plugins: show in plugin bar -> transfer variable into CPluginData -// 26 = 2.5b8 only to transfer plug-in configuration from version 2.5b7 -// 27 = 2.5b9 only to transfer plug-in configuration from version 2.5b8 -// 28 = 2.5b9 new color scheme from old DOS Navigator -> convert 'scheme' -// 29 = 2.5b10 only to transfer plug-in configuration from version 2.5b9 -// 30 = 2.5b11 only to transfer plug-in configuration from version 2.5b10 -// 31 = 2.5b11 introduced Floppy section in Drives configuration - need to force reading icons for Removable +// 24 = 2.5b7 only to transfer plugin configuration from version 2.5b6 +// 25 = 2.5b7 plugins: show in plugin bar -> transfer the variable to CPluginData +// 26 = 2.5b8 only to transfer plugin configuration from version 2.5b7 +// 27 = 2.5b9 only to transfer plugin configuration from version 2.5b8 +// 28 = 2.5b9 new color scheme based on the old DOS Navigator -> convert 'scheme' +// 29 = 2.5b10 only to transfer plugin configuration from version 2.5b9 +// 30 = 2.5b11 only to transfer plugin configuration from version 2.5b10 +// 31 = 2.5b11 introduced the Floppy section in the Drives configuration - need to force icon loading for Removable // 32 = 2.5b11 Find: "Local Settings\\Temporary Internet Files" is searched by default -// 33 = 2.5b12 only to transfer plug-in configuration from version 2.5b11 -// 34 = 2.5b12 modification of external packer/unpacker PKZIP25 (external Win32 version) -// 35 = 2.5RC1 only to transfer plug-in configuration from version 2.5b12 (internal only, we shipped RC1 instead) -// 36 = 2.5RC2 only to transfer plug-in configuration from version 2.5RC1 -// 37 = 2.5RC3 only to transfer plug-in configuration from version 2.5RC2 +// 33 = 2.5b12 only to transfer plugin configuration from version 2.5b11 +// 34 = 2.5b12 modification of the external PKZIP25 packer/unpacker (external Win32 version) +// 35 = 2.5RC1 only to transfer plugin configuration from version 2.5b12 (internal only, RC1 was released instead) +// 36 = 2.5RC2 only to transfer plugin configuration from version 2.5RC1 +// 37 = 2.5RC3 only to transfer plugin configuration from version 2.5RC2 // 38 = 2.5RC3 renamed Servant Salamander to Altap Salamander -// 39 = 2.5 only to transfer plug-in configuration from version 2.5RC3 -// 40 = 2.51 only to transfer plug-in configuration from version 2.5 +// 39 = 2.5 only to transfer plugin configuration from version 2.5RC3 +// 40 = 2.51 only to transfer plugin configuration from version 2.5 // 41 = 2.51 configuration version containing a list of disabled icon overlay handlers (see CONFIG_DISABLEDCUSTICOVRLS_REG) -// 42 = 2.52b1 only to transfer plug-in configuration from version 2.51 -// 43 = 2.52b2 only to transfer plug-in configuration from version 2.52 beta 1 -// 44 = 2.52b2 changed viewer, editor and archiver extensions to lowercase (uppercase extensions are obsolete in Windows) -// 45 = 2.52b2 introduced password manager, forced FTP client load so it registers to use the Password Manager, see SetPluginUsesPasswordManager -// 46 = 2.52 (DB30) only to transfer plug-in configuration from version 2.52 beta 2 -// 47 = 2.52 (IB31) support for Sal/Env variables like $(SalDir) or $[USERPROFILE] in hot paths; need to escape old hot paths -// 48 = 2.52 only to transfer plug-in configuration from version 2.52 (DB30) -// 49 = 2.53b1 (DB33) only to transfer plug-in configuration from version 2.52 -// 50 = 2.53b1 (DB36) only to transfer plug-in configuration from version 2.53b1 (DB33) -// 51 = 2.53b1 (PB38) only to transfer plug-in configuration from version 2.53b1 (DB36) -// 52 = 2.53b1 (DB39) only to transfer plug-in configuration from version 2.53b1 (PB38) -// 53 = 2.53b1 (DB41) only to transfer plug-in configuration from version 2.53b1 (DB39) -// 54 = 2.53b1 (PB44) only to transfer plug-in configuration from version 2.53b1 (DB41) -// 55 = 2.53b1 (DB46) only to transfer plug-in configuration from version 2.53b1 (PB44) -// 56 = 2.53b1 only to transfer plug-in configuration from version 2.53b1 (DB46) -// 57 = 2.53 (DB52) only to transfer plug-in configuration from version 2.53b1 -// 58 = 2.53b2 (IB55) only to transfer plug-in configuration from version 2.53 (DB52) -// 59 = 2.53b2 only to transfer plug-in configuration from version 2.53b2 (IB55) -// 60 = 2.53 (DB60) only to transfer plug-in configuration from version 2.53b2 -// 61 = 2.53 only to transfer plug-in configuration from version 2.53 (DB60) -// 62 = 2.54b1 (DB66) only to transfer plug-in configuration from version 2.53 -// 63 = 2.54 only to transfer plug-in configuration from version 2.54b1 (DB66) -// 64 = 2.55b1 (DB72) only to transfer plug-in configuration from version 2.54 -// 65 = 2.55b1 (DB72) external archivers: identify by UID instead of Title (translated according to language version, so cannot be used for identification) - switching language caused external archiver paths to be lost -// 66 = 3.00b1 (PB75) only to transfer plug-in configuration from version 2.55b1 (DB72) -// 67 = 3.00b1 (DB76) only to transfer plug-in configuration from version 3.00b1 (PB75) -// 68 = 3.00b1 (PB79) only to transfer plug-in configuration from version 3.00b1 (DB76) -// 69 = 3.00b1 (DB80) only to transfer plug-in configuration from version 3.00b1 (PB79) -// 70 = 3.00b1 (DB83) only to transfer plug-in configuration from version 3.00b1 (DB80) -// 71 = 3.00b1 (PB87) only to transfer plug-in configuration from version 3.00b1 (DB83) -// 72 = 3.00b1 (DB88) only to transfer plug-in configuration from version 3.00b1 (PB87) -// 73 = 3.00b1 only to transfer plug-in configuration from version 3.00b1 (DB88) -// 74 = 3.00b2 (DB94) only to transfer plug-in configuration from version 3.00b1 -// 75 = 3.00b2 only to transfer plug-in configuration from version 3.00b2 (DB94) -// 76 = 3.00b3 (DB100) only to transfer plug-in configuration from version 3.00b2 -// 77 = 3.00b3 (PB103) only to transfer plug-in configuration from version 3.00b3 (DB100) -// 78 = 3.00b3 (DB105) only to transfer plug-in configuration from version 3.00b3 (PB103) -// 79 = 3.00b3 only to transfer plug-in configuration from version 3.00b3 (DB105) -// 80 = 3.00b4 (DB111) only to transfer plug-in configuration from version 3.00b3 -// 81 = 3.00b4 (DB111) RAR 5.0 needs a new switch on the command line because of file list encoding -// 82 = 3.00b4 only to transfer plug-in configuration from version 3.00b4 (DB111) -// 83 = 3.00b5 (DB117) only to transfer plug-in configuration from version 3.00b4 -// 84 = 3.0 only to transfer plug-in configuration from version 3.00b5 (DB117) -// 85 = 3.10b1 (DB123) only to transfer plug-in configuration from version 3.0 -// 86 = 3.01 only to transfer plug-in configuration from version 3.10b1 (DB123) -// 87 = 3.10b1 (DB129) only to transfer plug-in configuration from version 3.01 -// 88 = 3.02 only to transfer plug-in configuration from version 3.10b1 (DB129) -// 89 = 3.10b1 (DB135) only to transfer plug-in configuration from version 3.02 -// 90 = 3.03 only to transfer plug-in configuration from version 3.10b1 (DB135) -// 91 = 3.10b1 (DB141) only to transfer plug-in configuration from version 3.03 -// 92 = 3.04 only to transfer plug-in configuration from version 3.10b1 (DB141) -// 93 = 3.10b1 (DB147) only to transfer plug-in configuration from version 3.04 -// 94 = 3.05 only to transfer plug-in configuration from version 3.10b1 (DB147) -// 95 = 3.10b1 (DB153) only to transfer plug-in configuration from version 3.05 -// 96 = 3.06 only to transfer plug-in configuration from version 3.10b1 (DB153) -// 97 = 3.10b1 (DB159) only to transfer plug-in configuration from version 3.06 -// 98 = 3.10b1 (DB162) only to transfer plug-in configuration from version 3.10b1 (DB159) -// 99 = 3.07 only to transfer plug-in configuration from version 3.10b1 (DB162) -// 100 = 4.00b1 (DB168) only to transfer plug-in configuration from version 3.07 -// 101 = 3.08 only to transfer plug-in configuration from version 4.00b1 (DB168) - by mistake 3.08 and DB171 share the same version number 101, sorry, I will be more careful next time -// 101 = 4.00b1 (DB171) only to transfer plug-in configuration from version 4.00b1 (DB168); this is the last VC2008 build, later versions are VC2019 -// 102 = 4.00b1 (DB177) only to transfer plug-in configuration from version 4.00b1 (DB171) -// 103 = 4.00 only to transfer plug-in configuration from version 4.00b1 (DB177) -// 104 = 5.00 only to transfer plug-in configuration from version 4.00, first Open Salamander release +// 42 = 2.52b1 only to transfer plugin configuration from version 2.51 +// 43 = 2.52b2 only to transfer plugin configuration from version 2.52 beta 1 +// 44 = 2.52b2 changed viewer, editor, and archiver extensions to lowercase (uppercase extensions are obsolete in Windows) +// 45 = 2.52b2 introduced the password manager, forced the FTP client to load so it registers to use the Password Manager; see SetPluginUsesPasswordManager +// 46 = 2.52 (DB30) only to transfer plugin configuration from version 2.52 beta 2 +// 47 = 2.52 (IB31) support for Sal/Env variables such as $(SalDir) or $[USERPROFILE] in hot paths; old hot paths need to be escaped +// 48 = 2.52 only to transfer plugin configuration from version 2.52 (DB30) +// 49 = 2.53b1 (DB33) only to transfer plugin configuration from version 2.52 +// 50 = 2.53b1 (DB36) only to transfer plugin configuration from version 2.53b1 (DB33) +// 51 = 2.53b1 (PB38) only to transfer plugin configuration from version 2.53b1 (DB36) +// 52 = 2.53b1 (DB39) only to transfer plugin configuration from version 2.53b1 (PB38) +// 53 = 2.53b1 (DB41) only to transfer plugin configuration from version 2.53b1 (DB39) +// 54 = 2.53b1 (PB44) only to transfer plugin configuration from version 2.53b1 (DB41) +// 55 = 2.53b1 (DB46) only to transfer plugin configuration from version 2.53b1 (PB44) +// 56 = 2.53b1 only to transfer plugin configuration from version 2.53b1 (DB46) +// 57 = 2.53 (DB52) only to transfer plugin configuration from version 2.53b1 +// 58 = 2.53b2 (IB55) only to transfer plugin configuration from version 2.53 (DB52) +// 59 = 2.53b2 only to transfer plugin configuration from version 2.53b2 (IB55) +// 60 = 2.53 (DB60) only to transfer plugin configuration from version 2.53b2 +// 61 = 2.53 only to transfer plugin configuration from version 2.53 (DB60) +// 62 = 2.54b1 (DB66) only to transfer plugin configuration from version 2.53 +// 63 = 2.54 only to transfer plugin configuration from version 2.54b1 (DB66) +// 64 = 2.55b1 (DB72) only to transfer plugin configuration from version 2.54 +// 65 = 2.55b1 (DB72) external archivers: identify by UID instead of Title (translated by language version, so it cannot be used for identification) - switching languages caused the external archiver paths to be lost +// 66 = 3.00b1 (PB75) only to transfer plugin configuration from version 2.55b1 (DB72) +// 67 = 3.00b1 (DB76) only to transfer plugin configuration from version 3.00b1 (PB75) +// 68 = 3.00b1 (PB79) only to transfer plugin configuration from version 3.00b1 (DB76) +// 69 = 3.00b1 (DB80) only to transfer plugin configuration from version 3.00b1 (PB79) +// 70 = 3.00b1 (DB83) only to transfer plugin configuration from version 3.00b1 (DB80) +// 71 = 3.00b1 (PB87) only to transfer plugin configuration from version 3.00b1 (DB83) +// 72 = 3.00b1 (DB88) only to transfer plugin configuration from version 3.00b1 (PB87) +// 73 = 3.00b1 only to transfer plugin configuration from version 3.00b1 (DB88) +// 74 = 3.00b2 (DB94) only to transfer plugin configuration from version 3.00b1 +// 75 = 3.00b2 only to transfer plugin configuration from version 3.00b2 (DB94) +// 76 = 3.00b3 (DB100) only to transfer plugin configuration from version 3.00b2 +// 77 = 3.00b3 (PB103) only to transfer plugin configuration from version 3.00b3 (DB100) +// 78 = 3.00b3 (DB105) only to transfer plugin configuration from version 3.00b3 (PB103) +// 79 = 3.00b3 only to transfer plugin configuration from version 3.00b3 (DB105) +// 80 = 3.00b4 (DB111) only to transfer plugin configuration from version 3.00b3 +// 81 = 3.00b4 (DB111) RAR 5.0 needs a new command-line switch because of file list encoding +// 82 = 3.00b4 only to transfer plugin configuration from version 3.00b4 (DB111) +// 83 = 3.00b5 (DB117) only to transfer plugin configuration from version 3.00b4 +// 84 = 3.0 only to transfer plugin configuration from version 3.00b5 (DB117) +// 85 = 3.10b1 (DB123) only to transfer plugin configuration from version 3.0 +// 86 = 3.01 only to transfer plugin configuration from version 3.10b1 (DB123) +// 87 = 3.10b1 (DB129) only to transfer plugin configuration from version 3.01 +// 88 = 3.02 only to transfer plugin configuration from version 3.10b1 (DB129) +// 89 = 3.10b1 (DB135) only to transfer plugin configuration from version 3.02 +// 90 = 3.03 only to transfer plugin configuration from version 3.10b1 (DB135) +// 91 = 3.10b1 (DB141) only to transfer plugin configuration from version 3.03 +// 92 = 3.04 only to transfer plugin configuration from version 3.10b1 (DB141) +// 93 = 3.10b1 (DB147) only to transfer plugin configuration from version 3.04 +// 94 = 3.05 only to transfer plugin configuration from version 3.10b1 (DB147) +// 95 = 3.10b1 (DB153) only to transfer plugin configuration from version 3.05 +// 96 = 3.06 only to transfer plugin configuration from version 3.10b1 (DB153) +// 97 = 3.10b1 (DB159) only to transfer plugin configuration from version 3.06 +// 98 = 3.10b1 (DB162) only to transfer plugin configuration from version 3.10b1 (DB159) +// 99 = 3.07 only to transfer plugin configuration from version 3.10b1 (DB162) +// 100 = 4.00b1 (DB168) only to transfer plugin configuration from version 3.07 +// 101 = 3.08 only to transfer plugin configuration from version 4.00b1 (DB168) - 3.08 and DB171 accidentally share version number 101; hopefully harmless, but avoid this next time +// 101 = 4.00b1 (DB171) only to transfer plugin configuration from version 4.00b1 (DB168); this is the last VC2008 build, later versions are built with VC2019 +// 102 = 4.00b1 (DB177) only to transfer plugin configuration from version 4.00b1 (DB171) +// 103 = 4.00 only to transfer plugin configuration from version 4.00b1 (DB177) +// 104 = 5.00 only to transfer plugin configuration from version 4.00, first Open Salamander release // -// When increasing configuration version, add one to THIS_CONFIG_VERSION +// When increasing the configuration version, add 1 to THIS_CONFIG_VERSION // // When upgrading to a new program version, THIS_CONFIG_VERSION must be incremented by 1 -// so that new plug-ins are auto-installed and the plugins.ver counter resets. +// so that new plugins are auto-installed and the plugins.ver counter is reset. // const DWORD THIS_CONFIG_VERSION = 104; // Configuration roots for individual Open Salamander versions. -// The root of the current (youngest) configuration is at index 0. -// Then follow other roots towards older versions of the program. -// The last index contains NULL and serves as a terminator when working with the array. -// When creating a new configuration version (should be stored separately in the registry from the previous one) +// The root of the current (latest) configuration is at index 0. +// It is followed by the other roots, in order toward older program versions. +// The last index contains NULL, which serves as a terminator when working with the array. +// When creating a new configuration version (which should be stored separately in the registry from the previous one), // simply insert the path at index 0. // !!! Keep the corresponding lines in SalamanderConfigurationVersions up to date @@ -325,11 +325,11 @@ const char* SalamanderConfigurationVersions[SALCFG_ROOTS_COUNT] = const char* SALAMANDER_ROOT_REG = NULL; // will be set in salamdr1.cpp const char* SALAMANDER_SAVE_IN_PROGRESS = "Save In Progress"; // value exists only during configuration save (detects interrupted saves -> corrupted configuration) -BOOL IsSetSALAMANDER_SAVE_IN_PROGRESS = FALSE; // TRUE = the registry contains SALAMANDER_SAVE_IN_PROGRESS (detect interrupted configuration saving) +BOOL IsSetSALAMANDER_SAVE_IN_PROGRESS = FALSE; // TRUE = the registry contains SALAMANDER_SAVE_IN_PROGRESS (detects interrupted configuration saving) const char* SALAMANDER_COPY_IS_OK = "Copy Is OK"; // backup key only: value exists only if the key was copied completely -const char* SALAMANDER_AUTO_IMPORT_CONFIG = "AutoImportConfig"; // value exists only during upgrade: installer overwrites the old version with the new and stores this value pointing to the old configuration key from which the configuration should be imported +const char* SALAMANDER_AUTO_IMPORT_CONFIG = "AutoImportConfig"; // value exists only during upgrade: the installer overwrites the old version with the new one and stores this value in the new version's key, pointing to the old configuration key from which the configuration should be imported const char* FINDDIALOG_WINDOW_REG = "Find Dialog Window"; const char* SALAMANDER_WINDOW_REG = "Window"; @@ -921,7 +921,7 @@ BOOL GetUpgradeInfo(BOOL* autoImportConfig, char* autoImportConfigFromKey, int a if (!*autoImportConfig && // this version's key lacks "AutoImportConfig" or does not point to a valid old configuration HANDLES_Q(RegOpenKeyEx(HKEY_CURRENT_USER, SalamanderConfigurationRoots[0], 0, KEY_READ | KEY_WRITE, &rootKey)) == ERROR_SUCCESS) - { // remove "AutoImportConfig" from this version's key (if it exists it makes no sense here) + { // remove "AutoImportConfig" from this version's key if it exists; it serves no purpose here RegDeleteValue(rootKey, SALAMANDER_AUTO_IMPORT_CONFIG); HANDLES(RegCloseKey(rootKey)); } @@ -976,7 +976,7 @@ BOOL FindLanguageFromPrevVerOfSal(char* slgName) if (cfgFound) { BOOL found = FALSE; - if (rootIndex != 0 && // only for one of the older keys + if (rootIndex != 0 && // only if this is one of the older keys configVersion >= 59 /* 2.53 beta 2 */) // before 2.53 beta 2 there was only English, so reading makes no sense; offer system default language or manual selection of the language { GetValue(hCfgKey, CONFIG_LANGUAGE_REG, REG_SZ, slgName, MAX_PATH); @@ -993,8 +993,8 @@ BOOL FindLanguageFromPrevVerOfSal(char* slgName) return FALSE; } -// obtains a number from a string (unsigned decimal format); returns TRUE, if a number was found -// ignores white spaces before and after the number +// Gets a number from a string (decimal format without a sign); returns TRUE if a number was found +// Ignores whitespace before and after the number BOOL GetNumFromStr(const char* s, DWORD* retNum) { DWORD n = 0; @@ -1013,7 +1013,7 @@ void CheckShutdownParams() { // HKEY_CURRENT_USER\Control Panel\Desktop\WaitToKillAppTimeout=20000,REG_SZ ... warn if less than 20000 // HKEY_CURRENT_USER\Control Panel\Desktop\AutoEndTasks=0,REG_SZ ... warn if not 0 - // W2K and XP have it; I could not find it on Vista but supposedly it is there (info from the internet) + // W2K and XP have these settings; they were not found on Vista, but they are reportedly present there as well (per internet sources) BOOL showWarning = FALSE; HKEY key; @@ -1043,10 +1043,11 @@ void CheckShutdownParams() BOOL MyRegRenameKey(HKEY key, const char* name, const char* newName) { BOOL ret = FALSE; - // There is also NtRenameKey but I could not get it working (requires UNICODE_STRING - // and probably the key opened via NtOpenKey with the key passed via OBJECT_ATTRIBUTES initialized through - // InitializeObjectAttributes). It's overly complicated and not frequently used code, - // so we'll do it the slow but simple way... copy the key to a new one and then delete the original + // NtRenameKey also exists, but it proved impractical here (it requires UNICODE_STRING + // and probably also a key opened via NtOpenKey, with the key passed through OBJECT_ATTRIBUTES + // initialized by InitializeObjectAttributes). That is unnecessarily complicated for + // infrequently used code, so use the slow but simple approach: copy the key to a new one, + // then delete the original. HKEY newKey; if (!OpenKeyAux(NULL, key, newName, newKey)) // verify if the target key does not already exist { @@ -1087,7 +1088,7 @@ BOOL MyRegRenameKey(HKEY key, const char* name, const char* newName) BOOL FindLatestConfiguration(BOOL* deleteConfigurations, const char*& loadConfiguration) { HKEY hRootKey; - loadConfiguration = NULL; // we don't want to load any configuration - default values will be used + loadConfiguration = NULL; // do not load any configuration; default values will be used int rootIndex = 0; const char* root; DWORD saveInProgress; // dummy @@ -1114,7 +1115,7 @@ BOOL FindLatestConfiguration(BOOL* deleteConfigurations, const char*& loadConfig else copyIsOK = 0; // backup is corrupted HANDLES(RegCloseKey(backupKey)); - if (!copyIsOK) // delete the corrupted backup and pretend it never existed (it probably wasn't fully created) + if (!copyIsOK) // delete the corrupted backup and treat it as if it never existed (it probably was not fully created) { TRACE_I("Configuration backup is incomplete, removing... " << backup); SHDeleteKey(HKEY_CURRENT_USER, backup); @@ -1151,13 +1152,13 @@ BOOL FindLatestConfiguration(BOOL* deleteConfigurations, const char*& loadConfig } TRACE_I("Corrupted configuration was moved to: " << corrupted); TRACE_I("Using configuration backup instead ..."); - continue; // in the second pass load configuration from the backup created during "critical shutdown" + continue; // in the second pass, load the configuration from the backup created during "critical shutdown" } else TRACE_E("Unable to move corrupted configuration or configuration backup."); } - if (rootIndex == 0) // for the active version inform the user about the corrupted configuration and let them back up the key, then try to delete it (older versions - simply ignore the corrupted configuration) + if (rootIndex == 0) // For the current program version, inform the user about the corrupted configuration and let them back up the key, then try to delete it (for older versions, simply ignore the corrupted configuration) { char buf[1500]; _snprintf_s(buf, _TRUNCATE, LoadStr(IDS_CORRUPTEDCONFIGFOUND), root); @@ -1204,7 +1205,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = if (rootFound) CloseKeyAux(hRootKey); - if (rootIndex == 0 && backupFound) // backup not needed, remove it + if (rootIndex == 0 && backupFound) // backup is not needed, remove it { TRACE_I("Removing unnecessary configuration backup: " << backup); SHDeleteKey(HKEY_CURRENT_USER, backup); @@ -1301,7 +1302,7 @@ void CMainWindow::DeleteOldConfigurations(BOOL* deleteConfigurations, BOOL autoI } } } - if (autoImportConfig) // clean old configuration (already stored in the new key) and remove "AutoImportConfig" from the new key + if (autoImportConfig) // clean the old configuration (already stored in the new key) and remove "AutoImportConfig" from the new key { BOOL ok = FALSE; HKEY cfgKey; @@ -1312,13 +1313,13 @@ void CMainWindow::DeleteOldConfigurations(BOOL* deleteConfigurations, BOOL autoI ok = TRUE; HANDLES(RegCloseKey(cfgKey)); } - if (!ok) // if this happens it's probably fine because we likely didn't - // write Salamander's configuration either (it goes to the - // same key) and the whole upgrade will need to be run again + if (!ok) // if this happens, it is probably not a problem because we likely did not +// write Salamander's configuration either (it goes to the same key), and +// the whole upgrade will need to be run again { TRACE_E("CMainWindow::DeleteOldConfigurations(): unable to delete " << SALAMANDER_AUTO_IMPORT_CONFIG << " value from HKCU\\" << SalamanderConfigurationRoots[0]); } - else // clean the old configuration (already saved to the new key) + else // clear the old configuration (it is already stored in the new key) { if (!doNotDeleteImportedCfg) { @@ -1380,7 +1381,7 @@ void CMainWindow::SaveConfig(HWND parent) if (SALAMANDER_ROOT_REG == NULL) { - TRACE_E("SALAMANDER_ROOT_REG == NULL"); // not necessarily an error: during UPGRADE we may exit Salamander without saving the configuration (if not all plug-ins are installed and the user chooses Exit) + TRACE_E("SALAMANDER_ROOT_REG == NULL"); // not necessarily an error: during UPGRADE we may exit Salamander without saving the configuration (if not all plugins are installed and the user chooses Exit) return; } @@ -1397,7 +1398,7 @@ void CMainWindow::SaveConfig(HWND parent) analysing.Create(); EnableWindow(parent, FALSE); - // SaveConfiguration plug-ins will be invoked as well -> set the parent for their message boxes + // SaveConfiguration plugins will be invoked as well -> set the parent for their message boxes PluginMsgBoxParent = analysing.HWindow; } @@ -2400,7 +2401,7 @@ void CMainWindow::LoadPanelConfig(char* panelPath, CFilesWindow* panel, HKEY hSa panel->HeaderLineVisible = value; if (GetValue(actKey, PANEL_VIEW_REG, REG_DWORD, &value, sizeof(DWORD))) { - if (Configuration.ConfigVersion < 13 && !value) // conversion: the Detailed view was stored as FALSE + if (Configuration.ConfigVersion < 13 && !value) // conversion: the Detailed view was saved as FALSE value = 2; panel->SelectViewTemplate(value, FALSE, FALSE, VALID_DATA_ALL, FALSE, TRUE); } @@ -2506,7 +2507,7 @@ void LoadIconOvrlsInfo(const char* root) } else { - if (configVersion >= 41) // if this value is missing in newer configurations, disable overlays (older versions didn't have these variables, so it's not an error-leave overlays enabled) + if (configVersion >= 41) // If this value is missing in newer configurations, disable overlays (older versions did not have these variables, so it is not an error; leave overlays enabled) Configuration.EnableCustomIconOverlays = FALSE; } @@ -2870,7 +2871,7 @@ BOOL CMainWindow::LoadConfig(BOOL importingOldConfig, const CCommandLineParams* } //--- Plugins - if (OpenKey(salamander, SALAMANDER_PLUGINS, actKey)) // otherwise default values + if (OpenKey(salamander, SALAMANDER_PLUGINS, actKey)) // otherwise use default values { Plugins.Load(HWindow, actKey); CloseKey(actKey); @@ -3301,7 +3302,7 @@ BOOL CMainWindow::LoadConfig(BOOL importingOldConfig, const CCommandLineParams* { char path[MAX_PATH]; GetIfPathIsInaccessibleGoTo(path, TRUE); - if (IsTheSamePath(path, Configuration.IfPathIsInaccessibleGoTo)) // user wants to go to My Documents + if (IsTheSamePath(path, Configuration.IfPathIsInaccessibleGoTo)) // the user prefers My Documents { Configuration.IfPathIsInaccessibleGoToIsMyDocs = TRUE; Configuration.IfPathIsInaccessibleGoTo[0] = 0; @@ -3340,7 +3341,7 @@ BOOL CMainWindow::LoadConfig(BOOL importingOldConfig, const CCommandLineParams* } else { - if (Configuration.ConfigVersion == 11) // in 1.6 beta 7 it was enabled ... turn it off + if (Configuration.ConfigVersion == 11) // In 1.6 beta 7 this was enabled ... disable it { Configuration.UseSalOpen = FALSE; // default is not to use it } @@ -3406,7 +3407,7 @@ BOOL CMainWindow::LoadConfig(BOOL importingOldConfig, const CCommandLineParams* &Configuration.CompareIgnoreFiles, sizeof(DWORD)); GetValue(actKey, CONFIG_COMPAREIGNOREDIRS_REG, REG_DWORD, &Configuration.CompareIgnoreDirs, sizeof(DWORD)); - // a bit ugly: we provide MasksString, but the range is checked so it's fine + // a bit of a hack: we provide MasksString; the range is checked, so it is harmless GetValue(actKey, CONFIG_CONFIGTIGNOREFILESMASKS_REG, REG_SZ, Configuration.CompareIgnoreFilesMasks.GetWritableMasksString(), MAX_PATH); GetValue(actKey, CONFIG_CONFIGTIGNOREDIRSMASKS_REG, REG_SZ, @@ -3760,7 +3761,7 @@ BOOL CMainWindow::LoadConfig(BOOL importingOldConfig, const CCommandLineParams* &Configuration.TabSize, sizeof(DWORD)); GetValue(actKey, VIEWER_CONFIGDEFMODE_REG, REG_DWORD, &Configuration.DefViewMode, sizeof(DWORD)); - // a bit ugly: we provide MasksString, but the range is checked so it's fine + // a bit ugly, but we pass MasksString; the range is checked, so it is safe GetValue(actKey, VIEWER_CONFIGTEXTMASK_REG, REG_SZ, Configuration.TextModeMasks.GetWritableMasksString(), MAX_PATH); if (Configuration.ConfigVersion < 17 && @@ -3770,7 +3771,7 @@ BOOL CMainWindow::LoadConfig(BOOL importingOldConfig, const CCommandLineParams* } int errPos; Configuration.TextModeMasks.PrepareMasks(errPos); - // a bit ugly: we provide MasksString, but the range is checked so it's fine + // a bit ugly, but we pass MasksString; the range is checked, so it is safe GetValue(actKey, VIEWER_CONFIGHEXMASK_REG, REG_SZ, Configuration.HexModeMasks.GetWritableMasksString(), MAX_PATH); Configuration.HexModeMasks.PrepareMasks(errPos); @@ -3850,7 +3851,7 @@ BOOL CMainWindow::LoadConfig(BOOL importingOldConfig, const CCommandLineParams* if (cmdLineFocus) SendMessage(HWindow, WM_COMMAND, CM_EDITLINE, 0); - // this caused trouble: + // this caused problems here: // when a panel pointed to an unavailable UNC path, // it would wait here for several seconds // LeftPanel->UpdateDriveIcon(TRUE); @@ -3890,7 +3891,7 @@ BOOL CMainWindow::LoadConfig(BOOL importingOldConfig, const CCommandLineParams* Configuration.AlwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); - // show the window in full + // show the window normally if (useWinPlacement) { // from MSDN: @@ -3898,8 +3899,8 @@ BOOL CMainWindow::LoadConfig(BOOL importingOldConfig, const CCommandLineParams* // 3 = SW_SHOWMAXIMIZED // 7 = SW_SHOWMINNOACTIVE - // we don't want the application minimized on startup unless the user - // defined it in a shortcut + // we do not want the application minimized at startup unless the user + // specified it in the shortcut if (!Configuration.StatusArea) { switch (CmdShow) @@ -3968,7 +3969,7 @@ BOOL CMainWindow::LoadConfig(BOOL importingOldConfig, const CCommandLineParams* { if (cmdLineParams->LeftPath[0] == 0 && cmdLineParams->RightPath[0] == 0 && cmdLineParams->ActivePath[0] != 0) { - if (GetActivePanel()->ChangeDirLite(cmdLineParams->ActivePath)) // no point in combining this with left/right panel settings + if (GetActivePanel()->ChangeDirLite(cmdLineParams->ActivePath)) // no point in combining this with the left/right panel paths { if (rightPanelFocused) rightPanelPathSet = TRUE; @@ -3997,10 +3998,10 @@ BOOL CMainWindow::LoadConfig(BOOL importingOldConfig, const CCommandLineParams* } } - // save the array of visible items; normally this is done in idle time, but if it - // should be ready so that icon reading for user menu entries has priority over icons - // outside the visible part of the panel, we must handle it manually (icon loading - // is already running, but sooner is better than later, this minimal delay should not hurt) + // save the array of visible items; normally this is done during idle time, but if it + // is to be ready so that icon loading for user menu items has priority over icons + // outside the visible part of the panel, we must handle it manually (icon loading is + // already running, but better now than even later; this minimal delay should not matter much) if (rightPanelPathSet) RightPanel->RefreshVisibleItemsArray(); diff --git a/src/mainwnd3.cpp b/src/mainwnd3.cpp index 333896cc9..384465dd3 100644 --- a/src/mainwnd3.cpp +++ b/src/mainwnd3.cpp @@ -39,14 +39,14 @@ extern "C" #include "find.h" #include "viewer.h" -// critical shutdown: the maximum time we can spend in WM_QUERYENDSESSION (after that, -// KILL comes from Windows). It is 5s (5s with an open message box, 10s without pumping -// messages). I left a 500ms reserve. Tested on Vista, Win7, Win8, Win10. +// critical shutdown: the maximum time that can be spent in WM_QUERYENDSESSION (after that, +// Windows sends KILL) is 5 s (5 s with an open message box, 10 s without pumping +// messages); a 500 ms reserve was left. Tested on Vista, Win7, Win8, and Win10. #define QUERYENDSESSION_TIMEOUT 4500 // variables used when saving configuration during shutdown, log-off or restart // we must pump messages so the system does not kill us as "not responding" -CWaitWindow* GlobalSaveWaitWindow = NULL; // if a global wait window for Save exists, it's here (otherwise NULL) +CWaitWindow* GlobalSaveWaitWindow = NULL; // if a global wait window for Save exists, it is here (otherwise NULL) int GlobalSaveWaitWindowProgress = 0; // current progress value of the global wait window for Save // borrow constants from a newer SDK @@ -58,7 +58,7 @@ int GlobalSaveWaitWindowProgress = 0; // current progress value of the globa #define GET_APPCOMMAND_LPARAM(lParam) ((short)(HIWORD(lParam) & ~FAPPCOMMAND_MASK)) #define APPCOMMAND_BROWSER_BACKWARD 1 #define APPCOMMAND_BROWSER_FORWARD 2 -/* not supported yet +/* not currently supported #define APPCOMMAND_BROWSER_SEARCH 5 #define APPCOMMAND_HELP 27 #define APPCOMMAND_BROWSER_REFRESH 3 @@ -111,8 +111,8 @@ BOOL MainFrameIsActive = FALSE; // HtmlHelp support // -// universal callback for our MessageBox when the user clicks the HELP button -// should be called, for example, like this: +// universal callback for our MessageBox when the user clicks the Help button +// call it, for example, like this: // MSGBOXEX_PARAMS params; // params.Flags = MSGBOXEX_OK | MSGBOXEX_HELP | MSGBOXEX_ICONEXCLAMATION; // params.ContextHelpId = IDH_LICENSE; @@ -178,7 +178,7 @@ BOOL OpenHtmlHelp(char* helpFileName, HWND parent, CHtmlHelpCommand command, DWO !DirExists(helpPath)) { // the directory from the current .slg file does not exist lstrcpyn(helpPath, CurrentHelpDir, MAX_PATH); - if (_stricmp(helpSubdir, "english") == 0 || // we already tested "english" and it does not exist so no point in trying again + if (_stricmp(helpSubdir, "english") == 0 || // we already checked "english" and it does not exist, so there is no point in trying again !SalPathAppend(helpPath, "english", MAX_PATH) || !DirExists(helpPath)) { // the ENGLISH directory does not exist @@ -274,7 +274,7 @@ BOOL OpenHtmlHelp(char* helpFileName, HWND parent, CHtmlHelpCommand command, DWO } } - if (helpFileName != NULL) // plugin help: to open the window in the right position + if (helpFileName != NULL) // plugin help: open the help window in the correct position and restore the Favorites list correctly { // with remembered Favorites, we must open "salamand.chm" first (then // the plugin help opens in this same window) lstrcpyn(helpPath, CurrentHelpDir, MAX_PATH); @@ -366,7 +366,7 @@ class CMWDropTarget : public IDropTarget } STDMETHOD(QueryInterface) - (REFIID refiid, void FAR* FAR* ppv) + (REFIID refiid, void FAR * FAR * ppv) { if (refiid == IID_IUnknown || refiid == IID_IDropTarget) { @@ -389,7 +389,7 @@ class CMWDropTarget : public IDropTarget if (--RefCount == 0) { delete this; - return 0; // cannot touch the object anymore, it no longer exists + return 0; // must not touch the object; it no longer exists } return RefCount; } @@ -705,7 +705,7 @@ BOOL CMainWindow::IsPanelZoomed(BOOL leftPanel) void CMainWindow::ToggleSmartColumnMode(CFilesWindow* panel) { - if (panel->GetViewMode() == vmDetailed) // the panel must be running in detailed mode + if (panel->GetViewMode() == vmDetailed) // the panel must be in detailed mode { if (panel->Columns.Count < 1) return; @@ -822,13 +822,13 @@ BOOL CMainWindow::SHChangeNotifyInitialize() entry.pidl = pidl; entry.fRecursive = TRUE; - // message WM_USER_SHCHANGENOTIFY, which will be delivered to us on notifications, crosses process boundaries - // by using the constant SHCNRF_NewDelivery (also known as SHCNF_NO_PROXY) we assume responsibility - // for accessing the memory passed with the message (via SHChangeNotification_Lock) and tell the OS not to - // create proxy windows (note: a bug has been reported on XP where the proxy window is created but not destroyed): + // The WM_USER_SHCHANGENOTIFY message delivered for these notifications crosses process boundaries. + // By using the SHCNRF_NewDelivery constant (also known as SHCNF_NO_PROXY), we assume responsibility + // for accessing the memory passed with the message (using SHChangeNotification_Lock), and the OS must not + // create proxy windows (note: under XP, a bug was reported where the proxy window is created but not destroyed): // http://groups.google.com/groups?selm=3CDFD449.6BA0CDB4%40ic.ac.uk&output=gplain // - // through SHCNE_ASSOCCHANGED we receive notifications about association changes + // Using SHCNE_ASSOCCHANGED, we receive notifications about association changes. SHChangeNotifyRegisterID = SHChangeNotifyRegister(HWindow, SHCNRF_ShellLevel | SHCNRF_NewDelivery, SHCNE_MEDIAINSERTED | SHCNE_MEDIAREMOVED | SHCNE_DRIVEREMOVED | SHCNE_DRIVEADD | SHCNE_NETSHARE | SHCNE_NETUNSHARE | @@ -865,17 +865,17 @@ BOOL CMainWindow::OnAssociationsChangedNotification(BOOL showWaitWnd) // tweak the icon size LoadSaveToRegistryMutex.Enter(); // users reported shrunken icons, see https://forum.altap.cz/viewtopic.php?t=638 - // this synchronization ensures that two Salamanders do not interfere with each other - // unfortunately the trick with changing "Shell Icon Size" to rebuild the cache is used by many tools (including Tweak UI), - // so if they refresh at the same time as Salamander, conflicts occur - // we try to avoid this by postponing the following mess using IDT_ASSOCIATIONSCHNG + // this synchronization ensures that two Salamander instances do not interfere with each other + // unfortunately, the trick of changing "Shell Icon Size" to rebuild the cache is used by many tools (including Tweak UI), + // so if they refresh at the same time as Salamander, a conflict occurs + // we try to avoid this by delaying the following hack using IDT_ASSOCIATIONSCHNG HKEY hKey; if (HANDLES(RegOpenKeyEx(HKEY_CURRENT_USER, "Control Panel\\Desktop\\WindowMetrics", 0, KEY_READ | KEY_WRITE, &hKey)) == ERROR_SUCCESS) { // older SHELL32.DLL versions may not export this, fileIconInit will be NULL FT_FileIconInit fileIconInit = NULL; - fileIconInit = (FT_FileIconInit)GetProcAddress(Shell32DLL, MAKEINTRESOURCE(660)); // no header available + fileIconInit = (FT_FileIconInit)GetProcAddress(Shell32DLL, MAKEINTRESOURCE(660)); // no header char size[50]; BOOL deleteVal = FALSE; @@ -894,7 +894,7 @@ BOOL CMainWindow::OnAssociationsChangedNotification(BOOL showWaitWnd) deleteVal = TRUE; } int val = atoi(size); - if (val > 0) // unfortunately (according to net) users set icon sizes randomly (72, 96, 128, etc.) so we cannot filter out "strange" sizes + if (val > 0) // unfortunately, users set icon sizes arbitrarily (72, 96, 128, etc.), so we cannot filter out "strange" sizes { IgnoreWM_SETTINGCHANGE = TRUE; @@ -922,7 +922,7 @@ BOOL CMainWindow::OnAssociationsChangedNotification(BOOL showWaitWnd) if (fileIconInit != NULL) fileIconInit(TRUE); - // debug icon display + // icon display for debugging SHFILEINFO shi; HIMAGELIST systemIL = (HIMAGELIST)SHGetFileInfo("C:\\TEST.QWE", 0, &shi, sizeof(shi), SHGFI_SYSICONINDEX | SHGFI_SMALLICON | SHGFI_SHELLICONSIZE); @@ -1249,7 +1249,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = case WM_SETTINGCHANGE: { - if (IgnoreWM_SETTINGCHANGE || LeftPanel == NULL || RightPanel == NULL) // a bug report showed that WM_SETTINGCHANGE was delivered immediately from WM_CREATE of the main window (panels didn't exist yet, causing a NULL access) + if (IgnoreWM_SETTINGCHANGE || LeftPanel == NULL || RightPanel == NULL) // a bug report showed that WM_SETTINGCHANGE can be delivered during WM_CREATE of the main window (the panels did not exist yet, so it crashed on NULL access) return 0; // detection based on EXPLORER.EXE on NT4 @@ -1414,7 +1414,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = HANDLES(LeaveCriticalSection(&TimeCounterSection)); PostMessage(panel->HWindow, WM_USER_REFRESH_DIR, 0, t1); } - if (type == DRIVE_NO_ROOT_DIR) // device disappeared (the drive is invalid) + if (type == DRIVE_NO_ROOT_DIR) // the device disappeared (the drive is invalid) { if (LeftPanel == panel) { @@ -1439,15 +1439,15 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = } /* - // WM_DEVICECHANGE didn't work well, for example under Win XP when connecting the DSC F707 camera. - // A notification about device connection arrived, but the subsequent device name detection + // WM_DEVICECHANGE did not work reliably, for example on Win XP when connecting a DSC F707 camera. + // A device connection notification was delivered, but the subsequent device name detection // (if the Alt+F1/2 menu was displayed) via SHGetFileInfo returned an empty string. - // I found a thread on Google where someone complains about the same problem + // I found a Google thread where someone reported the same problem. // // http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=99a435fa.0203280715.69a286a8%40posting. // google.com&rnum=1&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26q%3Ddevice%2Bname%2Bshgetfileinfo // - // and he solved it with a wait. People recommended abandoning WM_DEVICECHANGE and switching to + // He solved it by waiting. People recommended abandoning WM_DEVICECHANGE and switching to // the undocumented function SHChangeNotifyRegister... // (http://www.geocities.com/SiliconValley/4942/notify.html) case WM_DEVICECHANGE: @@ -1455,7 +1455,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = if (wParam == DBT_DEVICEARRIVAL || wParam == DBT_DEVICEREMOVECOMPLETE || wParam == DBT_CONFIGCHANGED) // CD-ROM media change { - // if the Alt+F1/F2 menu is open, refresh (read volume name) + // if the Alt+F1/F2 menu is open, refresh it (read the volume name) CFilesWindow *panel = GetActivePanel(); if (panel != NULL) PostMessage(MainWindow->HWindow, WM_USER_DRIVES_CHANGE, 0, 0); @@ -1468,7 +1468,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = UINT type = MyGetDriveType(panel->GetPath()); if (type == DRIVE_CDROM || type == DRIVE_REMOVABLE) { - HANDLES(EnterCriticalSection(&TimeCounterSection)); // capture the time when a refresh is needed + HANDLES(EnterCriticalSection(&TimeCounterSection)); // capture the time when the refresh is needed int t1 = MyTimeCounter++; HANDLES(LeaveCriticalSection(&TimeCounterSection)); PostMessage(panel->HWindow, WM_USER_REFRESH_DIR, 0, t1); @@ -1484,8 +1484,8 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = case WM_USER_PROCESSDELETEMAN: { - // delay data processing due to the main window activation after ESC from the viewer on WinXP; - // without this hack, it somehow did not catch up - the main window stayed inactive and the safe-wait window never appeared + // delay data processing because the main window is activated after pressing Esc in the viewer on WinXP + // without this hack, the timing was too tight: the main window stayed inactive, so the safe-wait window was not shown if (!SetTimer(HWindow, IDT_DELETEMNGR_PROCESS, 200, NULL)) DeleteManager.ProcessData(); // if the timer fails, run immediately; forget about WinXP return 0; @@ -1582,9 +1582,9 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = UserMenuIconBkgndReader.BeginUserMenuIconsInUse(); CMenuPopup menu; FillUserMenu(&menu); - // another lock/unlock cycle (BeginUserMenuIconsInUse + EndUserMenuIconsInUse) + // another lock cycle (BeginUserMenuIconsInUse + EndUserMenuIconsInUse) // will occur in WM_USER_ENTERMENULOOP + WM_USER_LEAVEMENULOOP, but - // it is nested and lightweight, so we ignore it and do not fight it + // it is nested and has no overhead, so we ignore it menu.Track(0, r.left, r.bottom, HWindow, &r); UserMenuIconBkgndReader.EndUserMenuIconsInUse(); break; @@ -1680,9 +1680,9 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = iterator++; CMenuPopup menu; FillUserMenu2(&menu, &iterator, endIndex); - // another lock/unlock cycle (BeginUserMenuIconsInUse + EndUserMenuIconsInUse) + // Another lock/unlock cycle (BeginUserMenuIconsInUse + EndUserMenuIconsInUse) // will occur in WM_USER_ENTERMENULOOP + WM_USER_LEAVEMENULOOP, - // but it is nested and lightweight, so we ignore it + // but it is already nested and has no overhead, so we ignore it menu.Track(0, r.left, r.bottom, HWindow, &r); UserMenuIconBkgndReader.EndUserMenuIconsInUse(); } @@ -1728,12 +1728,12 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = { SalamanderBusy = TRUE; // now BUSY LastSalamanderIdleTime = GetTickCount(); - BringWindowToTop(HWindow); // probably not important, but I saw it in a sample so I am adding it here too + BringWindowToTop(HWindow); // probably not important, but it appears in one sample, so add it here too if (IsIconic(HWindow)) { - // SetForegroundWindow: this is crucial. If we don't call it and - // "only one instance" with the tray is active, Salamander sometimes - // appears in the background and only later moves to the front. + // SetForegroundWindow: this is very important. If we do not call it and + // "only one instance" with the tray is enabled, Salamander sometimes + // appears in the background and only later comes to the foreground. SetForegroundWindow(HWindow); ShowWindow(HWindow, SW_RESTORE); } @@ -1771,7 +1771,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = GetCurrentProcess(), &fm, // this process file-mapping 0, FALSE, DUPLICATE_SAME_ACCESS))) { - CSetPathsParams *unsafe = (CSetPathsParams *)HANDLES(MapViewOfFile(fm, FILE_MAP_WRITE, 0, 0, sizeof(CSetPathsParams))); // FIXME_X64 are we passing x86/x64 incompatible data? + CSetPathsParams *unsafe = (CSetPathsParams *)HANDLES(MapViewOfFile(fm, FILE_MAP_WRITE, 0, 0, sizeof(CSetPathsParams))); // FIXME_X64: are x86/x64-incompatible data being passed here? if (unsafe != NULL) { alreadyDone = unsafe->Received; @@ -1782,12 +1782,12 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = if (unsafe->MagicSignature1 == 0x07f2ab13 && unsafe->MagicSignature2 == 0x471e0901) { - // new features since 2.52 - // WORD version = unsafe->StructVersion; // not used yet, the first version is recognized by the presence of signatures + // changes since 2.52 + // WORD version = unsafe->StructVersion; // not used yet, the first version is recognized by the presence of the signatures lstrcpyn(params.ActivePath, unsafe->ActivePath, MAX_PATH); params.ActivatePanel = unsafe->ActivatePanel; } - // we return the result value having taken over the data + // return confirmation that the data were accepted unsafe->Received = TRUE; } HANDLES(UnmapViewOfFile(unsafe)); @@ -1818,9 +1818,9 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = if (IsWindow(hCaller)) { // If the window that invoked us still exists, try to bring it to - // the foreground. This is a bit dirty because if it opens a modal - // dialog in the meantime, it won't get activation. But I don't care, - // the viewer will (hopefully) end up inside Salamander - in the plugin ;-) + // the foreground. This is a bit of a hack, because if it opens a modal + // dialog in the meantime, it will not receive activation. That is acceptable, + // because the viewer will hopefully end up in Salamander, that is, in the plugin. SetForegroundWindow(hCaller); } return 0; @@ -1842,7 +1842,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = UserMenuIconBkgndReader.ResetSysColorsChanged(); // now, we start watching system color changes (icon reload required) BOOL readingUMIcons = UserMenuIconBkgndReader.IsReadingIcons(); - if (readingUMIcons) // new icons are on their way to the user menu; show them after configuration is done (on OK reload icons again so newly added ones are read as well) + if (readingUMIcons) // new icons are being loaded for the user menu; show them only after the configuration is finished (on OK, reload the icons so any newly added ones are loaded too) UserMenuIconBkgndReader.BeginUserMenuIconsInUse(); BOOL oldUseCustomPanelFont = UseCustomPanelFont; LOGFONT oldLogFont = LogFont; @@ -1856,7 +1856,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = IdleRefreshStates = TRUE; // force status variable check on next Idle IdleCheckClipboard = TRUE; // also check the clipboard - if (res == IDOK) // values changed -> refresh everything possible + if (res == IDOK) // values changed -> refresh as much as possible { if (dlg.PageView.IsDirty()) { @@ -1944,10 +1944,10 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = if (HasLockedUI()) break; - // if the user pressed the Alt button while the initial splash window was shown, - // the system menu could be entered before MainWindow appeared and the splash + // if the user pressed Alt while the initial splash window was displayed, + // the system menu of the not-yet-visible MainWindow could be entered and the splash // window remained open until the user pressed Escape - // if MainWindow is not yet visible, disable entering the Window menu + // if MainWindow is not yet visible, disable access to the Window menu if (wParam == SC_KEYMENU && !IsWindowVisible(HWindow)) return 0; @@ -2147,7 +2147,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = if (LOWORD(wParam) >= CM_PLUGINCMD_MIN && LOWORD(wParam) <= CM_PLUGINCMD_MAX) { // command from a plugin menu - // lower the thread priority to "normal" (so operations don't burden the system) + // lower the thread priority to "normal" (so operations do not burden the system) SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); if (Plugins.ExecuteMenuItem(activePanel, HWindow, LOWORD(wParam))) @@ -2344,7 +2344,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = int tgtSelCount = inactivePanel->Is(ptDisk) ? inactivePanel->GetSelItems(2, tgtIndexes) : 0; // interested in: 0-1=number selected, 2=more than one if (selCount == 2) // two selected items in the source panel { - if ((indexes[0] < activePanel->Dirs->Count) == (indexes[1] < activePanel->Dirs->Count)) // both items are files/directories + if ((indexes[0] < activePanel->Dirs->Count) == (indexes[1] < activePanel->Dirs->Count)) // both items are either files or directories { f1 = (indexes[0] < activePanel->Dirs->Count) ? &activePanel->Dirs->At(indexes[0]) : &activePanel->Files->At(indexes[0] - activePanel->Dirs->Count); f2 = (indexes[1] < activePanel->Dirs->Count) ? &activePanel->Dirs->At(indexes[1]) : &activePanel->Files->At(indexes[1] - activePanel->Dirs->Count); @@ -2359,7 +2359,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = userMenuAdvancedData.CompareNamesAreDirs = (indexes[0] < activePanel->Dirs->Count); if (!focusOnUpDir && focus != indexes[0] && tgtSelCount != 1) { - if ((focus < activePanel->Dirs->Count) == userMenuAdvancedData.CompareNamesAreDirs) // both items are files/directories + if ((focus < activePanel->Dirs->Count) == userMenuAdvancedData.CompareNamesAreDirs) // both items are of the same type: either files or directories { f2 = (focus < activePanel->Dirs->Count) ? &activePanel->Dirs->At(focus) : &activePanel->Files->At(focus - activePanel->Dirs->Count); } @@ -2367,7 +2367,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = } else { - if (selCount == 0) // no selected item in the source panel, take the focus + if (selCount == 0) // no item is selected in the source panel, use the focused item { if (!focusOnUpDir) { @@ -3057,7 +3057,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = { ChangePanel(); if (GetActivePanel() != RightPanel) - return 0; // the panel cannot be activated + return 0; // the panel could not be activated UpdateWindow(HWindow); // render the focus before the menu appears } if (RightPanel->DirectoryLine != NULL) @@ -3297,7 +3297,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = char temporarySelected[MAX_PATH]; activePanel->SelectFocusedItemAndGetName(temporarySelected, MAX_PATH); - if (activePanel->Is(ptDisk)) // source is disk - all operations go here + if (activePanel->Is(ptDisk)) // source is a disk; all operations go through here { CActionType type; switch (LOWORD(wParam)) @@ -3324,7 +3324,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = } else { - if (activePanel->Is(ptZIPArchive)) // source is an archive - all operations go here + if (activePanel->Is(ptZIPArchive)) // source is an archive; all operations are handled here { BOOL archMaybeUpdated; activePanel->OfferArchiveUpdateIfNeeded(HWindow, IDS_ARCHIVECLOSEEDIT2, &archMaybeUpdated); @@ -3346,7 +3346,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = } else { - if (activePanel->Is(ptPluginFS)) // source is a FS - all operations go here + if (activePanel->Is(ptPluginFS)) // source is FS - all operations are routed here { CPluginFSActionType type; switch (LOWORD(wParam)) @@ -3613,7 +3613,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = case CM_FINDFILE: { - if (activePanel->Is(ptDisk)) // does Find relate to the current path? (archives and FS not yet) + if (activePanel->Is(ptDisk)) // does Find apply to the current path? (not yet for archives and file systems) { activePanel->UserWorkedOnThisPath = TRUE; } @@ -3902,9 +3902,9 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = FillUserMenu(&menu); POINT p; activePanel->GetContextMenuPos(&p); - // another lock/unlock cycle (BeginUserMenuIconsInUse + EndUserMenuIconsInUse) will occur - // in WM_USER_ENTERMENULOOP + WM_USER_LEAVEMENULOOP, but it is nested and lightweight, - // so we ignore it and do not fight it + // Another lock/unlock cycle (BeginUserMenuIconsInUse + EndUserMenuIconsInUse) + // will occur in WM_USER_ENTERMENULOOP + WM_USER_LEAVEMENULOOP, + // but it is already nested and has no overhead, so we ignore it menu.Track(0, p.x, p.y, HWindow, NULL); UserMenuIconBkgndReader.EndUserMenuIconsInUse(); @@ -3965,7 +3965,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = } else { - if (EditPermanentVisible || EditWindow->IsEnabled()) // there may be an archive in the panel + if (EditPermanentVisible || EditWindow->IsEnabled()) // the panel may contain an archive ShowCommandLine(); } return 0; @@ -4426,7 +4426,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = SendMessage(LeftPanel->HWindow, WM_USER_REFRESH_DIR, 0, t1); SendMessage(RightPanel->HWindow, WM_USER_REFRESH_DIR, 0, t2); - // distribute this news among plug-ins as well + // distribute this news among plugins as well Plugins.Event(PLUGINEVENT_CONFIGURATIONCHANGED, 0); return 0; } @@ -4490,7 +4490,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = case WM_USER_DISPACHCHANGENOTIF: { - if (LastDispachChangeNotifTime < lParam) // not an outdated message + if (LastDispachChangeNotifTime < lParam) // not an old message { if (AlreadyInPlugin || StopRefresh > 0) NeedToResentDispachChangeNotif = TRUE; @@ -4518,7 +4518,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = } else ok = FALSE; - if (!ok) // store the time of the last refresh (still in the critical section) + if (!ok) // store the time of the last dispatch attempt (still in the critical section) { HANDLES(EnterCriticalSection(&TimeCounterSection)); LastDispachChangeNotifTime = MyTimeCounter++; @@ -4526,9 +4526,9 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = } HANDLES(LeaveCriticalSection(&DispachChangeNotifCS)); - if (ok) // distribute a notification about the change on 'path' with 'includingSubdirs' + if (ok) // dispatch a change notification for 'path' with 'includingSubdirs' { - // send the message to all loaded plugins + // dispatch the notification to all loaded plugins Plugins.AcceptChangeOnPathNotification(path, includingSubdirs); if (GetNonActivePanel() != NULL) // non-active panel first (due to timestamps of subdirectory changes on NTFS) @@ -4542,8 +4542,8 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = if (DetachedFSList->Count > 0) { - // for better input/output optimization with plugins, the EnterPlugin/LeavePlugin section - // is exported here (not inside the interface encapsulation) + // to optimize plugin entry/exit, the EnterPlugin/LeavePlugin section + // is moved out here (it is not inside the interface encapsulation) EnterPlugin(); int i; for (i = 0; i < DetachedFSList->Count; i++) @@ -4691,7 +4691,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = popup->SetHotImageList(NULL); // just to be safe, so the popup doesn't own an invalid handle ImageList_Destroy(hIcons); } - if (popupID == CML_PLUGINS) // closing the Plugins menu; dynamic icons can be freed (they are rebuilt before each next menu opening) + if (popupID == CML_PLUGINS) // closing the Plugins menu; the dynamic icons can be freed (they are rebuilt before each subsequent menu opening) Plugins.ReleasePluginDynMenuIcons(); break; } @@ -5200,7 +5200,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = r2.right = r.right; DrawSplitLine(HWindow, -1, DragSplitX, r2); SendMessage(ToolTipWindow.HWindow, TTM_ACTIVATE, FALSE, 0); - DestroyWindow(ToolTipWindow.HWindow); // just detaches the tooltip from the control + DestroyWindow(ToolTipWindow.HWindow); // destroys the tooltip window if (uMsg == WM_LBUTTONUP) { // accept the position only when the drag finishes legally @@ -5599,7 +5599,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = CALL_STACK_MESSAGE4("CPluginInterfaceForMenuExt::ExecuteMenuItem(, , %d,) (%s v. %s)", (int)lParam, data->DLLName, data->Version); - // lower the thread priority to "normal" (so operations don't burden the system) + // lower the thread priority to "normal" (so the operation does not put too much load on the machine) SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); data->GetPluginInterfaceForMenuExt()->ExecuteMenuItem(NULL, HWindow, (int)lParam, 0); @@ -5782,7 +5782,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = MSG msg; CanCloseButInEndSuspendMode = CanClose; BOOL oldCanClose = CanClose; - CanClose = FALSE; // don't let ourselves be closed; we are inside the method + CanClose = FALSE; // do not allow closing while inside this method BOOL postWM_USER_CLOSE_MAINWND = FALSE; BOOL postWM_USER_FORCECLOSE_MAINWND = FALSE; while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) @@ -5954,7 +5954,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = // if (IsWindowVisible(HWindow)) // now handled by FirstActivateApp // { - if (wParam == TRUE) // activating the app + if (wParam == TRUE) // app activation { if (!LeftPanel->DontClearNextFocusName) LeftPanel->NextFocusName[0] = 0; @@ -6171,7 +6171,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = if (uMsg == WM_QUERYENDSESSION && (lParam & ENDSESSION_CRITICAL) != 0) endAfterCleanup = TRUE; // cannot be refused -> perform minimal cleanup else - return 0; // refuse close/shutdown/logoff; a forced shutdown will be detected in WM_ENDSESSION + return 0; // reject close/shutdown/logoff; detect any forced shutdown only in WM_ENDSESSION } } @@ -6205,7 +6205,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = TRACE_E("WM_USER_CLOSE_MAINWND: SalamanderBusy == TRUE!"); if (uMsg == WM_QUERYENDSESSION) TRACE_I("WM_QUERYENDSESSION: cancelling shutdown: SalamanderBusy is TRUE"); - return 0; // refuse close/shutdown/logoff; a forced shutdown will be detected in WM_ENDSESSION + return 0; // Reject close/shutdown/logoff; detect any forced shutdown in WM_ENDSESSION } } } @@ -6266,7 +6266,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = if (uMsg == WM_QUERYENDSESSION) TRACE_I("WM_QUERYENDSESSION: cancelling shutdown: user rejects to close all disk operation progress dialogs"); // the user does not want to exit yet - return 0; // refuse closing/shutdown/logoff; any "forced shutdown" will be detected later in WM_ENDSESSION + return 0; // refuse close/shutdown/logoff; any "forced shutdown" will be detected later in WM_ENDSESSION } UpdateWindow(HWindow); } @@ -6283,7 +6283,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = GetTickCount() - msgArrivalTime <= QUERYENDSESSION_TIMEOUT - 200) Sleep(200); WaitInEndSession = TRUE; - return TRUE; // continue to WM_ENDSESSION where we will either finish or be killed while waiting + return TRUE; // proceed to WM_ENDSESSION, where we either finish or get killed if we wait any longer } int i = 0; @@ -6329,11 +6329,11 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = if (findDlg != NULL) // if the window still exists, we send it a close query (otherwise it is pointless) { BOOL myPost = findDlg->StateOfFindCloseQuery == sofcqNotUsed; - if (myPost) // if this is not nesting (maybe possible, not verified but unlikely) + if (myPost) // if this is not a nested call (probably possible, not investigated, but unlikely) { findDlg->StateOfFindCloseQuery = sofcqSentToFind; PostMessage(destroyArray[i], WM_USER_QUERYCLOSEFIND, 0, - uMsg == WM_QUERYENDSESSION && (lParam & ENDSESSION_CRITICAL) != 0); // during critical shutdown we don't ask, we just cancel + uMsg == WM_QUERYENDSESSION && (lParam & ENDSESSION_CRITICAL) != 0); // during critical shutdown, do not ask and cancel immediately } BOOL cont = TRUE; while (cont) @@ -6406,7 +6406,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = // window size and a few other minor things won't be saved, but we ignore that) // note: the !endAfterCleanup check here is unnecessary because outside critical shutdown // endAfterCleanup is always FALSE - if (uMsg != WM_QUERYENDSESSION || (lParam & ENDSESSION_CRITICAL) == 0) // mimo criticky shutdown + if (uMsg != WM_QUERYENDSESSION || (lParam & ENDSESSION_CRITICAL) == 0) // except during critical shutdown { for (i = 0; i < destroyArray.Count; i++) { @@ -6456,7 +6456,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = Sleep(200); WaitInEndSession = TRUE; - return TRUE; // continue to WM_ENDSESSION where we finish or are killed if we wait longer + return TRUE; // Proceed to WM_ENDSESSION, where we finish or are terminated if we wait longer. } if (uMsg == WM_QUERYENDSESSION && (lParam & ENDSESSION_CRITICAL) != 0) // this applies to Vista+ @@ -6483,7 +6483,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = } BOOL backupOK = FALSE; - if (cfgOK) // old configuration seems OK; back it up in case saving the new configuration fails + if (cfgOK) // the old configuration seems OK; back it up in case saving the configuration fails { char backup[200]; sprintf_s(backup, "%s.backup.63A7CD13", SALAMANDER_ROOT_REG); // "63A7CD13" prevents the key name from matching a user key @@ -6514,14 +6514,14 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = GetTickCount() - msgArrivalTime <= QUERYENDSESSION_TIMEOUT - 200) Sleep(200); - if (backupOK) // backup done, configuration will be saved in WM_ENDSESSION, - SaveCfgInEndSession = TRUE; // if we get killed during it, the configuration will load from the backup + if (backupOK) // backup is ready; the configuration will be saved in WM_ENDSESSION, + SaveCfgInEndSession = TRUE; // if we are killed during this, the configuration will be loaded from the backup else { // EndStopRefresh(); // during critical shutdown we don't end stop-refresh (refreshes are sent to panels) WaitInEndSession = TRUE; // backup failed, we won't risk saving the configuration } - return TRUE; // we want 5s in WM_ENDSESSION, so return TRUE + return TRUE; // we want 5 seconds in WM_ENDSESSION, so return TRUE } if ((uMsg == WM_QUERYENDSESSION || uMsg == WM_ENDSESSION) && HLanguage != NULL && @@ -6534,7 +6534,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = CWaitWindow analysing(HWindow, IDS_SAVINGCONFIGURATION, FALSE, ooStatic, TRUE); HWND oldPluginMsgBoxParent = PluginMsgBoxParent; BOOL shutdown = uMsg == WM_QUERYENDSESSION || uMsg == WM_ENDSESSION; - if (shutdown) // during shutdown/log-off/restart show a wait window for all Saves (including plugins) and process the message loop (so we aren't marked as "not responding" and killed early) + if (shutdown) // During shutdown/logoff/restart, show a wait window for all save operations (including plugins) and process the message loop so we are not marked as "not responding" and terminated prematurely. { // start a thread that will handle registry work while saving the configuration; // meanwhile this (main) thread will pump messages in the message loop @@ -6580,7 +6580,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = if (uMsg == WM_QUERYENDSESSION || uMsg == WM_ENDSESSION) MyShutdownBlockReasonDestroy(HWindow); - if (uMsg != WM_ENDSESSION) // during critical shutdown we don't end stop-refresh (refreshes are sent to the panels) + if (uMsg != WM_ENDSESSION) // During a critical shutdown, do not end stop-refresh; refreshes are being dispatched to the panels. { EndStopRefresh(); return 0; // refuse close/shutdown/logoff; any "forced shutdown" will be detected in WM_ENDSESSION @@ -6602,7 +6602,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = reason + (int)strlen(reason), BUG_REPORT_REASON_MAX - ((int)strlen(reason) + 1)) > 0) { // ask whether Salamander should continue or generate a bug report - if (CriticalShutdown || // during critical shutdown there's no point in asking anything, let the system terminate us quietly + if (CriticalShutdown || // during a critical shutdown, do not prompt; allow the system to terminate us SalMessageBox(shutdown ? analysing.HWindow : HWindow, LoadStr(IDS_SHELLEXTBREAK3), SALAMANDER_TEXT_VERSION, MSGBOXEX_CONTINUEABORT | MB_ICONINFORMATION) != IDABORT) @@ -6627,7 +6627,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = { BOOL canClose = FALSE; BOOL detachFS1, detachFS2; - if (LeftPanel->PrepareCloseCurrentPath(shutdown ? analysing.HWindow : LeftPanel->HWindow, TRUE, FALSE, detachFS1, FSTRYCLOSE_UNLOADCLOSEFS /* unnecessary - plugins (including FS) already unloaded */)) + if (LeftPanel->PrepareCloseCurrentPath(shutdown ? analysing.HWindow : LeftPanel->HWindow, TRUE, FALSE, detachFS1, FSTRYCLOSE_UNLOADCLOSEFS /* unnecessary - plugins (including FS) are already unloaded */)) { if (RightPanel->PrepareCloseCurrentPath(shutdown ? analysing.HWindow : RightPanel->HWindow, TRUE, FALSE, detachFS2, FSTRYCLOSE_UNLOADCLOSEFS /* unnecessary - plugins (including FS) already unloaded */)) { @@ -6636,7 +6636,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = RightPanel->SleepIconCacheThread(); RightPanel->CloseCurrentPath(shutdown ? analysing.HWindow : RightPanel->HWindow, FALSE, detachFS2, FALSE, FALSE, TRUE); // close the right panel - // protect the list box from errors caused by redraw requests (we just cut its data) + // protect the list box against errors caused by redraw requests (we just cut off its data) RightPanel->ListBox->SetItemsCount(0, 0, 0, TRUE); RightPanel->SelectedCount = 0; // If WM_USER_UPDATEPANEL is delivered, the panel contents are redrawn @@ -6651,7 +6651,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = LeftPanel->SleepIconCacheThread(); LeftPanel->CloseCurrentPath(shutdown ? analysing.HWindow : LeftPanel->HWindow, FALSE, detachFS1, FALSE, FALSE, TRUE); // close the left panel - // Protect the list box from errors caused by redraw requests (after we just cut the data) + // Protect the list box from errors caused by redraw requests (we have just cut off its data) LeftPanel->ListBox->SetItemsCount(0, 0, 0, TRUE); LeftPanel->SelectedCount = 0; // If WM_USER_UPDATEPANEL is delivered, the panel contents are redrawn @@ -6710,7 +6710,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = DiskCache.PrepareForShutdown(); // clean any empty tmp directories from disk // if (TipOfTheDayDialog != NULL) - // DestroyWindow(TipOfTheDayDialog->HWindow); // the dialog already saved its data (transfer happens there at runtime) + // DestroyWindow(TipOfTheDayDialog->HWindow); // the dialog has already saved its data (transfer happens there at runtime) MainWindowCS.SetClosed(); @@ -6815,7 +6815,7 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = // some crazy shell extension has just called DestroyWindow on Salamander's main window MSG msg; // flush the message queue (WMP9 buffered Enter and dismissed our OK) - // while (PeekMessage(&msg, HWindow, 0, 0, PM_REMOVE)); // Petr: I replaced it by discarding key messages only; without TranslateMessage and DispatchMessage we risk an endless loop (discovered during unloading Automation with memory leaks; before showing the leak message box, an infinite loop occurred because WM_PAINT kept being added to the queue and we kept discarding it) + // while (PeekMessage(&msg, HWindow, 0, 0, PM_REMOVE)); // Petr: replaced this with discarding only keyboard messages; without TranslateMessage and DispatchMessage, an infinite loop can occur (found while unloading Automation with memory leaks; before displaying the leak message box, WM_PAINT kept being added to the queue and we kept discarding it) while (PeekMessage(&msg, NULL, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE)) ; @@ -6947,15 +6947,15 @@ MENU_TEMPLATE_ITEM AddToSystemMenu[] = } if (uMouseMsg == WM_RBUTTONDOWN) { - /* used by the export_mnu.py script which generates salmenu.mnu for the Translator; + /* used by the export_mnu.py script, which generates salmenu.mnu for Translator; keep synchronized with the InsertMenu() call below... -MENU_TEMPLATE_ITEM TaskBarIconMenu[] = -{ - {MNTT_PB, 0 - {MNTT_IT, IDS_CONTEXTMENU_EXIT - {MNTT_PE, 0 -}; -*/ + MENU_TEMPLATE_ITEM TaskBarIconMenu[] = + { + {MNTT_PB, 0 + {MNTT_IT, IDS_CONTEXTMENU_EXIT + {MNTT_PE, 0 + }; + */ HMENU hMenu = CreatePopupMenu(); InsertMenu(hMenu, 0, MF_BYPOSITION | MF_STRING, CM_EXIT, LoadStr(IDS_CONTEXTMENU_EXIT)); @@ -6997,7 +6997,7 @@ MENU_TEMPLATE_ITEM TaskBarIconMenu[] = int count = activePanel->GetSelCount(); if (count != 0) { - // determine the index of the nth (index) selected item + // get the index of the nth selected item int totalCount = activePanel->Dirs->Count + activePanel->Files->Count; if (totalCount == 0 || index >= totalCount) return 0; diff --git a/src/mainwnd4.cpp b/src/mainwnd4.cpp index d545c40ce..6e6bf89c8 100644 --- a/src/mainwnd4.cpp +++ b/src/mainwnd4.cpp @@ -129,7 +129,7 @@ BOOL CMainWindow::CloseDetachedFS(HWND parent, CPluginFSInterfaceEncapsulation* CALL_STACK_MESSAGE1("CMainWindow::CloseDetachedFS()"); BOOL dummy; // ignored return value if (!detachedFS->TryCloseOrDetach(CriticalShutdown, FALSE, dummy, FSTRYCLOSE_UNLOADCLOSEDETACHEDFS) && - !CriticalShutdown) // test close; forceClose==TRUE only during a "critical shutdown" + !CriticalShutdown) // try closing; forceClose==TRUE only during a "critical shutdown" { // ask the user whether to close it even against the FS wishes char path[2 * MAX_PATH]; strcpy(path, detachedFS->GetPluginFSName()); @@ -146,7 +146,7 @@ BOOL CMainWindow::CloseDetachedFS(HWND parent, CPluginFSInterfaceEncapsulation* detachedFS->TryCloseOrDetach(TRUE, FALSE, dummy, FSTRYCLOSE_UNLOADCLOSEDETACHEDFS); } else - return FALSE; // user doesn't want to close the detached FS + return FALSE; // the user chose not to close the detached FS } // close the FS @@ -171,12 +171,12 @@ BOOL CMainWindow::CanUnloadPlugin(HWND parent, CPluginInterfaceAbstract* plugin) if (RightPanel != NULL && !RightPanel->CanUnloadPlugin(parent, plugin)) return FALSE; - // find detached FS belonging to the plug-in 'plugin' and attempt to close them + // find detached FS belonging to the plugin 'plugin' and attempt to close them int i; for (i = DetachedFSList->Count - 1; i >= 0; i--) // iterate backwards; as we will be deleting from the array (quadratic complexity) { CPluginFSInterfaceEncapsulation* detachedFS = DetachedFSList->At(i); - if (detachedFS->GetPluginInterface() == plugin) // belongs to plug-in 'plugin' + if (detachedFS->GetPluginInterface() == plugin) // belongs to plugin 'plugin' { if (CloseDetachedFS(parent, detachedFS)) { @@ -185,16 +185,16 @@ BOOL CMainWindow::CanUnloadPlugin(HWND parent, CPluginInterfaceAbstract* plugin) DetachedFSList->ResetState(); } else - return FALSE; // unload cannot proceed (user refused to close the plug-in's detached FS) + return FALSE; // unload cannot proceed (user refused to close the plugin's detached FS) } } // check if data from the plugin is not in SalShExtPastedData - // (panels leaving archives might have stored them there due to plug-in unload) + // (panels leaving archives might have stored them there due to plugin unload) if (!SalShExtPastedData.CanUnloadPlugin(parent, plugin)) return FALSE; // unload cannot proceed - return TRUE; // unload is possible; all plug-in resources were released + return TRUE; // unload can proceed; all plugin resources have been released } void CMainWindow::MakeFileList() @@ -393,7 +393,7 @@ BOOL GetNextFileFromPanel(int index, char* path, char* name, void* param) { name[0] = 0; // for up-dir or for the first item of an empty panel the name will be empty... } - else // copy the name for others + else // otherwise copy the name { CFileData* f = &((index < data->Window->Dirs->Count) ? data->Window->Dirs->At(index) : data->Window->Files->At(index - data->Window->Dirs->Count)); strcpy(name, f->Name); @@ -427,27 +427,27 @@ BOOL GetNextFileFromPanel(int index, char* path, char* name, void* param) BOOL CheckIfCanBeExecuted(BOOL buildBat, int commandLen, int argumentsLen) { - /* MEASURED LIMITS: - Batch file: - W2K: 2041 including executable name, spaces and parameters - XP64/XP: 8185 including executable name, spaces and parameters - Win7/Vista: 32776 including executable name, spaces and parameters - - ShellExecuteEx: - XP/XP64/Vista/W2K: 2080 including executable name (without quotes), spaces and parameters - Win7: 32764 including executable name (without quotes), spaces and parameters -*/ - - // WARNING: if a .bat file is executed that runs a .exe and passes all parameters (%*), a long .exe name - // can still trigger "too long name" error even when respecting the limit here. The limit is exceeded once - // parameters are passed to the .exe. (I wouldn't solve this issue; it would require parsing - // .bat files etc., which is just nonsense.) + /* MEASURED VALUES: + Batch file: + W2K: 2041 including the executable name, spaces, and parameters + XP64/XP: 8185 including the executable name, spaces, and parameters + Win7/Vista: 32776 including the executable name, spaces, and parameters + + ShellExecuteEx: + XP/XP64/Vista/W2K: 2080 including the executable name (without quotes), spaces, and parameters + Win7: 32764 including the executable name (without quotes), spaces, and parameters + */ + + // WARNING: if a .bat file is executed that runs a .exe and passes all parameters (%*), + // a longer .exe name than the .bat file name can still trigger a "too long name" error even when the + // limit given here is respected. The limit is exceeded after the parameters are expanded for the .exe. + // This problem would not be addressed; it would require parsing .bat files, which is not worth it. int cmdLineLen = commandLen + argumentsLen + 1; // +1 for the space between command and arguments if (buildBat) // launching via a .bat file { if (WindowsVistaAndLater) - return cmdLineLen <= 8191; // Vista/Win7: in reality it's 32776 but only 8191 works (with longer parameters, probably due to a Windows bug, characters get erased; tested on Vista and Win7) + return cmdLineLen <= 8191; // Vista/Win7: in reality the limit is 32776, but only 8191 works (with longer parameters, characters are apparently erased due to a Windows bug; tested on Vista and Win7) return cmdLineLen <= 8185; // XP/XP64 } else // launching via ShellExecuteEx @@ -464,18 +464,18 @@ BOOL CheckIfCanBeExecuted(BOOL buildBat, int commandLen, int argumentsLen) // // parent - parent window (for error dialogs) // cmd - buffer for the expanded command -// cmdSize - size of 'cmd' buffer +// cmdSize - size of the 'cmd' buffer // args - buffer for receiving arguments -// argsSize - size of 'args' buffer +// argsSize - size of the 'args' buffer // buildBat - if TRUE, arguments are placed into 'cmd' -// initDir - buffer for the path where the execution should take place -// initDirSize - length of initDir buffer +// initDir - buffer for the path where execution should take place +// initDirSize - length of the initDir buffer // item - user-menu item // path - long path to the file // longName - long filename // fileNameUsed - returns TRUE if a file name or path was used during argument expansion -// userMenuAdvancedData - advanced parameter`s values for User Menu: the Arguments array -// ignoreEnvVarNotFoundOrTooLong - see ExpandVarString description +// userMenuAdvancedData - values of the advanced parameters for User Menu: the Arguments field +// ignoreEnvVarNotFoundOrTooLong - see the ExpandVarString description // // returns success of the operation @@ -844,7 +844,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = strcpy(prevInitDir, initDir); BOOL expandOK = ExpandCommand2(parent, cmdLine, USRMNUCMDLINE_MAXLEN, - arguments, USRMNUARGS_MAXLEN, buildBat, // if we are running via a batch file, allow + arguments, USRMNUARGS_MAXLEN, buildBat, // when running via a batch file, initDir, MAX_PATH, // arguments will be inserted into cmdLine UserMenuItems->At(itemIndex), path, name, &fileNameUsed, @@ -882,7 +882,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = break; } } - else // direct execution + else // run directly { // the original launching via CreateProcess couldn't run screen savers (*.SCR) // or Control Panel items (*.cpl) and people kept complaining @@ -893,15 +893,15 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = // set correct default directories for individual drives MainWindow->SetDefaultDirectories((initDir[0] != 0) ? initDir : NULL); - // to work with old configurations, remove the " character from the start and end of cmdLine + // to support old configurations, remove the '"' character from the beginning and end of cmdLine int cmdLen = (int)strlen(cmdLine); if (cmdLen > 1 && cmdLine[0] == '\"' && cmdLine[cmdLen - 1] == '\"') { memmove(cmdLine, cmdLine + 1, cmdLen - 2); cmdLine[cmdLen - 2] = 0; } - // better not swallow backslashes so that we don't destroy some OLE paths - //RemoveRedundantBackslahes(cmdLine); // ShellExecuteEx dislikes multiple backslashes, "$(SalDir)\salamand.exe" + // It is better not to strip backslashes so we do not break some OLE paths + //RemoveRedundantBackslahes(cmdLine); // ShellExecuteEx does not like multiple backslashes, "$(SalDir)\salamand.exe" CShellExecuteWnd shellExecuteWnd; SHELLEXECUTEINFO sei; @@ -997,7 +997,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = HANDLES(CloseHandle(pi.hThread)); } } - else // an empty .BAT is not worth running (in case of low memory or other crazy errors) + else // an empty .BAT is not worth running (in case of low memory or other serious errors) { DiskCache.ReleaseName(batUniqueName, FALSE); } @@ -1053,7 +1053,7 @@ BOOL CMainWindow::HandleCtrlLetter(char c) else // NC + Windows Ctrl+? hotkeys { WPARAM cmd; - switch (c) // only upper-case characters reach here + switch (c) // only uppercase characters are handled here { case 'A': cmd = CM_ACTIVESELECTALL; @@ -1842,8 +1842,8 @@ BOOL CMainWindow::ProcessHelpMsg(MSG& msg, DWORD* pContext, HWND* hDirtyWindow) return FALSE; } ReleaseCapture(); - // the message we peeked changes into a non-client because - // of the release capture. + // the message we peeked becomes a non-client message because + // capture is released. GetMessage(&msg, NULL, WM_NCLBUTTONDOWN, WM_NCLBUTTONDOWN); DispatchMessage(&msg); GetCursorPos(&point); @@ -1885,7 +1885,7 @@ BOOL CMainWindow::ProcessHelpMsg(MSG& msg, DWORD* pContext, HWND* hDirtyWindow) // Hit one of our apps windows (or desktop) -- dispatch the message. PeekMessage(&msg, NULL, msg.message, msg.message, PM_REMOVE); - // Dispatch mouse messages that hit the desktop! + // Dispatch mouse messages to the desktop. DispatchMessage(&msg); } } @@ -1903,8 +1903,8 @@ BOOL CMainWindow::ProcessHelpMsg(MSG& msg, DWORD* pContext, HWND* hDirtyWindow) { GetMessage(&msg, NULL, msg.message, msg.message); - // ensure sending messages to our menu (avoiding the need for a keyboard hook) - // this supports entering the menu via Alt/F10/Alt+letter during help mode + // ensure that messages are delivered to our menu (avoiding the need for a keyboard hook) + // this allows entry into the menu via Alt/F10/Alt+letter during help mode if (MenuBar == NULL || !MenuBar->IsMenuBarMessage(&msg)) { TranslateMessage(&msg); diff --git a/src/mainwnd5.cpp b/src/mainwnd5.cpp index ccbaaaef8..84d70240c 100644 --- a/src/mainwnd5.cpp +++ b/src/mainwnd5.cpp @@ -17,7 +17,7 @@ void GetFileDateAndTimeFromPanel(DWORD validFileData, CPluginDataInterfaceEncaps *validDate = FALSE; *validTime = FALSE; FILETIME ft; - if (validFileData & (VALID_DATA_DATE | VALID_DATA_TIME)) // at least something is in LastWrite + if (validFileData & (VALID_DATA_DATE | VALID_DATA_TIME)) // LastWrite contains at least the date or time { if (FileTimeToLocalFileTime(&f->LastWrite, &ft) && FileTimeToSystemTime(&ft, st)) @@ -40,14 +40,14 @@ void GetFileDateAndTimeFromPanel(DWORD validFileData, CPluginDataInterfaceEncaps { *validTime = TRUE; } - if (!*validDate) // no date set, reset it... + if (!*validDate) // no date set, initialize it to the default date... { st->wYear = 1602; st->wMonth = 1; st->wDay = 1; st->wDayOfWeek = 2; } - if (!*validTime) // no time set, reset it... + if (!*validTime) // no time set, zero it out... { st->wHour = 0; st->wMinute = 0; @@ -99,10 +99,10 @@ int CompareFilesByTime(CFilesWindow* leftPanel, const CFileData* l, BOOL lFAT, FILETIME lf, rf; if (Configuration.UseTimeResolution) { - // trim time with second precision + // truncate time to whole seconds stLeft.wMilliseconds = 0; stRight.wMilliseconds = 0; - // convert time to numbers + // convert times to numeric values if (!SystemTimeToFileTime(&stLeft, &lf)) { TRACE_E("CompareFilesByTime(): date&time of left file is invalid!"); @@ -162,7 +162,7 @@ int CompareFilesByTime(CFilesWindow* leftPanel, const CFileData* l, BOOL lFAT, { if (lFAT == rFAT) res = MyCompareFileTime(&lf, &rf, foundDSTShifts, compResNoDSTShiftIgn); // same filesystems -> OK - else // FAT plus a different filesystem -> adjust the non-FAT time to FAT time (by 2 seconds) + else // FAT + different filesystem -> convert the non-FAT time to FAT time (2-second resolution) { WORD date, time; // FAT values FILETIME t; @@ -257,16 +257,16 @@ int CompareFilesBySize(CFilesWindow* leftPanel, CFileData* l, CFilesWindow* righ return 0; } -// compares files 'file1' and 'file2' specified by full path by their content -// on successful comparison, it returns TRUE and sets 'different' -// variable (TRUE if a difference was found, otherwise FALSE) -// on error or user abort, returns FALSE and sets 'canceled' variable -// (TRUE if the user canceled the operation, otherwise FALSE) +// compares the contents of files 'file1' and 'file2', specified by full paths +// on successful comparison, the function returns TRUE and sets +// 'different' (TRUE if a difference was found, otherwise FALSE) +// on error or cancellation, it returns FALSE and sets +// 'canceled' (TRUE if the user canceled the operation, otherwise FALSE) #define COMPARE_BUFFER_SIZE (2 * 1024 * 1024) // buffer size for comparison in bytes (does not necessarily need to be fully used) #define COMPARE_BLOCK_SIZE (32 * 1024) // size of a block read continuously from the file; NOTE: COMPARE_BUFFER_SIZE must be divisible by COMPARE_BLOCK_SIZE #define COMPARE_BLOCK_GROUP 8 // how many blocks can be read at once when reading is fast enough (more than 1 MB/s, see COMPARE_BUF_TIME_LIMIT); NOTE: the number of blocks in the buffer (COMPARE_BUFFER_SIZE / COMPARE_BLOCK_SIZE) must be divisible by COMPARE_BLOCK_GROUP -#define COMPARE_BUF_TIME_LIMIT 2000 // time limit in milliseconds for reading the entire buffer (COMPARE_BUFFER_SIZE) - if met, blocks are read in groups COMPARE_BLOCK_GROUP which speeds up network reading on Vista+ 2-3x; otherwise reading is done block by block (COMPARE_BLOCK_SIZE) +#define COMPARE_BUF_TIME_LIMIT 2000 // time limit in milliseconds for reading the entire buffer (COMPARE_BUFFER_SIZE) - if met, blocks are read in groups of COMPARE_BLOCK_GROUP, which makes network reading on Vista+ 2x to 3x faster; otherwise, reading is done one block at a time (COMPARE_BLOCK_SIZE) void AddProgressSizeWithLimit(CCmpDirProgressDialog* progressDlg, DWORD read, CQuadWord* fileProgressTotal, const CQuadWord& sizeLimit) { @@ -324,7 +324,7 @@ BOOL CompareFilesByContent(HWND hWindow, CCmpDirProgressDialog* progressDlg, // DWORD measureStart = GetTickCount(); // unsigned __int64 measuredSize = 0; BOOL readErr = FALSE; - BOOL readingIsFast1 = FALSE; // FALSE = wait until speed reaches the limit and we can read in groups (COMPARE_BLOCK_GROUP) + BOOL readingIsFast1 = FALSE; // FALSE = wait until the speed reaches the limit and we can read in groups (COMPARE_BLOCK_GROUP) BOOL readingIsFast2 = FALSE; while (TRUE) { @@ -374,7 +374,7 @@ BOOL CompareFilesByContent(HWND hWindow, CCmpDirProgressDialog* progressDlg, } if (readErr || *canceled) break; - readingIsFast1 = WindowsVistaAndLater && // on W2K/XP this should not speed things up, so we will not tempt fate + readingIsFast1 = WindowsVistaAndLater && // on W2K/XP this should not make things faster, so we will not try it there GetTickCount() - readBegTime < (DWORD)(((unsigned __int64)read1 * COMPARE_BUF_TIME_LIMIT) / COMPARE_BUFFER_SIZE); // measure the speed so it is over 1 MB/s /* // read the entire buffer at once from one file (on Vista, when both files are on the same physical disk and the buffer is large, this is slightly faster than reading in 32KB blocks) @@ -446,7 +446,7 @@ BOOL CompareFilesByContent(HWND hWindow, CCmpDirProgressDialog* progressDlg, } if (readErr || ret || *canceled) break; - readingIsFast2 = WindowsVistaAndLater && // on W2K/XP this should not speed things up, so we will not tempt fate + readingIsFast2 = WindowsVistaAndLater && // on W2K/XP this should not make things faster, so we will not try it there GetTickCount() - readBegTime < (DWORD)(((unsigned __int64)read2 * COMPARE_BUF_TIME_LIMIT) / COMPARE_BUFFER_SIZE); // measure the speed so it is over 1 MB/s /* // read the entire buffer at once from one file (on Vista, when both files are on the same physical disk and the buffer is large, this is slightly faster than reading in 32KB blocks) @@ -720,7 +720,7 @@ BOOL ReadDirsAndFilesAux(HWND hWindow, DWORD flags, CCmpDirProgressDialog* progr if (zipFiles == NULL || zipDirs == NULL) { *canceled = TRUE; - return FALSE; // low memory, bail out + return FALSE; // low memory, abort } files->SetDeleteData(FALSE); // shallow data copies only @@ -737,7 +737,7 @@ BOOL ReadDirsAndFilesAux(HWND hWindow, DWORD flags, CCmpDirProgressDialog* progr { TRACE_E(LOW_MEMORY); *canceled = TRUE; - return FALSE; // low memory, bail out + return FALSE; // low memory, abort } } } @@ -752,7 +752,7 @@ BOOL ReadDirsAndFilesAux(HWND hWindow, DWORD flags, CCmpDirProgressDialog* progr { TRACE_E(LOW_MEMORY); *canceled = TRUE; - return FALSE; // low memory, bail out + return FALSE; // low memory, abort } } } @@ -767,16 +767,16 @@ BOOL ReadDirsAndFilesAux(HWND hWindow, DWORD flags, CCmpDirProgressDialog* progr return TRUE; } -// recursive function searching for differences between directories -// directories are determined by the paths in the left and right panel -// and the variables 'leftSubDir' and 'rightSubDir' -// leftFAT and rightFAT indicate whether the respective panel is on a FAT system; if an archive is opened, -// the corresponding xxxFAT will be set to FALSE -// 'flags' specifies comparison criteria and comes from the COMPARE_DIRECTORIES_xxx family -// the function returns TRUE on successful comparison and sets 'different' (TRUE +// recursive function that searches for differences between directories +// the directories are specified by the paths in the left and right panels +// and by the variables 'leftSubDir' and 'rightSubDir' +// leftFAT and rightFAT indicate whether the corresponding panel is on a FAT file system; if an archive is open, +// the corresponding xxxFAT is set to FALSE +// 'flags' specifies the comparison criteria and comes from the COMPARE_DIRECTORIES_xxx family +// the function returns TRUE if the comparison succeeds and sets 'different' (TRUE // if the directories differ, otherwise FALSE). -// on error or user abort it returns FALSE -// and sets the variable 'canceled' (TRUE if aborted by the user, otherwise FALSE) +// if an error occurs or the operation is canceled by the user, the function returns FALSE +// and sets the variable 'canceled' (TRUE if canceled by the user, otherwise FALSE) // supports ptDisk and ptZIPArchive @@ -961,7 +961,7 @@ BOOL CompareDirsAux(HWND hWindow, CCmpDirProgressDialog* progressDlg, // directories are not compared by time } - if (timeDiffWithDSTShiftExists) // we found no other difference, so we report an unignored DST time shift including a warning + if (timeDiffWithDSTShiftExists) // no other difference found, so report the non-ignored DST time shift including a warning { (*foundDSTShifts)++; *different = TRUE; @@ -1071,7 +1071,7 @@ BOOL CompareDirsAux(HWND hWindow, CCmpDirProgressDialog* progressDlg, if (*different) { *foundDSTShifts += foundDSTShiftsInSubDir; - return TRUE; // found a difference in a subdirectory, stop + return TRUE; // found a difference in a subdirectory, return early } foundDSTShiftsInThisDir += foundDSTShiftsInSubDir; } @@ -1182,7 +1182,7 @@ void CMainWindow::CompareDirectories(DWORD flags) // lower the thread priority to "normal" (so the operation doesn't overburden the machine) SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); - //--- open the progress dialog + //--- open the progress dialog box BOOL displayDialogBox = (flags & COMPARE_DIRECTORIES_BYCONTENT) != 0 || // for quick actions there's no point in showing the dialog (flags & COMPARE_DIRECTORIES_SUBDIRS) != 0; BOOL displayProgressBar = (flags & COMPARE_DIRECTORIES_BYCONTENT) != 0; @@ -1251,9 +1251,9 @@ void CMainWindow::CompareDirectories(DWORD flags) getTotal = FALSE; // FALSE: we mark differences, compare files by content CQuadWord total(0, 0); // total number of bytes that may need to be compared in the worst case - // the 'dirSubTotal' array contains sizes of individual subdirectories (files contained in them) + // the 'dirSubTotal' array contains the sizes of individual subdirectories (the files they contain) // the array is filled in the first pass (getTotal == TRUE) - // it is used in the second pass (getTotal == FALSE): if a subdirectory differs we know how much to skip on the total progress + // it is used in the second pass (getTotal == FALSE): if a subdirectory differs, we know how much to skip in the total progress TDirectArray dirSubTotal(max(1, min(leftDirs->Count, rightDirs->Count)), 1); int subTotalIndex; // index into the dirSubTotal array @@ -1352,7 +1352,7 @@ void CMainWindow::CompareDirectories(DWORD flags) // By Content if (flags & COMPARE_DIRECTORIES_BYCONTENT) { - if (leftFile->Size == rightFile->Size) // size test is intentionally not covered by the following optimization so both files are marked and unnecessary DST warnings don't pop up + if (leftFile->Size == rightFile->Size) // the size check is intentionally not gated by the following optimization condition so both files are marked and unnecessary DST warnings do not pop up { if (!selectLeft && !leftIsNewer || !selectRight && !rightIsNewer) // if both files are already flagged, there is no point in comparing them by content { @@ -1412,7 +1412,7 @@ void CMainWindow::CompareDirectories(DWORD flags) if (!getTotal) { if (leftIsNewerNoDSTShiftIgn && !selectLeft || rightIsNewerNoDSTShiftIgn && !selectRight) - foundDSTShifts += isDSTShift; // count only time differences of files that are not already marked for another reason (e.g., due to a difference by another criterion) -- motivation: if we don't need to show a complex DST warning, don't show it + foundDSTShifts += isDSTShift; // count only time differences for files that are not already marked for another reason (e.g. because of a difference by another criterion) -- motivation: if the complex DST warning does not need to be shown, do not show it if (selectLeft || leftIsNewer) { @@ -1459,8 +1459,8 @@ void CMainWindow::CompareDirectories(DWORD flags) } // Sal2.0 and TC compare without directories in such a way that they even ignore their names - // people kept pointing this out to us, so we'll behave the same (with - // COMPARE_DIRECTORIES_ONEPANELDIRS disabled) + // this behavior is kept for compatibility because users kept pointing it out + // (when COMPARE_DIRECTORIES_ONEPANELDIRS is not set) if ((flags & COMPARE_DIRECTORIES_SUBDIRS) || (flags & COMPARE_DIRECTORIES_ONEPANELDIRS)) { // now compare subdirectories @@ -1853,14 +1853,14 @@ BOOL CDynString::Append(const char* str, int len) len = (int)strlen(str); if (Length + len >= Allocated) { - int size = Length + len + 1 + 256; // +256 characters as reserve so we don't allocate so often + int size = Length + len + 1 + 256; // +256 characters in reserve so reallocations are less frequent char* newBuf = (char*)realloc(Buffer, size); if (newBuf != NULL) { Buffer = newBuf; Allocated = size; } - else // out of memory, tough luck... + else // Out of memory. { TRACE_E(LOW_MEMORY); return FALSE; diff --git a/src/mapi.cpp b/src/mapi.cpp index 6e22fb383..0fe7a6f75 100644 --- a/src/mapi.cpp +++ b/src/mapi.cpp @@ -28,9 +28,9 @@ BOOL CSimpleMAPI::Init(HWND hParent) HLibrary = HANDLES_Q(LoadLibrary("mapi32.dll")); if (HLibrary == NULL) { - // under NT4.0 US + IE 4.01 US, mapi32.dll is not installed - // but I found msoemapi.dll there which has the necessary export and more importantly, it works, - // so why not try it... + // Under NT 4.0 US + IE 4.01 US, mapi32.dll is not installed, + // but I found msoemapi.dll there. It has the required export and, + // more importantly, it works, so it is worth trying. HLibrary = HANDLES_Q(LoadLibrary("msoemapi.dll")); if (HLibrary == NULL) { @@ -144,7 +144,7 @@ BOOL CSimpleMAPI::SendMail() message.nFileCount = FileNames.Count; message.lpFiles = fileDesc; - char* subject = (char*)malloc(subjectSize + strlen(LoadStr(IDS_EMAILFILES_SUBJECT)) + 2); // space for "emailing" and the terminating NULL + char* subject = (char*)malloc(subjectSize + strlen(LoadStr(IDS_EMAILFILES_SUBJECT)) + 2); // space for the email subject and the terminating NULL if (subject == NULL) { TRACE_E(LOW_MEMORY); @@ -183,8 +183,8 @@ BOOL CSimpleMAPI::SendMail() free(subject); free(fileDesc); - // report nothing because various clients return different values - // for example Outlook 6 on XP returned 1 when cancelling a message or 3 + // do not report anything, because different clients return different values + // for example, Outlook 6 on XP returned 1 when cancelling a message or 3 // when cancelling the connection wizard (if it was not configured) /* if (ret != 0) diff --git a/src/masks.cpp b/src/masks.cpp index 00b2c91c8..34978b2c6 100644 --- a/src/masks.cpp +++ b/src/masks.cpp @@ -71,7 +71,7 @@ BOOL AgreeMask(const char* filename, const char* mask, BOOL hasExtension, BOOL e } if (*mask == '*') mask++; // asterisk '*' afterwards -> represents "" -> everything is ok - if (!hasExtension && *mask == '.') // without extension mask "*.*" must still match... + if (!hasExtension && *mask == '.') // without an extension, the mask "*.*" must still match... return *(mask + 1) == 0 || (*(mask + 1) == '*' && *(mask + 2) == 0); else return *mask == 0; @@ -88,11 +88,11 @@ char* MaskName(char* buffer, int bufSize, const char* name, const char* mask) return buffer; } - // the first dot in the mask separates two operational parts: the first for the name, + // the first dot in the mask separates the two parts of the working mask: the first for the name, // the second for the extension (example: "a.b.c.d" + "*.*.old": "a.b.c" + "*" = "a.b.c"; // "d" + "*.old" = "d.old" -> the result is the combination "a.b.c.d.old") - int ignPoints = 0; // how many dots the name contains (this section corresponds to the text of the mask from the start to the first dot); the rest matches the extension (after the fisrt dot) + int ignPoints = 0; // how many dots the name contains (this section corresponds to the text of the mask from the start to the first dot); the rest corresponds to the extension (after the first dot) const char* n = name; while (*n != 0) if (*n++ == '.') @@ -204,10 +204,10 @@ char* MaskName(char* buffer, int bufSize, const char* name, const char* mask) // Functions for quick-search // the '/' character represents any number of characters (like '*' in a standard mask) -// returns TRUE if it is a wildcard character replacing '*' -// it must be a character not allowed in file names -// and at the same time, it should be easy to type (see the '<' on the German keyboard; -// for the backslash on the German keyboard you must press AltGr+\) +// returns TRUE if this is a character used in place of '*' +// it must be a character that is not allowed in file names +// and at the same time, it should be easy to type (see the '<' on a German keyboard; +// for a backslash on a German keyboard, you must press AltGr+\) BOOL IsQSWildChar(char ch) { return (ch == '/' || ch == '\\' || ch == '<'); @@ -249,7 +249,7 @@ BOOL AgreeQSMaskAux(const char* filename, BOOL hasExtension, const char* filenam if (!wholeString && *mask == 0) { offset = (int)(filename - filenameBase); - return TRUE; // end of mask, 'offset' = how far it reaches into the file name + return TRUE; // end of mask, 'offset' = how far it extends into the file name } if (LowerCase[*filename] == LowerCase[*mask]) { @@ -342,7 +342,7 @@ CMaskGroup::operator=(const CMaskGroup& s) if (!s.NeedPrepare) { int errpos = 0; - if (!PrepareMasks(errpos)) // an error shouldn't occur, the source mask is valid + if (!PrepareMasks(errpos)) // an error should not occur because the source mask is valid TRACE_E("CMaskGroup::operator= Internal error, PrepareMasks() failed."); } return *this; @@ -359,7 +359,7 @@ void CMaskGroup::ReleaseMasksHashArray() { free(MasksHashArray[i].Mask); CMasksHashEntry* next = MasksHashArray[i].Next; - while (next != NULL) // if there are multiple masks at the same entry (hash) + while (next != NULL) // if there are multiple masks in the same hash bucket { CMasksHashEntry* nextNext = next->Next; if (next->Mask != NULL) @@ -588,7 +588,7 @@ BOOL CMaskGroup::PrepareMasks(int& errorPos, const char* masksString) s++; } - if (hashableMasks >= 10) // to be worthwhile there should be at least 10 + if (hashableMasks >= 10) // only do this if there are at least 10 of them { MasksHashArraySize = 2 * hashableMasks; MasksHashArray = (CMasksHashEntry*)malloc(MasksHashArraySize * sizeof(CMasksHashEntry)); @@ -609,7 +609,7 @@ BOOL CMaskGroup::PrepareMasks(int& errorPos, const char* masksString) MasksHashArray[hash].Mask = mask; PreparedMasks.Detach(i2); if (!PreparedMasks.IsGood()) - PreparedMasks.ResetState(); // Detach always succeeds (at most the array won't shift, which is fine) + PreparedMasks.ResetState(); // Detach always succeeds (at worst the array will not be shifted, which is fine) } else { @@ -658,7 +658,7 @@ BOOL CMaskGroup::PrepareMasks(int& errorPos, const char* masksString) #endif // _DEBUG */ } - else // out of memory -> we simply won't accelerate searching in masks + else // out of memory -> mask searching will not be accelerated { TRACE_E(LOW_MEMORY); MasksHashArraySize = 0; @@ -686,7 +686,7 @@ BOOL CMaskGroup::AgreeMasks(const char* fileName, const char* fileExt) fileExt++; } const char* ext = fileExt; - if (*ext == 0 && *fileName == '.' && *(ext - 1) != '.') // may be the ".cvspass" case; ".." has no extension + if (*ext == 0 && *fileName == '.' && *(ext - 1) != '.') // this may be the ".cvspass" case; ".." has no extension { TRACE_E("CMaskGroup::AgreeMasks: Unexpected situation: fileName starts with '.' but fileExt points to end of name: " << fileName); ext = fileName + 1; diff --git a/src/md5.cpp b/src/md5.cpp index fd56c2674..9dd8e766d 100644 --- a/src/md5.cpp +++ b/src/md5.cpp @@ -1,7 +1,8 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED -#include "precomp.h" // include slouzi pouze k prelozitelnosti v Salamanderu +#include "precomp.h" // include serves only for compilability in Salamander //#include //#include @@ -27,7 +28,7 @@ void MD5::update(uint1* input, uint4 input_length) uint4 buffer_space; // how much space is left in buffer if (finalized) - { // so we can't update! + { // cannot update after finalization TRACE_E("MD5::update: Can't update a finalized digest!"); return; } @@ -45,7 +46,7 @@ void MD5::update(uint1* input, uint4 input_length) // Transform as many times as possible. if (input_length >= buffer_space) - { // ie. we have enough to fill the buffer + { // i.e. we have enough data to fill the buffer // fill the rest of the buffer and transform memcpy(buffer + buffer_index, input, buffer_space); transform(buffer); @@ -55,12 +56,12 @@ void MD5::update(uint1* input, uint4 input_length) input_index += 64) transform(input + input_index); - buffer_index = 0; // so we can buffer remaining + buffer_index = 0; // so we can buffer the remaining input } else input_index = 0; // so we can buffer the whole input - // and here we do the buffering: + // Buffer the input here: memcpy(buffer + buffer_index, input + input_index, input_length - input_index); } @@ -118,9 +119,9 @@ void MD5::init() state[3] = 0x10325476; } -// Constants for MD5Transform routine. -// Although we could use C++ style constants, defines are actually better, -// since they let us easily evade scope clashes. +// Constants for the MD5Transform routine. +// Although we could use C++-style constants, `#define`s are actually better, +// since they let us easily avoid scope clashes. #define S11 7 #define S12 12 diff --git a/src/md5.h b/src/md5.h index c42868ff6..ef30b1d9c 100644 --- a/src/md5.h +++ b/src/md5.h @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once @@ -8,15 +9,15 @@ class MD5 public: // methods for controlled operation: - MD5(); // simple initializer + MD5(); // default constructor void update(unsigned char* input, unsigned int input_length); void finalize(); public: // first, some types: - typedef unsigned int uint4; // assumes integer is 4 words long - typedef unsigned short int uint2; // assumes short integer is 2 words long - typedef unsigned char uint1; // assumes char is 1 word long + typedef unsigned int uint4; // assumes integer is 4 bytes long + typedef unsigned short int uint2; // assumes short integer is 2 bytes long + typedef unsigned char uint1; // assumes char is 1 byte long // next, the private data: uint4 state[4]; diff --git a/src/menu.h b/src/menu.h index f4a755835..3df42ecf8 100644 --- a/src/menu.h +++ b/src/menu.h @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once @@ -15,22 +16,22 @@ class CMenuBar; class CBitmap; /* -Posilane zpravy: +Sent messages: WM_INITMENUPOPUP hmenuPopup = (HMENU) wParam; // handle to submenu uPos = (UINT) LOWORD(lParam); // submenu item position fSystemMenu = (BOOL) HIWORD(lParam); // window menu flag - Tato zprava je posilana pouze v pripade windows menu popupu. + This message is sent only for Windows menu popups. WM_USER_INITMENUPOPUP WM_USER_UNINITMENUPOPUP - menuPopup = (CGUIMenuPopupAbstract*) wParam; // ukazatel na submenu + menuPopup = (CGUIMenuPopupAbstract*) wParam; // pointer to submenu uPos = LOWORD(lParam); // submenu item position uID = HIWORD(lParam); // submenu ID - Tyto dve zpravy jsou posilane vzdy - i pro menu postavene nad windows - menu popup. + These two messages are always sent, even for menus implemented + on top of a Windows popup. */ //***************************************************************************** @@ -42,16 +43,16 @@ class CMenuWindowQueue { private: TDirectArray Data; - CRITICAL_SECTION DataCriticalSection; // kriticka sekce pro pristup k datum + CRITICAL_SECTION DataCriticalSection; // critical section for data access BOOL UsingData; public: CMenuWindowQueue(); ~CMenuWindowQueue(); - BOOL Add(HWND hWindow); // prida polozku do fronty, vraci uspech - void Remove(HWND hWindow); // odstrani polozku z fronty - void DispatchCloseMenu(); // posle vsem otevrenym oknum menu zpravu WM_USER_CLOSEMENU + BOOL Add(HWND hWindow); // adds an item to the queue, returns success + void Remove(HWND hWindow); // removes an item from the queue + void DispatchCloseMenu(); // sends WM_USER_CLOSEMENU to all open menu windows }; extern CMenuWindowQueue MenuWindowQueue; @@ -77,15 +78,15 @@ extern COldMenuHookTlsAllocator OldMenuHookTlsAllocator; // // CMenuSharedResources // -// Pro jeden strom sub menu existuje pouze jedna instance techto prostredku. -// Jsou zalozeny napriklad ve funkci Track. -// Vsechny sub menu pak pouze dostavaji ukazatel na tyto sdilene prostredky. +// Only one instance of these resources exists for a given submenu tree. +// They are created for example in the Track function. +// All submenus then simply receive a pointer to these shared resources. // class CMenuSharedResources { public: - // barvy + // colors COLORREF NormalBkColor; COLORREF SelectedBkColor; COLORREF NormalTextColor; @@ -93,35 +94,35 @@ class CMenuSharedResources COLORREF HilightColor; COLORREF GrayTextColor; - // cache DC + // cache bitmap CBitmap* CacheBitmap; CBitmap* MonoBitmap; // temp DC - HDC HTempMemDC; // memory dc pro docasne presuny - HDC HTemp2MemDC; // memory dc pro docasne presuny + HDC HTempMemDC; // memory DC for temporary transfers + HDC HTemp2MemDC; // memory DC for temporary transfers // fonts - HFONT HNormalFont; // prubezne je vybran v HCacheMemoryDC - HFONT HBoldFont; // je vybiran pouze docasne + HFONT HNormalFont; // continuously selected in HCacheMemoryDC + HFONT HBoldFont; // selected only temporarily // menu bitmaps - HBITMAP HMenuBitmaps; // vytazeno ze systemu: poradi dle CMenuBitmapEnum + HBITMAP HMenuBitmaps; // retrieved from the system: order according to CMenuBitmapEnum int MenuBitmapWidth; // other - HWND HParent; // okno, ze ktereho bylo menu vyvolano - int TextItemHeight; // vyska polozky z textu - BOOL BitmapsZoom; // nasobek puvodni velikost bitmap - DWORD ChangeTickCount; // hodnota GetTickCount z doby, kdy doslo ke zmene vybrane polozky + HWND HParent; // window from which the menu was invoked + int TextItemHeight; // item height based on text + BOOL BitmapsZoom; // bitmap scaling relative to the original size + DWORD ChangeTickCount; // GetTickCount value from the time the selected item changed POINT LastMouseMove; - CMenuBar* MenuBar; // okno je aktivovano z MenuBar; jinak je rovno NULL - DWORD SkillLevel; // honodta pro retezec popupu -- urcuje, kerer itemy budou zobrazeny - BOOL HideAccel; // maji se skryt akceleratory + CMenuBar* MenuBar; // MenuBar from which the window was activated; otherwise NULL + DWORD SkillLevel; // value determining which items will be displayed + BOOL HideAccel; // should accelerators be hidden - const RECT* ExcludeRect; // tento obdelnik nesmime prekryt + const RECT* ExcludeRect; // this rectangle must not be covered - HANDLE HCloseEvent; // slouzi pro rozbehnuti message queue + HANDLE HCloseEvent; // used to start the message queue public: CMenuSharedResources(); @@ -151,28 +152,28 @@ class CMenuItem HICON HOverlay; ULONG_PTR CustomData; DWORD SkillLevel; // MENU_LEVEL_BEGINNER, MENU_LEVEL_INTERMEDIATE, MENU_LEVEL_ADVANCED - // tyto hodnoty se pouzivaji pro optimalizovany pristup je stavum polozek - DWORD* Enabler; // Ukazuje na promennou, ktera ridi stav polozky. - // Hodnote ruzne od nuly odpovida nulovany bit MENU_STATE_GRAYED. - // Nule odpovida nastaveny bit MENU_STATE_GRAYED. + // these values are used for optimized access to item states + DWORD* Enabler; // Points to a variable controlling the state of the item. + // A nonzero value corresponds to the MENU_STATE_GRAYED bit cleared. + // Zero corresponds to the MENU_STATE_GRAYED bit set. DWORD Flags; // MENU_FLAG_xxx - DWORD Temp; // pomocna promenna pro nektere metody + DWORD Temp; // helper variable for some methods - // vypocitane hodnoty + // calculated values int Height; int MinWidth; int YOffset; - const char* ColumnL1; // text prvniho sloupce - int ColumnL1Len; // pocet znaku + const char* ColumnL1; // text of the first column + int ColumnL1Len; // number of characters int ColumnL1Width; int ColumnL1X; - const char* ColumnL2; // text druheho sloupce (muze byt rovno NULL) - int ColumnL2Len; // pocet znaku + const char* ColumnL2; // text of the second column (can be NULL) + int ColumnL2Len; // number of characters int ColumnL2Width; int ColumnL2X; - const char* ColumnR; // text praveho sloupce (muze byt rovno NULL) - int ColumnRLen; // pocet znaku + const char* ColumnR; // text of the right column (can be NULL) + int ColumnRLen; // number of characters int ColumnRWidth; int ColumnRX; @@ -182,8 +183,8 @@ class CMenuItem BOOL SetText(const char* text, int len = -1); - // projede retezec TypeData a podle oddelovacu a promenne threeCol - // nastavi promenne ColumnL1 - ColumnR, ColumnL1Len - ColumnRLen, + // walks through the TypeData string and according to separators and the threeCol variable + // sets the variables ColumnL1 - ColumnR, ColumnL1Len - ColumnRLen, // ColumnL1Width - ColumnRWidth void DecodeSubTextLenghtsAndWidths(CMenuSharedResources* sharedRes, BOOL threeCol); @@ -206,30 +207,28 @@ enum CMenuBitmapEnum enum CMenuPopupHittestEnum { - mphItem, // na polozce, userData = index polozky - mphUpArrow, // na sipce Up - mphDownArrow, // na sipce Down - mphBorderOrOutside, // na ramecku nebo mimo - // mphOutside, // mimo okno + mphItem, // on an item, userData = item index + mphUpArrow, // on the Up arrow + mphDownArrow, // on the Down arrow + mphBorderOrOutside, // on the border or outside + // mphOutside, // outside the window }; /* Items - Seznam polozek obsazenych v pop-up menu. + List of items contained in the pop-up menu. HParent - Okno, kteremu se budou dorucovat notifikacni message. + Window that receives notification messages. HImageList - Ikonky zobrazovane pred polozkama. Ikona je urcovana promennou - CMenuItem::ImageIndex. + Icons displayed before items. The icon is chosen by CMenuItem::ImageIndex. HWindowsMenu - Handle windowsackeho popup menu. Pred otevrenim tohoto submenu - se provede enumerace jeho polozek. Ty jsou pak transformovany do docasneho - objetku CMenuPopup. Po zavreni tohoto submenu je docasny objekt zrusen. - Pro takove menu jsou posilany notifikacni message WM_INITPOPUP, WM_DRAWITEM - a WM_MEASUREITEM. + Handle of the Windows popup menu. Before opening this submenu its items are + enumerated and transformed into a temporary CMenuPopup object. After the + submenu is closed the temporary object is destroyed. Notifications + WM_INITPOPUP, WM_DRAWITEM and WM_MEASUREITEM are sent for such menus. */ class CMenuPopup : public CWindow, public CGUIMenuPopupAbstract @@ -239,46 +238,46 @@ class CMenuPopup : public CWindow, public CGUIMenuPopupAbstract HMENU HWindowsMenu; RECT WindowRect; - int TotalHeight; // celkova vyska menu; nemusi byt cela zobrazena - int Width; // rozmery client area + int TotalHeight; // total menu height; it may not be fully visible + int Width; // dimensions of the client area int Height; - int TopItemY; // y souradnice prvni polozky - BOOL UpArrowVisible; // je zobrazena sipka nahoru? - BOOL UpDownTimerRunnig; // bezi nam timer? - BOOL DownArrowVisible; // je zobrazena sipka dolu? + int TopItemY; // y-coordinate of the first item + BOOL UpArrowVisible; // is the Up arrow displayed? + BOOL UpDownTimerRunnig; // is our timer running? + BOOL DownArrowVisible; // is the Down arrow displayed? DWORD Style; // MENU_POPUP_xxxx DWORD TrackFlags; // MENU_TRACK_xxxx CMenuSharedResources* SharedRes; - CMenuPopup* OpenedSubMenu; // je-li otevreny nejaky submenu, ukazuje na nej - CMenuPopup* FirstPopup; // pokud nejde o prvni okno, ukazuje na nej; v pripade prvniho okna ukazuje na sebe samo - int SelectedItemIndex; // -1 == zadna + CMenuPopup* OpenedSubMenu; // if a submenu is open, points to it + CMenuPopup* FirstPopup; // if this is not the first window, points to it; otherwise points to itself + int SelectedItemIndex; // -1 == none BOOL SelectedByMouse; // TRUE->ByMouse FALSE->ByKeyboard HIMAGELIST HImageList; HIMAGELIST HHotImageList; - int ImageWidth; // rozmery jednoho obrazku z HImageList + int ImageWidth; // width of one image from HImageList int ImageHeight; - DWORD ID; // kopie ID z CMenuItem - BOOL Closing; // bylo zavolano HideAll a hned jak bude mozne, koncime - int MinWidth; // pri rozvrhovani sirky nebude sirka mensi, nez tato hodnota - BOOL ModifyMode; // pokud je menu zobrazeno, neni mozne nad nim provadet zmeny, neni-li v ModifyMode - DWORD SkillLevel; // urcuje, ktere polozky budou v tomto popupu zobrazeny + DWORD ID; // copy of ID from CMenuItem + BOOL Closing; // HideAll was called and we finish as soon as possible + int MinWidth; // during layout the width will not be smaller than this value + BOOL ModifyMode; // if the menu is visible, changes are allowed only in ModifyMode + DWORD SkillLevel; // determines which items will be shown in this popup int MouseWheelAccumulator; // vertical public: // - // Vlastni metody + // custom methods // CMenuPopup(DWORD id = 0); BOOL LoadFromTemplate2(HINSTANCE hInstance, const MENU_TEMPLATE_ITEM* menuTemplate, DWORD* enablersOffset, HIMAGELIST hImageList, HIMAGELIST hHotImageList, int* addedRows); // - // Implementace metod CGUIMenuPopupAbstract + // implementation of CGUIMenuPopupAbstract methods // virtual BOOL WINAPI LoadFromTemplate(HINSTANCE hInstance, const MENU_TEMPLATE_ITEM* menuTemplate, DWORD* enablersOffset, HIMAGELIST hImageList = NULL, HIMAGELIST hHotImageList = NULL); - virtual void WINAPI SetSelectedItemIndex(int index); // slouzi k prednastaveni vybrane polozky (musi byt nastaven flag MENU_TRACK_SELECT, jinak se nepouzije) + virtual void WINAPI SetSelectedItemIndex(int index); // used to preset the selected item (MENU_TRACK_SELECT must be set or it is ignored) virtual int WINAPI GetSelectedItemIndex() { return SelectedItemIndex; } virtual void WINAPI SetTemplateMenu(HMENU hWindowsMenu) { HWindowsMenu = hWindowsMenu; } @@ -316,12 +315,12 @@ class CMenuPopup : public CWindow, public CGUIMenuPopupAbstract virtual void WINAPI RemoveAllItems(); virtual BOOL WINAPI RemoveItemsRange(int firstIndex, int lastIndex); - // umoznuje provadet zmeny nad otevrenym menu popupem - virtual BOOL WINAPI BeginModifyMode(); // zahajeni editacniho rezimu - virtual BOOL WINAPI EndModifyMode(); // ukonceni rezimu - menu se prekresli + // allows making changes while the menu popup is open + virtual BOOL WINAPI BeginModifyMode(); // begins edit mode + virtual BOOL WINAPI EndModifyMode(); // ends the mode - the menu is redrawn - // urci polozky, kter budou v menu zobrazeny - // 'skillLevel' muze byt jedna z hodnot MENU_LEVEL_BEGINNER, MENU_LEVEL_INTERMEDIATE a MENU_LEVEL_ADVANCED + // determines which items will be displayed in the menu + // 'skillLevel' can be MENU_LEVEL_BEGINNER, MENU_LEVEL_INTERMEDIATE or MENU_LEVEL_ADVANCED virtual void WINAPI SetSkillLevel(DWORD skillLevel); // The FindItemPosition method finds a menu item position. @@ -339,7 +338,7 @@ class CMenuPopup : public CWindow, public CGUIMenuPopupAbstract virtual BOOL WINAPI FillMenuHandle(HMENU hMenu); virtual BOOL WINAPI GetStatesFromHWindowsMenu(HMENU hMenu); - virtual void WINAPI SetImageList(HIMAGELIST hImageList, BOOL subMenu = FALSE); // pokud je subMenu==TRUE, nastavi se hadle i do submenu + virtual void WINAPI SetImageList(HIMAGELIST hImageList, BOOL subMenu = FALSE); // if subMenu==TRUE, the image list handle is also set for submenus virtual HIMAGELIST WINAPI GetImageList(); virtual void WINAPI SetHotImageList(HIMAGELIST hHotImageList, BOOL subMenu = FALSE); virtual HIMAGELIST WINAPI GetHotImageList(); @@ -360,29 +359,29 @@ class CMenuPopup : public CWindow, public CGUIMenuPopupAbstract // 'hwnd' [in] Handle to the window that owns the shortcut menu. This window // receives all messages from the menu. The window does not receive a // WM_COMMAND message from the menu until the function returns. - // If you specify TPM_NONOTIFY in the fuFlags parameter, the function - // does not send messages to the window identified by hwnd. However, - // you still have to pass a window handle in hwnd. It can be any window - // handle from your application. + // If you specify MENU_TRACK_NONOTIFY in the 'trackFlags' parameter, the + // function does not send messages to the window identified by hwnd. + // However, you still have to pass a window handle in hwnd. It can be + // any window handle from your application. // // 'exclude' [in] Rectangle to exclude when positioning the menu, in screen // coordinates. This parameter can be NULL. // // Return Values: - // If you specify TPM_RETURNCMD in the 'flags' parameter, the return value is the - // menu-item identifier of the item that the user selected. If the user cancels - // the menu without making a selection, or if an error occurs, then the return - // value is zero. + // If you specify MENU_TRACK_RETURNCMD in the 'trackFlags' parameter, the return + // value is the menu-item identifier of the item that the user selected. If the + // user cancels the menu without making a selection, or if an error occurs, then + // the return value is zero. // - // If you do not specify TPM_RETURNCMD in the 'flags' parameter, the return value - // is nonzero if the function succeeds and zero if it fails. + // If you do not specify MENU_TRACK_RETURNCMD in the 'trackFlags' parameter, the + // return value is nonzero if the function succeeds and zero if it fails. virtual DWORD WINAPI Track(DWORD trackFlags, int x, int y, HWND hwnd, const RECT* exclude); - virtual BOOL WINAPI GetItemRect(int index, RECT* rect); // vrati obsany obdelnik kolem polozky v screen souradnicich + virtual BOOL WINAPI GetItemRect(int index, RECT* rect); // returns bounding rectangle of the item in screen coordinates - // obehne vsechny polozky a pokud maji nastaveny ukazatel 'EnablerData' - // porovnaja hodnotu (na kterou ukazuji) se skutecnym stavem polozky. - // Pokud se stav lisi, zmeni ho. + // iterates through all items and if they have the 'EnablerData' pointer set + // compares the pointed value with the actual item state. + // If the state differs, it is updated. virtual void WINAPI UpdateItemsState(); virtual void WINAPI SetMinWidth(int minWidth); @@ -392,28 +391,28 @@ class CMenuPopup : public CWindow, public CGUIMenuPopupAbstract virtual void WINAPI AssignHotKeys(); protected: - void Cleanup(); // inicializuje objekt + void Cleanup(); // initializes the object BOOL LoadFromHandle(); - void LayoutColumns(); // probehne polozky a podle jejich rozmeru nastavi hodnoty + void LayoutColumns(); // iterates over items and sets values according to their size DWORD GetOwnerDrawItemState(const CMenuItem* item, BOOL selected); - void DrawCheckBitmapVista(HDC hDC, CMenuItem* item, int yOffset, BOOL selected); // veze s alpha blendem - void DrawCheckBitmap(HDC hDC, CMenuItem* item, int yOffset, BOOL selected); // check marky dodane uzivatelem (HBmpChecked a HBmpUnchecked) - void DrawCheckImage(HDC hDC, CMenuItem* item, int yOffset, BOOL selected); // standardni checkmarky, ImageIndex, HIcon - void DrawCheckMark(HDC hDC, CMenuItem* item, int yOffset, BOOL selected); // vola odpovidajici funkci - void DrawItem(HDC hDC, CMenuItem* item, int yOffset, BOOL selected); // vykresli jednu polozku - void DrawUpDownItem(HDC hDC, BOOL up); // vykresli polozku obsahujici sipku nahoru nebo dolu + void DrawCheckBitmapVista(HDC hDC, CMenuItem* item, int yOffset, BOOL selected); // Vista version with alpha blend + void DrawCheckBitmap(HDC hDC, CMenuItem* item, int yOffset, BOOL selected); // user-supplied check marks (HBmpChecked and HBmpUnchecked) + void DrawCheckImage(HDC hDC, CMenuItem* item, int yOffset, BOOL selected); // standard check marks, ImageIndex, HIcon + void DrawCheckMark(HDC hDC, CMenuItem* item, int yOffset, BOOL selected); // calls the appropriate function + void DrawItem(HDC hDC, CMenuItem* item, int yOffset, BOOL selected); // draws a single item + void DrawUpDownItem(HDC hDC, BOOL up); // draws the item containing the up or down arrow CMenuPopupHittestEnum HitTest(const POINT* point, int* userData); BOOL FindNextItemIndex(int fromIndex, BOOL topToDown, int* index); - inline CMenuPopup* FindActivePopup(); // najde posledni otevreny popup; vrati ukazatel na objekt - inline CMenuPopup* FindPopup(HWND hWindow); // hleda od nas az po posledniho childa; vrati ukazatel na objekt nnebo NULL + inline CMenuPopup* FindActivePopup(); // finds the last opened popup; returns a pointer to the object + inline CMenuPopup* FindPopup(HWND hWindow); // searches from this popup down to the last child; returns a pointer to the popup object or NULL inline void DoDispatchMessage(MSG* msg, BOOL* leaveMenu, DWORD* retValue, BOOL* dispatchLater); void OnTimerTimeout(); - void CheckSelectedPath(CMenuPopup* terminator); // probehne celou vetev a nastavi SelectedItemy tak, aby vedly k poslednimu popupu + void CheckSelectedPath(CMenuPopup* terminator); // traverses the whole branch and sets SelectedItems so they lead to the last popup - // k Track pridava [in] menuBar - // [in] delayedMsg - // [in] dispatchDelayedMsg: Ma se delayedMsg dorucit po navratu z teto metodu? + // Compared to Track, adds [in] menuBar + // [in] delayedMsg + // [in] dispatchDelayedMsg: should delayedMsg be delivered after this method returns? // DWORD TrackInternal(DWORD trackFlags, int x, int y, HWND hwnd, const RECT* exclude, CMenuBar* menuBar, MSG& delayedMsg, BOOL& dispatchDelayedMsg); @@ -428,32 +427,32 @@ class CMenuPopup : public CWindow, public CGUIMenuPopupAbstract void OnChar(char key, BOOL* leaveMenu, DWORD* retValue); int FindNextItemIndex(int firstIndex, char key); - // pro navigaci pomoci PgDn/PgUp, hleda index prvni polozky - // za separatorem; pokud je 'down' TRUE, hleda smerem dolu - // od polozky 'firstIndex', jinak smerem nahoru + // for navigation using PgDn/PgUp, searches for the index of the first item + // after a separator; if 'down' is TRUE it searches downward from 'firstIndex', + // otherwise upward int FindGroupIndex(int firstIndex, BOOL down); - // pokud je 'byMouse' TRUE, jde o zmenu pomoci mysi, jinak jde o zmenu z klavesnice - // select nastaveny z klavesnice "drzi", pokud uzivatel pohybuje mysi mimo popupy + // if 'byMouse' is TRUE, it is a mouse change, otherwise a keyboard change + // selection set by keyboard "sticks" while the user moves the mouse outside popups void SelectNewItemIndex(int newItemIndex, BOOL byMouse); - void EnsureItemVisible(int index); // pokud polozka lezi mimo zobrazenou oblast, zajisti - // odrolovani a vykresleni polozek tak, aby byla cela - // viditelna + void EnsureItemVisible(int index); // if the item lies outside the visible area, + // scroll and repaint so the item becomes + // fully visible void OnMouseWheel(WPARAM wParam, LPARAM lParam); - // x, y jsou souradnice leveho horniho rohu okna - // submenuItemPos slouzi k zaslani notifikace aplikaci + // x, y are coordinates of the upper left corner of the window + // submenuItemPos is used to send a notification to the application BOOL CreatePopupWindow(CMenuPopup* firstPopup, int x, int y, int submenuItemPos, const RECT* exclude); - // Vrati handle popup window pod kurzorem; pokud je pod kurzorem child window, - // bude dohledan jeho parent. + // Returns the handle of the popup window under the cursor; if a child window + // is under the cursor, its parent is found. // - // Zavedeno kvuli PicaView, ktere vklada do kontextoveho menu child window, - // do ktereho renderuje se spozdenim obrazek. V Salamu 2.0 pri najeti na takovy - // obrazek doslo k odvybrani polozky v menu, protoze WindowFromPoint vratilo - // jine okno nez popup. + // Introduced because of PicaView, which inserts a child window into the context + // menu and renders an image there with a delay. In Salamander 2.0 moving the + // cursor over such an image deselected the item because WindowFromPoint returned + // a window other than the popup. HWND PopupWindowFromPoint(POINT point); void ResetMouseWheelAccumulator() { MouseWheelAccumulator = 0; } @@ -473,56 +472,57 @@ class CMenuBar : public CWindow, public CGUIMenuBarAbstract { protected: CMenuPopup* Menu; - int Width; // rozmery celeho okna + int Width; // dimensions of the entire window int Height; HFONT HFont; int FontHeight; - int HotIndex; // polozka, ktera je bud vysunuta nebo zamackla (zadna = -1) - HWND HNotifyWindow; // kam budeme dorucovat notifikace - BOOL MenuLoop; // jsou rozbalovana submenu - DWORD RetValue; // ktery command mame poslat do okna aplikace + int HotIndex; // item that is either expanded or pressed (-1 = none) + HWND HNotifyWindow; // where notifications will be delivered + BOOL MenuLoop; // are submenus expanded + DWORD RetValue; // which command should be sent to the application window MSG DelayedMsg; BOOL DispatchDelayedMsg; - BOOL HotIndexIsTracked; // je otevren popup pod HotIndex? + BOOL HotIndexIsTracked; // is a popup open under HotIndex? BOOL HandlingVK_MENU; BOOL WheelDuringMenu; POINT LastMouseMove; - BOOL Closing; // bylo zavolano WM_USER_CLOSEMENU hned jak bude mozne, koncime - HANDLE HCloseEvent; // slouzi pro rozbehnuti message queue - BOOL MouseIsTracked; // je mys sledovana pomoci TrackMouseEvent? - BOOL HelpMode; // jsme v rezimu Context Help (Shift+F1)? - - // tyto dve promenne slouzi pro kooperaci MenuBar a MenuPopup - // jsou nastavovany v CMenuPopup::TrackInternal a urcuji dalsi chovani - // MenuBar po zavreni Popupu - int IndexToOpen; // pokud bude nastavena na -1, nema se otevrit dalsi Popup, - // jinak obsahuje index popupu, ktery se ma otevrit - BOOL OpenWithSelect; // ma se v otevrenem menu vybrat prvni polozka? - BOOL OpenByMouse; // otevirano pomoci mysi nebo klavesnice? - BOOL ExitMenuLoop; // Pokud je TRUE, ukoncime MenuLoop - BOOL HelpMode2; // obdrzeli jmse WM_USER_HELP_MOUSEMOVE a cekame na WM_USER_HELP_MOUSELEAVE? (musime vysvecovat polozku pod kurzorem) - WORD UIState; // zobrazovani akceleratoru + BOOL Closing; // WM_USER_CLOSEMENU was called and we exit as soon as possible + HANDLE HCloseEvent; // used to start the message queue + BOOL MouseIsTracked; // is the mouse tracked using TrackMouseEvent? + BOOL HelpMode; // Context Help mode (Shift+F1)? + + // these two variables are used for cooperation between MenuBar and MenuPopup + // they are set in CMenuPopup::TrackInternal and determine further behavior + // of MenuBar after the popup is closed + int IndexToOpen; // -1 means no additional popup should be opened, + // otherwise the index of the popup to open + BOOL OpenWithSelect; // should the first item be selected when the menu opens? + BOOL OpenByMouse; // opened via mouse or keyboard? + BOOL ExitMenuLoop; // TRUE to exit MenuLoop + BOOL HelpMode2; // did we receive WM_USER_HELP_MOUSEMOVE and wait for + // WM_USER_HELP_MOUSELEAVE? (we must highlight the item under the cursor) + WORD UIState; // accelerator display BOOL ForceAccelVisible; public: // - // Vlastni metody + // custom methods // CMenuBar(CMenuPopup* menu, HWND hNotifyWindow, CObjectOrigin origin = ooStatic); ~CMenuBar(); // - // Implementace metod CGUIMenuBarAbstract + // implementation of CGUIMenuBarAbstract methods // virtual BOOL WINAPI CreateWnd(HWND hParent); virtual HWND WINAPI GetHWND() { return HWindow; } - virtual int WINAPI GetNeededWidth(); // vrati sirku, ktera bude pro okno potreba - virtual int WINAPI GetNeededHeight(); // vrati vysku, ktera bude pro okno potreba - virtual void WINAPI SetFont(); // vytahne font pro menu bar ze systemu - virtual BOOL WINAPI GetItemRect(int index, RECT& r); // vrati umisteni polozky ve screen souradnicich - virtual void WINAPI EnterMenu(); // user stisknul VK_MENU + virtual int WINAPI GetNeededWidth(); // returns the width needed for the window + virtual int WINAPI GetNeededHeight(); // returns the height needed for the window + virtual void WINAPI SetFont(); // obtains the menu bar font from the system + virtual BOOL WINAPI GetItemRect(int index, RECT& r); // Returns the item's rectangle in screen coordinates. + virtual void WINAPI EnterMenu(); // user pressed VK_MENU virtual BOOL WINAPI IsInMenuLoop() { return MenuLoop; } virtual void WINAPI SetHelpMode(BOOL helpMode) { HelpMode = helpMode; } @@ -535,17 +535,17 @@ class CMenuBar : public CWindow, public CGUIMenuBarAbstract void DrawItem(int index); void DrawItem(HDC hDC, int index, int x); void DrawAllItems(HDC hDC); - void RefreshMinWidths(); // obehne vsechny polozky a napocit si k nim 'MinWidth' + void RefreshMinWidths(); // iterates all items and computes the 'MinWidth' of each - void TrackHotIndex(); // zamackne HotIndex a zavola TrackPopup; vrati se po jeho zavreni - void EnterMenuInternal(int index, BOOL openWidthSelect, BOOL byMouse); // byMouse rika, zda jde o otevreni pres mys nebo klavesnici + void TrackHotIndex(); // presses HotIndex and calls TrackPopup; returns once it closes + void EnterMenuInternal(int index, BOOL openWidthSelect, BOOL byMouse); // byMouse indicates whether the menu was opened by mouse or keyboard - // vraci TRUE, pokud je na pozici polozka; pak take nastavi 'index' - // jinak vraci FALSE + // returns TRUE if there is an item at the position and sets 'index'; + // otherwise returns FALSE BOOL HitTest(int xPos, int yPos, int& index); - // prohleda vlozene submenu a vrati TRUE, pokud mezi nima najde nejaky s horkou - // klavesou 'hotKey'; zaroven vrati jeho index + // searches inserted submenus and returns TRUE if one with the hot key 'hotKey' is found; + // the index of the item is returned as well BOOL HotKeyIndexLookup(char hotKey, int& itemIndex); friend class CMenuPopup; @@ -558,14 +558,14 @@ extern CMenuPopup MainMenu; extern CMenuPopup ArchiveMenu; extern CMenuPopup ArchivePanelMenu; -BOOL BuildSalamanderMenus(); // sestavi globalni menu pro Salamandera -BOOL BuildFindMenu(CMenuPopup* popup); // sestavi instanci menu pro find +BOOL BuildSalamanderMenus(); // builds the global menu for Salamander +BOOL BuildFindMenu(CMenuPopup* popup); // builds an instance of the find menu -// Prida do 'popup' polozky vytvorene na zaklade pole 'buttonsID'. -// 'hWindow' je parent tlacitek, na ktere odkazuji konstanty pole 'buttonsID'. -// Pole 'buttonsID' muze obsahovat libovolne mnozstvi cisel zakoncene 0. -// Cislo -1 je vyhrazene pro separator a cislo -2 pro default polozku (nasledujici -// polozka bude mit nastaven default state). Ostatni cisla jsou povazovana -// za id tlacitek. Jejich text je vytazen a pridan do menu. Zaroven je -// vytazen jejich Enabled stav, ktery je take promitnut do polozky v menu. +// Adds to 'popup' items created from the 'buttonsID' array. +// 'hWindow' is the parent of the buttons referenced by the 'buttonsID' array. +// The 'buttonsID' array may contain any number of IDs terminated by 0. +// ID -1 denotes a separator and -2 marks the default item (the next item will +// have the default state set). Other numbers are treated as button IDs; their +// text is extracted and added to the menu and their enabled state is mirrored in +// the menu item. void FillContextMenuFromButtons(CMenuPopup* popup, HWND hWindow, int* buttonsID); diff --git a/src/menu1.cpp b/src/menu1.cpp index 0d185723f..b41d91ee8 100644 --- a/src/menu1.cpp +++ b/src/menu1.cpp @@ -284,7 +284,7 @@ void CMenuItem::DecodeSubTextLenghtsAndWidths(CMenuSharedResources* sharedRes, B ColumnL2 = NULL; ColumnR = NULL; - // set column pointers and character counts + // set pointers and character counts for each column while (inifiniteLoop) { if (*iterator == '\t' || *iterator == 0) diff --git a/src/menu2.cpp b/src/menu2.cpp index 40e60b209..bdbb77e01 100644 --- a/src/menu2.cpp +++ b/src/menu2.cpp @@ -281,11 +281,11 @@ BOOL CMenuPopup::EndModifyMode() UpdateWindow(HWindow); /* // update the current item - POINT cursorPos; - GetCursorPos(&cursorPos); - ScreenToClient(HWindow, &cursorPos); - SharedRes->LastMouseMove.x = cursorPos.x - 1; // disable the condition - SendMessage(HWindow, WM_MOUSEMOVE, 0, MAKELPARAM(cursorPos.x, cursorPos.y)); + POINT cursorPos; + GetCursorPos(&cursorPos); + ScreenToClient(HWindow, &cursorPos); + SharedRes->LastMouseMove.x = cursorPos.x - 1; // disable the condition + SendMessage(HWindow, WM_MOUSEMOVE, 0, MAKELPARAM(cursorPos.x, cursorPos.y)); */ } ModifyMode = FALSE; @@ -1131,7 +1131,7 @@ BOOL CMenuPopup::LoadFromHandle() // convert the mii.fState variable if (mii.fState & MFS_CHECKED) { - if (mii.hbmpChecked == NULL) // quick hack because of ICQ which uses checked && mii.hbmpChecked + if (mii.hbmpChecked == NULL) // workaround for ICQ, which uses checked && mii.hbmpChecked item->State |= MENU_STATE_CHECKED; else mii.hbmpUnchecked = mii.hbmpChecked; @@ -1636,8 +1636,8 @@ void CMenuPopup::OnChar(char key, BOOL* leaveMenu, DWORD* retValue) // x64 7zip returns 0xcccccccccccccccc when right-clicking a .7z file, // expanding the 7Zip menu and pressing 'h', which is inconsistent with // http://msdn.microsoft.com/en-us/library/windows/desktop/ms646349%28v=vs.85%29.aspx - // (it should return 0 because nothing in the menu starts with H) - // in any case, we were getting RTCs, so we mask to the lower DWORD + // (it should return 0 because nothing in the menu starts with H). + // In any case, RTCs were firing, so we mask to the lower DWORD. DWORD ret = (DWORD)(SendMessage(SharedRes->HParent, WM_MENUCHAR, MF_POPUP, (LPARAM)hMenu) & 0xffffffff); if (HIWORD(ret) == MNC_SELECT) SelectNewItemIndex(LOWORD(ret), FALSE); @@ -1952,7 +1952,7 @@ void CMenuPopup::OnMouseWheel(WPARAM wParam, LPARAM lParam) if (firstVisibleItem == NULL || lastVisibleItem == NULL) return; if (TopItemY == 0 && lastVisibleItem->YOffset + lastVisibleItem->Height <= Height) - return; // all items are visible; there’s no point in scrolling in this popup + return; // all items are visible; there is no point in scrolling in this popup // check the upper bound (so the top item is not pulled below the top edge of the menu) if (TopItemY + delta >= 0) @@ -1972,7 +1972,7 @@ void CMenuPopup::OnMouseWheel(WPARAM wParam, LPARAM lParam) else downArrow = TRUE; - // if something changed, we will paint (forget scrolling; if it flickers, we can add code later) + // if anything changed, repaint it (ignoring scrolling for now; if it flickers, we can add it later) if (delta != 0 || UpArrowVisible != upArrow || DownArrowVisible != downArrow) { TopItemY += delta; @@ -2051,10 +2051,10 @@ void CMenuPopup::DoDispatchMessage(MSG* msg, BOOL* leaveMenu, DWORD* retValue, B case WM_SYSKEYUP: { - // if the sys key up with VK_F10 was delivered to a modal dialog, a - // WM_SYSCOMMAND message with uCmdType=SC_KEYMENU was sent which activates the window menu - // this happened in Plugins/Encrypt/Create Key/Shift+F10 in one of the edit lines - // with passwords where our menu expands + // If the system key-up for VK_F10 was delivered to a modal dialog, a + // WM_SYSCOMMAND message with uCmdType=SC_KEYMENU was sent, which activated the window menu. + // This occurred in Plugins/Encrypt/Create Key/Shift+F10 in one of the password + // edit boxes, where our menu opens. if (msg->wParam == VK_F10) return; break; @@ -2078,7 +2078,7 @@ void CMenuPopup::DoDispatchMessage(MSG* msg, BOOL* leaveMenu, DWORD* retValue, B } return; } - if (msg->wParam == VK_MENU && (msg->lParam & 0x40000000) == 0 || // Alt down, ale ne autorepeat + if (msg->wParam == VK_MENU && (msg->lParam & 0x40000000) == 0 || // Alt pressed, but not auto-repeat (!shiftPressed && msg->wParam == VK_F10)) { *leaveMenu = TRUE; @@ -2210,7 +2210,7 @@ void CMenuPopup::DoDispatchMessage(MSG* msg, BOOL* leaveMenu, DWORD* retValue, B case VK_RETURN: { popup->OnKeyReturn(leaveMenu, retValue); // open sub menu or produce a command - return; // must not let TranslateMessage handle Return + return; // must not let TranslateMessage translate Return } } msg->hwnd = HWindow; // redirect to us (to prevent keystrokes from leaking out) @@ -2261,15 +2261,15 @@ void CMenuPopup::DoDispatchMessage(MSG* msg, BOOL* leaveMenu, DWORD* retValue, B CMenuItem* item = popup->Items[popup->SelectedItemIndex]; if (!(item->State & MENU_STATE_GRAYED) || SharedRes->MenuBar != NULL && SharedRes->MenuBar->HelpMode && // Petr: we are opened from the menubar and in HelpMode (Shift+F1) + - (item->SubMenu == NULL || item->ID != 0)) // Petr: plus we have a command ID or submenu (a "grayed" submenu cannot be opened) + (item->SubMenu == NULL || item->ID != 0)) // Petr: and we have a command ID or submenu (a "grayed" submenu cannot be opened) { - if (!(item->State & MENU_STATE_GRAYED) && // Petr: opening "grayed" submenus is not possible + if (!(item->State & MENU_STATE_GRAYED) && // Petr: a "grayed" submenu cannot be opened item->SubMenu != NULL && item->SubMenu != popup->OpenedSubMenu) { // if a sub-menu is open, close it if (popup->OpenedSubMenu != NULL) popup->CloseOpenedSubmenu(); - // now I can open a new one + // now a new one can be opened RECT itemRect; popup->GetItemRect(popup->SelectedItemIndex, &itemRect); item->SubMenu->SharedRes = SharedRes; @@ -2290,7 +2290,7 @@ void CMenuPopup::DoDispatchMessage(MSG* msg, BOOL* leaveMenu, DWORD* retValue, B { *leaveMenu = TRUE; *retValue = item->ID; - if (SharedRes->MenuBar != NULL) // we were opened from the menubar + if (SharedRes->MenuBar != NULL) // opened from the menu bar SharedRes->MenuBar->ExitMenuLoop = TRUE; // so we exit it } } @@ -2585,7 +2585,7 @@ BOOL CMenuPopup::CreatePopupWindow(CMenuPopup* firstPopup, int x, int y, int sub else if (TrackFlags & MENU_TRACK_BOTTOMALIGN) newY -= height; - // handle the menu crossing the right or left edge of the visible area + // handle overflow past the right and left edges of the visible area if (newX + width > clipRect.right) newX = clipRect.right - width; if (newX < clipRect.left) @@ -2924,14 +2924,14 @@ CMenuPopup::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) PAINTSTRUCT ps; HANDLES(BeginPaint(HWindow, &ps)); PaintAllItems(NULL); - HANDLES(EndPaint(HWindow, &ps)); // only turns off the caret that we do not have anyway + HANDLES(EndPaint(HWindow, &ps)); // only hides the caret, which we do not have anyway return 0; } /* - // support for animation + // animation support case WM_PRINTCLIENT: { - HDC hDC = (HDC) wParam; + HDC hDC = (HDC) wParam; if (lParam & PRF_CLIENT) { int y = 0; @@ -2963,17 +2963,17 @@ CMenuPopup::Track(DWORD trackFlags, int x, int y, HWND hwnd, const RECT* exclude if (!(trackFlags & MENU_TRACK_NONOTIFY)) SendMessage(hwnd, WM_USER_ENTERMENULOOP, 0, 0); - SelectedByMouse = FALSE; // in 2.5b9 the variable was not initialized and ChangeDeriveMenu Alt+F1/2 - // behaved unpredictably -- moving the cursor outside the menu sometimes + SelectedByMouse = FALSE; // in 2.5b9 the variable was not initialized, and ChangeDeriveMenu Alt+F1/2 + // behaved unpredictably: moving the cursor outside the menu sometimes // caused the selection to be lost - // if this behaviour is not suitable for CMenuPopup::Track(), - // it might be time to introduce a control flag in trackFlags + // if this behavior is not suitable for CMenuPopup::Track(), + // a control flag in trackFlags should probably be introduced DWORD retValue = TrackInternal(trackFlags, x, y, hwnd, exclude, NULL, msg, dispatchMsg); if (!(trackFlags & MENU_TRACK_NONOTIFY)) SendMessage(hwnd, WM_USER_LEAVEMENULOOP, 0, 0); - // if we installed a hook, we will also unhook it + // if we installed a hook, unhook it as well if (hOldHookProc != NULL) OldMenuHookTlsAllocator.UnhookThread(hOldHookProc); @@ -3059,7 +3059,7 @@ CMenuPopup::TrackInternal(DWORD trackFlags, int x, int y, HWND hwnd, const RECT* BeginStopRefresh(); // we do not want any refreshes BeginStopIconRepaint(); // we do not want any icon repaints - // open the father window + // open the parent window // TRACE_I("MENU: creating window"); if (CreatePopupWindow(this, x, y, 0, exclude)) { @@ -3097,7 +3097,7 @@ CMenuPopup::TrackInternal(DWORD trackFlags, int x, int y, HWND hwnd, const RECT* if (msg.message == WM_LBUTTONDOWN) skipFirstLBtnDblclk = FALSE; if (msg.message == WM_LBUTTONDBLCLK) - continue; // skip the message because it is a typo after lbuttondown + continue; // skip the message because it is a spurious double-click after WM_LBUTTONDOWN } if (skipFirstLBtnUp) { @@ -3107,7 +3107,7 @@ CMenuPopup::TrackInternal(DWORD trackFlags, int x, int y, HWND hwnd, const RECT* { skipFirstLBtnUp = FALSE; if (FindPopup(PopupWindowFromPoint(msg.pt)) == NULL) - continue; // skip the message to avoid immediate window closing + continue; // skip the message to prevent the window from closing immediately } } DoDispatchMessage(&msg, &leaveMenu, &retValue, &dispatchLater); diff --git a/src/menubar.cpp b/src/menubar.cpp index b993a0368..7ec31063d 100644 --- a/src/menubar.cpp +++ b/src/menubar.cpp @@ -396,7 +396,7 @@ void CMenuBar::EnterMenuInternal(int index, BOOL openWidthSelect, BOOL byMouse) case WM_KEYDOWN: { BOOL shiftPressed = (GetKeyState(VK_SHIFT) & 0x8000) != 0; - if (msg.wParam == VK_MENU && (msg.lParam & 0x40000000) == 0 || // Alt down, but not an autorepeat + if (msg.wParam == VK_MENU && (msg.lParam & 0x40000000) == 0 || // Alt down, but not auto-repeat (!shiftPressed && msg.wParam == VK_F10)) { leaveLoop = TRUE; @@ -556,7 +556,7 @@ void CMenuBar::EnterMenuInternal(int index, BOOL openWidthSelect, BOOL byMouse) // remove ourselves from monitoring closing messages MenuWindowQueue.Remove(HWindow); - // if we hooked, we will also unhook + // if we hooked the thread, we will also unhook it if (hOldHookProc != NULL) OldMenuHookTlsAllocator.UnhookThread(hOldHookProc); @@ -715,7 +715,7 @@ BOOL CMenuBar::IsMenuBarMessage(CONST MSG* lpMsg) } else { - WheelDuringMenu = FALSE; // if the user scrolled the wheel and then typed a number (Alt+numXXX), we will ignore the scrolling + WheelDuringMenu = FALSE; // if the user scrolled the wheel and then typed a number (Alt+numXXX), scrolling is ignored HandlingVK_MENU = FALSE; } if (wParam == VK_F10) @@ -754,7 +754,7 @@ BOOL CMenuBar::IsMenuBarMessage(CONST MSG* lpMsg) if (WheelDuringMenu) { WheelDuringMenu = FALSE; - return TRUE; // suppress releasing Alt after Alt+Wheel, otherwise the window menu opens (without being shown) + return TRUE; // suppress Alt release after Alt+Wheel; otherwise the window menu is entered without being shown } // if the user did not use the wheel, we must not process the message // Alt+num064 (etc.) is used for inserting characters @@ -826,7 +826,7 @@ CMenuBar::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_ERASEBKGND: { - if (WindowsVistaAndLater) // under Vista the rebar flickers + if (WindowsVistaAndLater) // On Vista, the rebar flickers return TRUE; RECT r; GetClientRect(HWindow, &r); @@ -908,7 +908,7 @@ CMenuBar::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) int newHotIndex = HotIndex; if (hitItem) { - if (!HelpMode2 && !MenuLoop && !MouseIsTracked) // capture is needed only in the track mode + if (!HelpMode2 && !MenuLoop && !MouseIsTracked) // mouse leave tracking is needed only in track mode { TRACKMOUSEEVENT tme; tme.cbSize = sizeof(tme); diff --git a/src/msgbox.cpp b/src/msgbox.cpp index 38774c7e1..532533f6a 100644 --- a/src/msgbox.cpp +++ b/src/msgbox.cpp @@ -191,9 +191,9 @@ BOOL CMessageBox::EscapeEnabled() return TRUE; } -// returns a copy of 'src' into which 'n' characters are inserted so that the resulting maximum -// width does not exceed 'maxWidth'. Assumes that the hDC has the correct font selected. -// returns NULL in case of failure +// returns a copy of 'src' with '\n' characters inserted so that the resulting maximum +// width does not exceed 'maxWidth'. Assumes that 'hDC' has the appropriate font selected. +// returns NULL on failure char* DuplicateStrAndInsertEOLs(const char* src, HDC hDC, int maxWidth) { @@ -581,7 +581,7 @@ CMessageBox::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) // maximum width relative to the desktop where the dialog will appear int maxTextWidth = (int)((clipRect.right - clipRect.left) / 1.8); - if (maxTextWidth > fontCharWidth * 90) // since Windows Vista dialogs are narrower again - wrap at 90 average characters + if (maxTextWidth > fontCharWidth * 90) // Since Windows Vista, dialogs are narrower again, so wrap at 90 average-width characters. maxTextWidth = fontCharWidth * 90; tR.right = maxTextWidth; @@ -589,8 +589,8 @@ CMessageBox::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (tR.right > maxTextWidth) { - // text width exceeds maxTextWidth limit, so we create a new one - // text into which we will insert hard line breaks + // text width exceeds the maxTextWidth limit, so we create new text + // with hard line breaks inserted const char* newText = DuplicateStrAndInsertEOLs(Text.Get(), hDC, maxTextWidth); if (newText != NULL) { @@ -790,7 +790,7 @@ CMessageBox::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) // assign text BOOL btnTextWasSet = FALSE; - if (AliasBtnNames != NULL) // alias button names + if (AliasBtnNames != NULL) // button name aliases { char tmpBuff[1000]; char seps[] = "\t"; diff --git a/src/olespy.cpp b/src/olespy.cpp index 7293cf0eb..d7fa50926 100644 --- a/src/olespy.cpp +++ b/src/olespy.cpp @@ -12,49 +12,49 @@ // // Notes on the implementation of IMallocSpy // -// 1) OLE caches (among other things) BSTRs, so under a normal OS it returns -// nonsensical leaks via IMallocSpy. Caching can be disabled by setting the environment -// variable OANOCACHE=1 and using the debug (Checked) version of OLE. Ideally, -// use the complete Checked Build of W2K or extract the appropriate DLL from the -// Checked version of the Service Pack which is freely available. +// 1) OLE caches (among other things) BSTRs, so under a normal OS IMallocSpy reports +// bogus leaks. Caching can be disabled by setting the OANOCACHE=1 environment +// variable and using the debug (Checked) version of OLE. Ideally, use the full +// Checked Build of W2K, or extract the appropriate DLLs from the Checked version +// of the Service Pack, which is freely available. // -// 2) If there are any remaining leaks in OLE, when trying to unregister the spy via -// CoRevokeMallocSpy, it returns E_ACCESSDENIED value and postpones the Release call. -// In practice, Release is never going to call us (W2K). Because some allocations are -// freed only during DLL_PROCESS_DETACH in OLEAUT32.DLL, the spy reports -// them as leaks. It is useful to compare the reported leaks with what the -// CairOLE system outputs to the debug window under the W2K Checked Build. +// 2) If any leaks remain in OLE, an attempt to unregister the spy by calling +// CoRevokeMallocSpy returns E_ACCESSDENIED and defers the call to Release. +// In practice, Release is never called later (W2K). Because some allocations are +// freed only during DLL_PROCESS_DETACH in OLEAUT32.DLL, the spy reports them +// as leaks. It is useful to compare the reported leaks with what the CairOLE +// system reports to the debug window under the W2K Checked Build. // -// 3) Two issues had to be avoided: we do not want the CRT to report a memory -// leak caused by allocating the CMallocSpy instance on the heap. At the same -// time, we need to keep the instance of this object alive as long as possible because OLE will -// call our methods (especially PreFree and PostFree with fSpy == FALSE) even -// after CoRevokeMallocSpy is called. We solve it by copying the object into static -// memory in OleSpyRegister(). The destructor is thus never called and the -// critical section is never destroyed. +// 3) Two problems had to be avoided: the CRT must not report a memory leak caused +// by allocating the CMallocSpy instance on the heap. At the same time, the +// instance of this object must be kept alive as long as possible, because OLE +// calls our methods (especially PreFree and PostFree with fSpy == FALSE) even +// after CoRevokeMallocSpy is called. This is handled by copying the object into +// static memory; see OleSpyRegister(). As a result, the destructor is never +// called and the critical section is never destroyed. // -// 4) When testing under W2K Checked Build, more reports can be obtained from OLE by -// adding a section to win.ini file: +// 4) When testing under the W2K Checked Build, OLE can be made to produce more +// reports by adding a section to the win.ini file: // [CairOLE InfoLevels] // cairole=7 // heap=7 // -// if we want to display detailed messages including call stacks of individual allocations -// we have to set both values to the decimal equivalent of 0xffffffff: +// To display detailed messages including the call stacks of individual allocations, +// both values must be set to the decimal equivalent of 0xffffffff: // [CairOLE InfoLevels] // cairole=4294967295 // heap=4294967295 // -// CairOLE often reports a higher amount of leaks than our spy detects. It is also common -// that CairOLE reports leaks while the spy reports that everything is OK. What -// matters is that these leaks are consistent (for example on Salamander -// start/exit CairOLE reports 13 leaks and about 800 bytes of memory). Since this number -// does not increase, I consider it unimportant. +// CairOLE often reports more leaks than the spy detects. It is also common for +// CairOLE to report leaks while the spy reports that everything is OK. The key +// point is that these leaks should remain constant (for example, on Salamander +// startup and exit CairOLE reports 13 leaks and about 800 bytes of memory). This +// number does not increase, so it is not considered important. // -// 5) The spy will report leaks from calls to functions like SHBrowseForFolder or -// SHGetSpecialFolderLocation. These are not real leaks but cached PIDLs which -// shell32.dll frees only when it detaches from the process. We can recognize -// them by the fact that repeated calls do not increase the number of leaks. +// 5) The spy reports leaks from calls to functions such as SHBrowseForFolder or +// SHGetSpecialFolderLocation. These are not real leaks, but cached PIDLs that +// shell32.dll frees only when it detaches from the process. They can be recognized +// by the fact that repeated calls do not increase the number of leaks. // //------------------------------------------------------------------------- @@ -73,7 +73,7 @@ #endif #define SHID_COMPUTER 0x20 -#define SHID_COMPUTER_1 0x21 // free +#define SHID_COMPUTER_1 0x21 // unused #define SHID_COMPUTER_REMOVABLE (0x20 | DRIVE_REMOVABLE) // 2 #define SHID_COMPUTER_FIXED (0x20 | DRIVE_FIXED) // 3 #define SHID_COMPUTER_REMOTE (0x20 | DRIVE_REMOTE) // 4 @@ -124,7 +124,7 @@ #define IS_VALID_READ_BUFFER(ptr, type, len) (!IsBadReadPtr((ptr), sizeof(type)*(len))) #define IS_VALID_PIDL(ptr) (IsValidPIDL(ptr)) -// IsBadReadPtr throws exceptions in the debug version and we don't want that +// IsBadReadPtr throws exceptions in debug builds, which is undesirable BOOL IsValidPIDL(LPCITEMIDLIST pidl) { @@ -134,7 +134,7 @@ IsValidPIDL(LPCITEMIDLIST pidl) } */ -// IsBadReadPtr throws exceptions in the debug version and we don't want that +// IsBadReadPtr throws exceptions in debug builds, and we do not want that BOOL IsGoodPIDL(LPCITEMIDLIST pidl, int cb) { if (cb < sizeof(USHORT) || cb < (int)(pidl->mkid.cb + sizeof(USHORT))) @@ -742,7 +742,7 @@ CMallocSpy::SpyPreFree(void* pvRequest) size_t CMallocSpy::SpyPreRealloc(void* pvRequest, size_t cbRequest, void** ppv) { - ASSERT(pvRequest != NULL); // in this case OLE calls IMallocSpy::PreAlloc + ASSERT(pvRequest != NULL); // in this case OLE calls IMallocSpy::PreFree ASSERT(cbRequest != 0); // in this case OLE calls IMallocSpy::PreFree size_t cb; @@ -815,7 +815,7 @@ BOOL IsAsciiString(LPSTR pv, int cb) cb--; pv++; } - return (!cb && bRet && !*pv); // we've only had ascii characters, and we're null terminated + return (!cb && bRet && !*pv); // ASCII characters only, and null-terminated } STDAPI _StrRetToBuf(STRRET* psr, LPCITEMIDLIST pidl, LPSTR pszBuf, UINT cchBuf) @@ -904,15 +904,15 @@ BOOL CMallocSpy::DumpLeaks() int leakedAllocs = 0; SPYBLK* psbWalk = _psbHead; - // reach the end and move forward + // Move to the end, then iterate forward if (psbWalk != NULL) while (psbWalk->psbNext != NULL) psbWalk = psbWalk->psbNext; while (psbWalk != NULL) { - // FIXME_X64 psbWalk->cbRequest is of type size_t, yet we print it as %d which is likely wrong - // check the rest of the code where the bug might appear; it probably should be (%Id) - http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx + // FIXME_X64 psbWalk->cbRequest is of type size_t, but we print it as %d, which is probably wrong + // check the rest of the code for places where the same bug may occur; it should probably be (%Id) - http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx sprintf(buff, "[%u] Leaked %Iu bytes at 0x%p, from thread 0x%X", psbWalk->cOrder, psbWalk->cbRequest, (BYTE*)psbWalk + sizeof(SPYBLK), psbWalk->dwThreadId); @@ -1049,9 +1049,9 @@ BOOL OleSpyRegister() // a correct instance of the object CMallocSpy templateSpy; - // dirty hack: we do not want memory leaks in the CRT so the object is not - // allocated on the heap, and we also need a correctly constructed VMT, so - // we copy the contents of the template + // workaround: we do not want CRT memory leaks, so the object is not + // allocated on the heap; at the same time, we need a correctly constructed + // VMT, so we copy the contents of the template object static byte _Spy[sizeof(templateSpy)]; memcpy(_Spy, &templateSpy, sizeof(templateSpy)); diff --git a/src/olespy.h b/src/olespy.h index b6097a3cc..e95916064 100644 --- a/src/olespy.h +++ b/src/olespy.h @@ -11,7 +11,7 @@ // Details on finding OLE leaks are described in OLESPY.CPP. // Attaches our IMallocSpy to OLE; COM must be initialized first. -// If it returns TRUE, the followed functions can be called. +// If it returns TRUE, the following functions can be called. BOOL OleSpyRegister(); // Detaches the Spy from OLE; OleSpyDump can still be called after this function. diff --git a/src/pack.h b/src/pack.h index 1b4c6b427..a97b0fca9 100644 --- a/src/pack.h +++ b/src/pack.h @@ -587,7 +587,7 @@ class CPackerFormatConfigData { public: char* Ext; // list of extensions the archive can have - BOOL UsePacker; // true if PackerIndex is valid (we can also pack) + BOOL UsePacker; // true if PackerIndex is valid (packing is also supported) int PackerIndex; // reference to the packer table int UnpackerIndex; // reference to the unpacker table @@ -662,7 +662,7 @@ class CPackerFormatConfig int GetFormatsCount() { return Formats.Count; } // returns the number of items in the array // BOOL SwapFormats(int index1, int index2); // swaps two items in the array - BOOL MoveFormat(int srcIndex, int dstIndex); // moves the item + BOOL MoveFormat(int srcIndex, int dstIndex); // moves the format void DeleteFormat(int index); int GetUnpackerIndex(int index) { return Formats[index]->UnpackerIndex; } @@ -757,7 +757,7 @@ void PackAutoconfig(HWND parent); // runs the external program cmdLine and interprets the return code according to errorTable BOOL PackExecute(HWND parent, char* cmdLine, const char* currentDir, TPackErrorTable* const errorTable); -// callback for enumeration by mask (used to extract all files matching the mask) +// callback for enumeration by mask (used to unpack all files matching the mask) const char* WINAPI PackEnumMask(HWND parent, int enumFiles, BOOL* isDir, CQuadWord* size, const CFileData** fileData, void* param, int* errorOccured); diff --git a/src/pack1.cpp b/src/pack1.cpp index 8a4c334f2..5748d3375 100644 --- a/src/pack1.cpp +++ b/src/pack1.cpp @@ -19,8 +19,7 @@ // // Pointer to the error handling function -BOOL(*PackErrorHandlerPtr) -(HWND parent, const WORD errNum, ...) = EmptyErrorHandler; +BOOL (*PackErrorHandlerPtr)(HWND parent, const WORD errNum, ...) = EmptyErrorHandler; const char* SPAWN_EXE_NAME = "salspawn.exe"; const char* SPAWN_EXE_PARAMS = "-c10000"; @@ -152,7 +151,7 @@ const SPackBrowseTable PackBrowseTable[] = char* PackGetField(char* buffer, const int index, const int nameidx, const char separator) { CALL_STACK_MESSAGE5("PackGetField(%s, %d, %d, %u)", buffer, index, nameidx, separator); - // the requested item does not exist for the given archiver program + // the requested item does not exist for the given archiver if (index == 0) return NULL; @@ -170,7 +169,7 @@ char* PackGetField(char* buffer, const int index, const int nameidx, const char { // skip the item if (i == nameidx) - // if we are on the name, only a newline is a separator + // for the name field, only a newline is a separator while (*buffer != '\0' && *buffer != '\n') buffer++; else @@ -180,13 +179,13 @@ char* PackGetField(char* buffer, const int index, const int nameidx, const char *buffer != separator) buffer++; - // skip the spaces behind it + // skip the spaces after it while (*buffer != '\0' && (*buffer == ' ' || *buffer == '\t' || *buffer == '\n' || *buffer == 0x10 || *buffer == 0x11 || *buffer == separator)) buffer++; - // we are on the next item + // now at the next item i++; } return buffer; @@ -364,7 +363,7 @@ BOOL PackScanLine(char* buffer, CSalamanderDirectory& dir, const int index, t.wYear += 2000; } - // ted cas + // time idx = configTable->TimeIdx; if (ARJHack) idx--; @@ -575,8 +574,8 @@ BOOL PackScanLine(char* buffer, CSalamanderDirectory& dir, const int index, // IN: panel is Salamander's file panel // archiveFileName is the name of the archive file to be listed // OUT: dir is filled with archive data -// pluginData is the interface to column data defined by the archiver plug-in -// plugin is the plug-in record that performed ListArchive +// pluginData is the interface to column data defined by the archiver plugin +// plugin is the plugin record that performed ListArchive BOOL PackList(CFilesWindow* panel, const char* archiveFileName, CSalamanderDirectory& dir, CPluginDataInterfaceAbstract*& pluginData, CPluginData*& plugin) @@ -717,7 +716,7 @@ BOOL PackList(CFilesWindow* panel, const char* archiveFileName, CSalamanderDirec return (*PackErrorHandlerPtr)(NULL, IDS_PACKERR_PROCESS, SpawnExe, GetErrorText(err)); } - // We no longer need these handles; the child will close the duplicates, we keep only StdOutRd + // These handles are no longer needed; the child closes the duplicates, and we keep only StdOutRd HANDLES(CloseHandle(StdOutWr)); HANDLES(CloseHandle(StdErrWr)); @@ -872,7 +871,7 @@ BOOL PackList(CFilesWindow* panel, const char* archiveFileName, CSalamanderDirec // a few local variables char* line = NULL; // buffer for building a "multi-line line" int lines = 0; // how many lines of the multi-line item we have read - int validData = 0; // whether we read header/footer or valid data + int validData = 0; // whether we are reading header/footer data or valid data int toSkip = browseTable->LinesToSkip; int alwaysSkip = browseTable->AlwaysSkip; int linesPerFile = browseTable->LinesPerFile; @@ -886,7 +885,7 @@ BOOL PackList(CFilesWindow* panel, const char* archiveFileName, CSalamanderDirec switch (validData) { case 0: // we are in the header - // determine whether we stay in it + // determine whether we stay in the header if (!strncmp(lineArray[i], browseTable->StartString, strlen(browseTable->StartString))) validData++; @@ -977,13 +976,13 @@ BOOL PackList(CFilesWindow* panel, const char* archiveFileName, CSalamanderDirec free(line); line = NULL; if (!ret) - return FALSE; // no need to call the error function, PackScanLine already did the call + return FALSE; // no need to call the error function; PackScanLine already called it // initialize variables lines = 0; } - // if we ended somewhere else than in the footer, we have a problem + // if we ended up anywhere other than in the footer, we have a problem if (validData < 2) return (*PackErrorHandlerPtr)(NULL, IDS_PACKERR_PARSE); @@ -1036,7 +1035,7 @@ BOOL PackUC2List(const char* archiveFileName, CPackLineArray& lineArray, if (!strncmp(txtPtr, "END", 3)) break; - // if the item is LIST, we determine which directory we are in + // if the item is LIST, determine which directory we are in if (!strncmp(txtPtr, "LIST", 4)) { // run to the start of the name @@ -1067,7 +1066,7 @@ BOOL PackUC2List(const char* archiveFileName, CPackLineArray& lineArray, continue; } - // if the item is FILE/DIR, we create a file/directory + // if the item is FILE/DIR, we create a file or directory if (!strncmp(txtPtr, "DIR", 3) || !strncmp(txtPtr, "FILE", 4)) { // what is it, a file or a directory? @@ -1090,8 +1089,8 @@ BOOL PackUC2List(const char* archiveFileName, CPackLineArray& lineArray, newfile.DosName = NULL; newfile.PluginData = -1; // just -1, ignored - // main parsing loop of a file/directory - // ends once we hit an unknown keyword + // the main file/directory parsing loop + // ends as soon as we encounter an unknown keyword while (1) { // prepare the next line @@ -1294,7 +1293,7 @@ BOOL PackUC2List(const char* archiveFileName, CPackLineArray& lineArray, free(newfile.Name); return (*PackErrorHandlerPtr)(NULL, IDS_PACKERR_GENERAL, buffer); } - // and finally just create a new object + // and finally just create a new file object newfile.IsOffline = 0; if (isDir) { @@ -1677,7 +1676,7 @@ const char* WINAPI PackEnumMask(HWND parent, int enumFiles, BOOL* isDir, CQuadWo if (fileData != NULL) *fileData = NULL; - // if there are no more masks return NULL - finished + // if there are no more masks, return NULL - end if (param == NULL || *(char**)param == NULL) return NULL; @@ -1756,16 +1755,16 @@ const char* WINAPI PackEnumMask(HWND parent, int enumFiles, BOOL* isDir, CQuadWo // Function for extracting a single file from an archive (for the viewer). // // RET: returns TRUE on success, FALSE on error -// on error the callback function *PackErrorHandlerPtr is called +// on error, calls the callback function *PackErrorHandlerPtr // IN: panel is the Salamander file panel -// archiveFileName is the name of the archive from which we extract -// nameInArchive is the name of the file we extract +// archiveFileName is the name of the archive from which the file is extracted +// nameInArchive is the name of the file to extract // fileData is a pointer to the CFileData structure of the extracted file // targetDir is the path where the file should be extracted -// newFileName (if not NULL) is the new name of the extracted file (during extraction, the file -// must be renamed from its original name to this new one) -// renamingNotSupported (only if newFileName is not NULL) - set TRUE if the plugin -// does not support renaming during extraction, Salamander will show an error +// newFileName (if not NULL) is the new name of the extracted file (during extraction, +// the file must be renamed from its original name to this new name) +// renamingNotSupported (only if newFileName is not NULL) - set to TRUE if the plugin +// does not support renaming during extraction; Salamander will display an error message // OUT: BOOL PackUnpackOneFile(CFilesWindow* panel, const char* archiveFileName, diff --git a/src/pack2.cpp b/src/pack2.cpp index c6a4f2ebd..94ad5af5b 100644 --- a/src/pack2.cpp +++ b/src/pack2.cpp @@ -189,12 +189,12 @@ BOOL PackCompress(HWND parent, CFilesWindow* panel, const char* archiveFileName, if (archiveRoot != NULL && *archiveRoot != '\0') { strcpy(archiveRootPath, archiveRoot); - if (!modifyTable->CanPackToDir) // the archiver program does not support it + if (!modifyTable->CanPackToDir) // the archiver does not support it { if ((*PackErrorHandlerPtr)(parent, IDS_PACKQRY_ARCPATH)) strcpy(archiveRootPath, "\\"); // the user wants to ignore it else - return FALSE; // the user will mind + return FALSE; // the user objects } } else @@ -355,7 +355,7 @@ BOOL PackUniversalCompress(HWND parent, const char* command, TPackErrorTable* co return (*PackErrorHandlerPtr)(parent, IDS_PACKERR_PATH, buffer); } - // and put it into the list + // and add it to the list file if (!isDir) { if (fprintf(listFile, "%s\n", namecnv) <= 0) @@ -524,7 +524,7 @@ BOOL PackUniversalCompress(HWND parent, const char* command, TPackErrorTable* co { HANDLES(FindClose(find)); // this name already exists with some extension, searching further (*PackErrorHandlerPtr)(parent, IDS_PACKERR_UNABLETOREN, src, dst); - return TRUE; // succeeded, only the resulting archive names differ slightly (even multivolume) + return TRUE; // Succeeded; only the names of the resulting archive differ slightly (including multivolume archives) } } else @@ -658,7 +658,7 @@ BOOL PackDelFromArc(HWND parent, CFilesWindow* panel, const char* archiveFileNam CharToOem(name, namecnv); else strcpy(namecnv, name); - // and put it into the list + // and add it to the list file if (!isDir) { if (fprintf(listFile, "%s%s\n", rootPath, namecnv) <= 0) diff --git a/src/pack3.cpp b/src/pack3.cpp index 01ca3822d..2902f9372 100644 --- a/src/pack3.cpp +++ b/src/pack3.cpp @@ -585,10 +585,10 @@ BOOL CPackerFormatConfig::SetFormat(int index, const char* ext, BOOL usePacker, } } -// returns the format table index + 1 or FALSE (0) when it's not an archive +// Returns the format table index + 1, or FALSE (0) if it is not an archive. int CPackerFormatConfig::PackIsArchive(const char* archiveName, int archiveNameLen) { - // j.r. I disabled the macro because PackIsArchive is heavily called from CFilesWindow::CommonRefresh() + // j.r. The macro was disabled because PackIsArchive is called heavily from CFilesWindow::CommonRefresh() CALL_STACK_MESSAGE_NONE // CALL_STACK_MESSAGE2("PackIsArchive(%s)", archiveName); if (archiveName[0] == 0) @@ -755,10 +755,10 @@ CArchiverConfig::CArchiverConfig(/*BOOL disableDefaultValues*/) : Archivers(20, 10) { /* - // set default values if it is not disabled - if (!disableDefaultValues) - AddDefault(0); -*/ + // set default values unless this is disabled + if (!disableDefaultValues) + AddDefault(0); + */ } void CArchiverConfig::InitializeDefaultValues() @@ -840,7 +840,7 @@ void CArchiverConfig::AddDefault(int SalamVersion) // initializes the configuration based on another configuration BOOL CArchiverConfig::Load(CArchiverConfig& src) { - // clear what we have (if we have anything) + // clear what we have, if anything DeleteAllArchivers(); // and add what we received int i; @@ -951,10 +951,10 @@ BOOL CArchiverConfig::Save(int index, HKEY hKey) d = GetArchiverUID(index); if (ret) ret &= SetValue(hKey, SALAMANDER_PPC_UID, REG_DWORD, &d, sizeof(d)); - // (saves the title) - because it is translated it can no longer be used for identification - // of the archiver (UID is now used instead), there is no point in storing it + // (saves the title) - because it is translated, it can no longer be used to identify the archiver + // (UID is used instead), so there is no point in storing it // if (ret) ret &= SetValue(hKey, SALAMANDER_PPC_TITLE, REG_SZ, GetArchiverTitle(index), -1); - // save the executable path + // saves the executable path if (ret) ret &= SetValue(hKey, SALAMANDER_PPC_PACKEXE, REG_SZ, GetPackerExeFile(index), -1); // save whether packer and unpacker are the same @@ -1014,7 +1014,7 @@ BOOL CArchiverConfig::Load(HKEY hKey) { CArchiverConfigData* arch = Archivers[i]; // for keys that are complete and whose title matches the default value, take over their paths - if (Configuration.ConfigVersion <= 64 && stricmp(title, arch->Title) == 0 || // Title is now translated and cannot be used anymore + if (Configuration.ConfigVersion <= 64 && stricmp(title, arch->Title) == 0 || // The title is now localized and can no longer be used Configuration.ConfigVersion > 64 && uid == arch->UID) // thus we introduced a standard UID { SetPackerExeFile(i, packExe); @@ -1040,22 +1040,22 @@ CArchiverConfig::Load(HKEY hKey) if (ret) ret &= GetValue(hKey, SALAMANDER_PPC_TITLE, REG_SZ, title, max); // loads the packing executable if (ret) ret &= GetValue(hKey, SALAMANDER_PPC_PACKEXE, REG_SZ, packExe, max); - // determine whether the unpacker is the same + // determines whether the unpacker is the same if (ret) ret &= GetValue(hKey, SALAMANDER_PPC_EXESAME, REG_DWORD, &exesAreSame, sizeof(DWORD)); - // loads the unpacker executable, if it is different from the packer + // loads the unpacking executable if it differs from the packing executable if (!exesAreSame) if (ret) ret &= GetValue(hKey, SALAMANDER_PPC_UNPACKEXE, REG_SZ, unpackExe, max); EPackExeType type; const char *name, *variablePack, *variableUnpack = NULL, *exePack, *exeUnpack = NULL; - // and now convert to a newer configuration - missing information is taken from defaults - // (none of it is configurable anyway :-)) + // convert to the newer configuration; missing information is taken from defaults + // (none of it is configurable anyway) if (ret) { int index; if ((index = AddArchiver()) == -1) return FALSE; - // I now assume the indices in the configuration keep their order. If not, nothing is loaded + // assumes the indices in the configuration keep the same order; otherwise nothing is loaded switch (index) { case 0: @@ -1137,14 +1137,14 @@ CArchiverConfig::Load(HKEY hKey) Archivers.Delete(index); // To avoid leaving an uninitialized structure; Salamander 2.0 crashed in SaveConfig return FALSE; } - // verify we are really adding the packer we think we are adding + // verifies that the packer being added is the expected one if (strncmp(title, name, 10) || (exesAreSame && exeUnpack != NULL) || (!exesAreSame && exeUnpack == NULL)) { TRACE_E("Inconsistency in configuration of packers."); Archivers.Delete(index); // To avoid leaving an uninitialized structure; Salamander 2.0 crashed in SaveConfig return FALSE; } - // and set all information + // sets all information ret &= SetArchiver(index, name, type, exesAreSame, variablePack, variableUnpack, exePack, exeUnpack, packExe, unpackExe); } @@ -1235,7 +1235,7 @@ const char* WINAPI PackExpArcDosName(HWND msgParent, void* param) if (data->DOSTmpFilePossible) // use a substitute name { - if (data->DOSTmpFile[0] == 0) // it needs to be generated + if (data->DOSTmpFile[0] == 0) // generate the temporary DOS name { char path[MAX_PATH + 50]; strcpy(path, data->ArcName); @@ -1262,8 +1262,8 @@ const char* WINAPI PackExpArcDosName(HWND msgParent, void* param) // while (--ext > data->ArcName && *ext != '\\' && *ext != '.'); while (--ext >= data->ArcName && *ext != '\\' && *ext != '.') ; - // if (ext > data->ArcName && *ext == '.' && *(ext - 1) != '\\') // copy the archive extension (used by multi-volume archivers: ARJ->A01,A02,...); ".cvspass" in Windows is an extension ... - if (ext >= data->ArcName && *ext == '.') // copy the archive extension (used by multi-volume archivers: ARJ->A01,A02,...) + // if (ext > data->ArcName && *ext == '.' && *(ext - 1) != '\\') // copy the archive extension (used by multi-volume archivers: ARJ->A01,A02,...); in Windows, ".cvspass" is also an extension ... + if (ext >= data->ArcName && *ext == '.') // copy the archive extension (used by multivolume archivers: ARJ -> A01, A02, ...) { int count = 4; // copy '.' plus at most 3 allowed extension characters (of the 8.3 format) while (count-- && *ext < 128 && *ext != '[' && *ext != ']' && @@ -1428,8 +1428,8 @@ PackExpExeName(unsigned int index, BOOL unpacker = FALSE) exe = ArchiverConfig.GetUnpackerExecutable(index); else { - // on older Windows it was impossible to redirect output from a DOS program in a directory - // with a long name; I no longer feel like patching and risking this that it won't work + // on older Windows, it was not possible to redirect output from a DOS program in a directory + // with a long name; this is left unchanged to avoid risking that it will stop working buff[0] = '\0'; DWORD len = GetShortPathName(exe, buff, MAX_PATH); // if the path was shortened successfully, return the short name @@ -1723,8 +1723,8 @@ BOOL PackExecute(HWND parent, char* cmdLine, const char* currentDir, TPackErrorT POINT p; if (MultiMonGetDefaultWindowPos(MainWindow->HWindow, &p)) { - // if the main window is on another monitor we should open the new window there - // preferably at the default position (as on the primary monitor) + // if the main window is on another monitor, we should also open the new window there + // preferably at the default position, as on the primary monitor si.dwFlags |= STARTF_USEPOSITION; si.dwX = p.x; si.dwY = p.y; @@ -1782,16 +1782,16 @@ BOOL PackExecute(HWND parent, char* cmdLine, const char* currentDir, TPackErrorT DWORD ret; do { - /* // Petr: pumping only WM_PAINT leads to blocking all other instances of Salamander - // (even newly started ones) and other softwares (at least during Paste), if we - // put a file or directory on the clipboard before packing. Accessing clipboard - // data causes OLE to communicate with this process which doesn't respond - // because it pumps only WM_PAINT. - // Original Tom's variant: - ret = MsgWaitForMultipleObjects(1, objects, FALSE, - PackWinTimeout <= 0 ? INFINITE : PackWinTimeout - elapsed, - QS_PAINT); -*/ + /* // Petr: pumping only WM_PAINT blocks all other Salamander instances + // (including newly started ones) and other applications (at least during Paste) if a + // file or directory is placed on the clipboard before packing. When clipboard data is + // accessed, OLE tries to communicate with this process, but it does not respond + // because it pumps only WM_PAINT. + // Tom's original variant: + ret = MsgWaitForMultipleObjects(1, objects, FALSE, + PackWinTimeout <= 0 ? INFINITE : PackWinTimeout - elapsed, + QS_PAINT); + */ ret = MsgWaitForMultipleObjects(1, objects, FALSE, PackWinTimeout <= 0 ? INFINITE : PackWinTimeout - elapsed, QS_ALLINPUT); @@ -1799,10 +1799,10 @@ BOOL PackExecute(HWND parent, char* cmdLine, const char* currentDir, TPackErrorT { // if a message arrived, handle it MSG msg; - /* // Original Tom's variant: (see description above) - while (PeekMessage(&msg, NULL, WM_PAINT, WM_PAINT, PM_REMOVE)) - DispatchMessage(&msg); -*/ + /* // Tom's original variant: (see description above) + while (PeekMessage(&msg, NULL, WM_PAINT, WM_PAINT, PM_REMOVE)) + DispatchMessage(&msg); + */ while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); @@ -1834,9 +1834,9 @@ BOOL PackExecute(HWND parent, char* cmdLine, const char* currentDir, TPackErrorT } while (win != NULL); do { - /* // Original Tom's variant: (see description above) - ret = MsgWaitForMultipleObjects(1, objects, FALSE, INFINITE, QS_PAINT); -*/ + /* // Tom's original variant: (see description above) + ret = MsgWaitForMultipleObjects(1, objects, FALSE, INFINITE, QS_PAINT); + */ ret = MsgWaitForMultipleObjects(1, objects, FALSE, INFINITE, QS_ALLINPUT); MSG msg; if (ret == WAIT_OBJECT_0 + 1) @@ -1926,9 +1926,9 @@ BOOL PackExecute(HWND parent, char* cmdLine, const char* currentDir, TPackErrorT } } // - // now come the external program errors + // external program errors follow // - // if errorTable == NULL, no translation is done (table doesn't exist) + // if errorTable == NULL, no translation is done (the table does not exist) if (!errorTable) { char buffer[1000]; diff --git a/src/packac.cpp b/src/packac.cpp index 172d32e91..262c15a9f 100644 --- a/src/packac.cpp +++ b/src/packac.cpp @@ -400,7 +400,7 @@ void CPackACDialog::LayoutControls() // block finished HANDLES(EndDeferWindowPos(hdwp)); } - // and adjust the column width in the list view + // adjust the list view column widths ListView->SetColumnWidth(); } @@ -753,7 +753,7 @@ void CPackACDialog::AddToExtensions(int foundIndex, int packerIndex, CPackACPack int found; do { - // look for who is using us + // find who uses us buffer[0] = '.'; int j = 1; while (*ptr != ';' && *ptr != '\0') @@ -773,10 +773,10 @@ void CPackACDialog::AddToExtensions(int foundIndex, int packerIndex, CPackACPack { int pos; CPackACPacker* p = NULL; - // if we are working with a packer adjust the record for the packer + // If we are working with a packer, update the packer entry if (foundPacker->GetPackerType() == Packer_Packer || foundPacker->GetPackerType() == Packer_Standalone) { - // if we used a packer, find out whether we found it + // if we used a packer, check whether we found it if (PackerFormatConfig.GetUsePacker(found - 1)) { pos = PackerFormatConfig.GetPackerIndex(found - 1); @@ -818,7 +818,7 @@ void CPackACDialog::AddToExtensions(int foundIndex, int packerIndex, CPackACPack if (p->GetArchiverIndex() == pos && p->GetPackerType() != Packer_Packer) break; } - // if the existing packer is not a plugin, was not found, or is different and we have a 32-bit one + // if the current packer is not a plugin, was not found, or is different and we have a 32-bit one if (pos >= 0 && pos != packerIndex && (p == NULL || p->GetSelectedFullName() == NULL || foundPacker->GetExeType() == EXE_32BIT)) { @@ -987,8 +987,8 @@ void CPackACDialog::RemoveFromCustom(int foundIndex, int packerIndex) CALL_STACK_MESSAGE3("CPackACDialog::RemoveFromCustom(%d, %d)", foundIndex, packerIndex); // a custom packer/unpacker is removed if: - // 1) the packer wasn't found or was found but not selected (fullName == NULL) - // 2) the invoked program is a variable corresponding to this packer + // 1) the packer was not found, or it was found but not selected (fullName == NULL) + // 2) the invoked program is the variable corresponding to this packer CPackACPacker* p = NULL; char variable[50]; @@ -1218,8 +1218,8 @@ int CPackACPacker::CheckAndInsert(const char* path, const char* fileName, FILETI ref++; act++; } - // the extension has been checked already; now verify if we are at the end of the string - // and whether other requirements are met (currently only the type, we will see in the future...) + // the extension has already been checked; now just verify that we are at the end of the string + // and that the other requirements are met (currently only the type; more may be added in the future) if (*ref == '\0' && act == &fileName[lstrlen(fileName) - 4] && exeType == Type) { @@ -1311,7 +1311,7 @@ int CPackACArray::AddAndCheck(CPackACFound* member) void CPackACArray::InvertSelect(int index) { CALL_STACK_MESSAGE2("CPackACArray::InvertSelect(%d)", index); - // the user must be allowed to select nothing + // the user must be allowed to leave nothing selected if (At(index)->Selected) At(index)->Selected = FALSE; else @@ -1401,7 +1401,7 @@ CPackACListView::GetPacker(int item, int* index) return PackersTable->At(archiver); } -// find an archiver by the index in the list view +// finds an archiver by its index in the list view BOOL CPackACListView::FindArchiver(unsigned int listViewIndex, unsigned int* archiver, unsigned int* arcIndex) { @@ -1492,7 +1492,7 @@ void CPackACListView::SetColumnWidth() { CALL_STACK_MESSAGE1("CPackACListView::SetColumnWidth()"); RECT r; - // find out the size we must fit into + // determine the size we must fit into GetClientRect(HWindow, &r); // total width DWORD cx = r.right - r.left - 1; @@ -1519,7 +1519,7 @@ BOOL CPackACListView::ConsiderItem(const char* path, const char* fileName, FILET // initialization BOOL stop = FALSE; int totalCount = 0; - // go through all packers to see if it is the one we are looking for + // go through all packers to see whether any of them is one of the ones we are looking for int i; for (i = 0; i < PackersTable->Count; i++) { diff --git a/src/packers.cpp b/src/packers.cpp index 856224b0d..aa6c51e1b 100644 --- a/src/packers.cpp +++ b/src/packers.cpp @@ -219,7 +219,7 @@ void CPackerConfig::AddDefault(int SalamVersion) SetPacker(index, 3, "PAK (Plugin)", "pak", TRUE); case 3: // added after beta2 case 4: // beta 3 but with old configuration (contains $(SpawnName)) - case 5:; // what is new in beta4? + case 5:; // new in beta4? // if ((index = AddPacker()) == -1) return; // SetPacker(index, 2, "TAR (Plugin)", "tgz", TRUE); } @@ -359,7 +359,7 @@ void CPackerConfig::AddDefault(int SalamVersion) free(cmdC); // an ugly hack because of RAR if (i == 2) - // if it's RAR we cannot tell whether it is 16-bit or 32-bit directly, only from long-name support + // for RAR, we cannot tell directly whether it is 16-bit or 32-bit, only from long-name support if (GetPackerSupLongNames(index)) cmdC = DupStr(PackConversionTable[i].variable); else @@ -373,7 +373,7 @@ void CPackerConfig::AddDefault(int SalamVersion) free(cmdM); // an ugly hack because of RAR if (i == 2) - // if it's RAR we cannot tell whether it is 16-bit or 32-bit directly, only from long-name support + // if it is RAR, we cannot tell directly whether it is 16-bit or 32-bit, only by long-name support if (GetPackerSupLongNames(index)) cmdM = DupStr(PackConversionTable[i].variable); else @@ -424,7 +424,7 @@ void CPackerConfig::AddDefault(int SalamVersion) { if ((GetPackerOldType(index) && GetPackerType(index) != 1) || (!GetPackerOldType(index) && GetPackerType(index) != CUSTOMPACKER_EXTERNAL)) - { // take only plug-ins (not external packers) + { // take only plugins (not external packers) char* s = Packers[index]->Title; char* f; if (s != NULL && (f = strstr(s, "(Internal)")) != NULL) // contains (Internal) @@ -483,7 +483,7 @@ void CPackerConfig::AddDefault(int SalamVersion) s = DupStr(newLHAMoveArgs); if (s != NULL) { - free(Packers[index]->CmdArgsMove); // cannot be NULL (old arguments here) + free(Packers[index]->CmdArgsMove); // cannot be NULL (it contains the old arguments) Packers[index]->CmdArgsMove = s; } } @@ -617,7 +617,7 @@ void CPackerConfig::AddDefault(int SalamVersion) // convert to new arguments (added "-scol") free(Packers[index]->CmdArgsCopy); // cannot be NULL (old arguments here) Packers[index]->CmdArgsCopy = DupStr(newRAR5CopyVolArgs); - free(Packers[index]->CmdArgsMove); // cannot be NULL (old arguments here) + free(Packers[index]->CmdArgsMove); // cannot be NULL (the old arguments are stored here) Packers[index]->CmdArgsMove = DupStr(newRAR5MoveVolArgs); } } @@ -905,7 +905,7 @@ BOOL CPackerConfig::Load(HKEY hKey) if (ret) { if (!GetValue(hKey, SALAMANDER_CPU_ANSILIST, REG_DWORD, &needANSI, sizeof(DWORD))) - needANSI = FALSE; // in older versions it wasn't present, assumed FALSE + needANSI = FALSE; // in older versions, it was not present; FALSE was assumed } if (ret) @@ -1077,7 +1077,7 @@ void CUnpackerConfig::AddDefault(int SalamVersion) } case 3: // what was added after beta2 case 4: // beta 3 but without the $(SpawnName) variable - // in older versions the $(SpawnName) variable might exist, it no longer does - we must remove it + // older versions may contain the $(SpawnName) variable, which no longer exists, so we must remove it for (index = 0; index < GetUnpackersCount(); index++) if (GetUnpackerType(index) == 1) { @@ -1126,7 +1126,7 @@ void CUnpackerConfig::AddDefault(int SalamVersion) free(cmd); // an ugly hack because of RAR if (i == 2) - // if it's RAR we cannot tell whether it is 16-bit or 32-bit directly, only from long-name support + // if it is RAR, we cannot tell directly whether it is 16-bit or 32-bit, only by long-name support if (GetUnpackerSupLongNames(index)) cmd = DupStr(PackConversionTable[i].variable); else @@ -1173,7 +1173,7 @@ void CUnpackerConfig::AddDefault(int SalamVersion) { if ((GetUnpackerOldType(index) && GetUnpackerType(index) != 1) || (!GetUnpackerOldType(index) && GetUnpackerType(index) != CUSTOMUNPACKER_EXTERNAL)) - { // take only plug-ins (not external unpackers) + { // take only plugins (not external unpackers) char* s = Unpackers[index]->Title; char* f; if (s != NULL && (f = strstr(s, "(Internal)")) != NULL) // contains (Internal) @@ -1238,7 +1238,7 @@ void CUnpackerConfig::AddDefault(int SalamVersion) s = DupStr(newPKZIP25Ext); if (s != NULL) { - free(Unpackers[index]->Ext); // cannot be NULL (old arguments here) + free(Unpackers[index]->Ext); // cannot be NULL (the old arguments are here) Unpackers[index]->Ext = s; } } @@ -1272,7 +1272,7 @@ void CUnpackerConfig::AddDefault(int SalamVersion) strcmp(extrArgs, "x \"$(ArchiveFullName)\" @\"$(ListFullName)\"") == 0) { // convert to new arguments (added "-scol") - free(Unpackers[index]->CmdArgsExtract); // cannot be NULL (old arguments here) + free(Unpackers[index]->CmdArgsExtract); // cannot be NULL (the old arguments are present) Unpackers[index]->CmdArgsExtract = DupStr(newRAR5Args); } } @@ -1518,7 +1518,7 @@ BOOL CUnpackerConfig::Load(HKEY hKey) if (ret) { if (!GetValue(hKey, SALAMANDER_CPU_ANSILIST, REG_DWORD, &needANSI, sizeof(DWORD))) - needANSI = FALSE; // in older versions it wasn't present, assumed FALSE + needANSI = FALSE; // In older versions, it was not present; FALSE was assumed. } if (ret) diff --git a/src/plugins.h b/src/plugins.h index bb609229e..516e7dab0 100644 --- a/src/plugins.h +++ b/src/plugins.h @@ -138,7 +138,7 @@ class CPluginInterfaceForArchiverEncapsulation } // ******************************************************************************** - // WARNING: lower thread priority before executing plug-in operations! + // WARNING: lower thread priority before executing plugin operations! // ******************************************************************************** }; @@ -301,23 +301,23 @@ class CPluginInterfaceForFSEncapsulation // called right after ChangeDriveMenuItemContextMenu -- the plugin is definitely loaded void ExecuteChangeDrivePostCommand(int panel, int postCmd, void* postCmdParam); - // direct interface call (does not go through CPluginData + InitDLL), call-stack-message is created; + // direct interface call (does not go through CPluginData + InitDLL), call-stack message is created; // called only when 'pluginFS' is in a panel - the plugin is definitely loaded void ExecuteOnFS(int panel, CPluginFSInterfaceAbstract* pluginFS, const char* pluginFSName, int pluginFSNameIndex, CFileData& file, int isDir); - // direct interface call (does not go through CPluginData + InitDLL), call-stack-message is created; + // direct interface call (does not go through CPluginData + InitDLL), call-stack message is created; // called only when 'pluginFS' exists (either in a panel or detached) - the plugin is definitely loaded BOOL DisconnectFS(HWND parent, BOOL isInPanel, int panel, CPluginFSInterfaceAbstract* pluginFS, const char* pluginFSName, int pluginFSNameIndex); - // direct interface call (does not go through CPluginData + InitDLL), call-stack-message is created; + // direct interface call (does not go through CPluginData + InitDLL), call-stack message is created; // called only when the plugin is loaded (its FS is open) void ConvertPathToInternal(const char* fsName, int fsNameIndex, char* fsUserPart); - // direct interface call (does not go through CPluginData + InitDLL), call-stack-message is created; + // direct interface call (does not go through CPluginData + InitDLL), call-stack message is created; // called only when the plugin is loaded (its FS is open) void ConvertPathToExternal(const char* fsName, int fsNameIndex, char* fsUserPart); @@ -990,10 +990,10 @@ class CPluginFSInterfaceEncapsulation // returns a reference to the string from the CPluginData of the plugin that created this interface const char* GetVersion() { return Version; } - // returns the plug-in interface that created the FS interface (FS part) + // returns the plugin interface that created the FS interface (FS part) CPluginInterfaceForFSEncapsulation* GetPluginInterfaceForFS() { return &IfaceForFS; } - // returns the plug-in interface that created the FS interface (base class) + // returns the plugin interface that created the FS interface (base class) CPluginInterfaceAbstract* GetPluginInterface() { return Iface; } // returns the name of the opened FS @@ -1362,7 +1362,7 @@ class CPluginFSInterfaceEncapsulation LoadStr(IDS_ERRORTITLE), MB_OK | MB_ICONEXCLAMATION); if (invalidPathOrCancel != NULL) *invalidPathOrCancel = TRUE; - return FALSE; // let the user fix the target path (copy/move to this path is not supported) + return FALSE; // let the user fix the target path (copying/moving to this path is not supported) } } } @@ -1853,7 +1853,7 @@ class CSalamanderPasswordManager : public CSalamanderPasswordManagerAbstract class CSalamanderGeneral : public CSalamanderGeneralAbstract { protected: - CPluginInterfaceAbstract* Plugin; // plug-in used by this iface; !!! note: may be NULL + CPluginInterfaceAbstract* Plugin; // plugin used by this iface; !!! note: may be NULL // (plugin not loaded) or -1 (during the plugin's entry point) char HelpFileName[MAX_PATH]; // if not empty, this is the name (without path) of the .chm help file used by this plugin (optimization only, not stored anywhere) @@ -2362,7 +2362,7 @@ struct CPluginMenuItem DWORD StateMask; // hiword is an OR mask, loword is an AND mask; if it is -1, // CPluginInterfaceAbstract::GetMenuItemState is used DWORD SkillLevel; // which user levels should see this item MENU_SKILLLEVEL_XXX - int ID; // plug-in UID - unique item number within the plugin + int ID; // plugin UID - unique item number within the plugin DWORD HotKey; // hot key: LOWORD=hotkey(LOBYTE:vk, HIBYTE:mods), HIWORD=(0:user kept it, 1:user changed it,it is dirty) // helper data: @@ -2473,7 +2473,7 @@ struct CPluginData #endif protected: - HINSTANCE DLL; // handle of the plug-in’s DLL file + HINSTANCE DLL; // handle of the plugin’s DLL file CPluginInterfaceEncapsulation PluginIface; // plugin interface (set to -1 during the entry point call) CPluginInterfaceForArchiverEncapsulation PluginIfaceForArchiver; // plugin interface: archiver CPluginInterfaceForViewerEncapsulation PluginIfaceForViewer; // plugin interface: viewer @@ -2501,13 +2501,13 @@ struct CPluginData CPluginInterfaceForViewerEncapsulation* GetPluginInterfaceForViewer() { return &PluginIfaceForViewer; } CPluginInterfaceForThumbLoaderEncapsulation* GetPluginInterfaceForThumbLoader() { return &PluginIfaceForThumbLoader; } - // loads the DLL into memory, attaches to it and verifies the validity of the stored information (SupportXXX, etc.) - // loads only a DLL that matches exactly, otherwise the plugin reinstallation is required - // 'parent' is the parent window for message boxes; if it is 'quiet'==TRUE no error messages are shown + // loads the DLL into memory, attaches to it, and verifies the validity of the information stored here (SupportXXX, etc.) + // loads only a DLL that matches exactly; otherwise, the plugin must be reinstalled + // 'parent' is the parent window for message boxes; if 'quiet'==TRUE, no error messages are shown // (however, messages from inside the plugin are still displayed) - // 'waitCursor' shows the Wait cursor while loading the DLL library - // if 'showUnsupOnX64' is TRUE, a message box warns about plugins unsupported on x64 - // if 'releaseDynMenuIcons' is TRUE, plugins`s dynamic menu icons are released (they are reloaded before opening the menu) + // 'waitCursor' shows the wait cursor while the DLL is being loaded + // if 'showUnsupOnX64' is TRUE, a message box is shown for plugins unsupported on x64 + // if 'releaseDynMenuIcons' is TRUE, the plugin's dynamic menu icons are released (they are reacquired before the menu is opened) BOOL InitDLL(HWND parent, BOOL quiet = FALSE, BOOL waitCursor = TRUE, BOOL showUnsupOnX64 = TRUE, BOOL releaseDynMenuIcons = TRUE); @@ -2581,10 +2581,10 @@ struct CPluginData BOOL HelpForMenuItem(HWND parent, int index, int suid, BOOL& helpDisplayed); // plugin call: BuildMenu - // let the plugin build a new menu; 'parent' is the parent message box window; + // lets the plugin build a new menu; 'parent' is the parent window of the message box; // if 'force' is TRUE, 'DynMenuWasAlreadyBuild' is ignored and the menu is always built; // returns TRUE if the plugin is loaded and has a static menu or has a dynamic menu and - // also returns the menu-extension interface + // provides the menu-extension interface BOOL BuildMenu(HWND parent, BOOL force); // plugin call: ListArchive @@ -2667,14 +2667,14 @@ struct CPluginData // plugin call: PrematureDeleteTmpCopy BOOL PrematureDeleteTmpCopy(HWND parent, int copiesCount); - // returns TRUE if the plugin is an archiver and has its own mechanism for deleting copies of files extracted from the archive + // returns TRUE if the plugin is an archiver and has its own mechanism for deleting copies of files extracted from the archive // must work even after unloading the plugin (until it is loaded again) BOOL IsArchiverAndHaveOwnDelete() { return ArcCacheOwnDelete; } HIMAGELIST CreateImageList(BOOL gray); - // fills 'mii::State' and 'mii::Type' structuresaccording to the command for 'pluginIndex' and 'menuItemIndex' - // returns TRUE if the item is enabled and FALSE if it is grayed + // fills the 'mii::State' and 'mii::Type' members according to the command specified by 'pluginIndex' and 'menuItemIndex' + // returns TRUE if the item is enabled and FALSE if it is GRAYED BOOL GetMenuItemStateType(int pluginIndex, int menuItemIndex, MENU_ITEM_INFO* mii); // synchronizes old hot keys (from configuration) with new ones (from Connect()): @@ -2791,7 +2791,7 @@ class CPlugins BOOL DefaultConfiguration; // TRUE => ZIP+TAR+PAK; allows recoding of old archiver data - TIndirectArray PluginFSTimers; // timers of individual plugin FS + TIndirectArray PluginFSTimers; // timers of individual plugin file systems DWORD TimerTimeCounter; // "time" for adding timer (prevents endless loops inside CPlugins::HandlePluginFSTimers()) BOOL StopTimerHandlerRecursion; // prevents recursive calls to HandlePluginFSTimers() CPluginFSInterfaceEncapsulation* WorkingPluginFS; // working plugin FS object (neither in a panel nor among detached FS yet) @@ -2852,13 +2852,13 @@ class CPlugins void CheckData(); // removes from Data all plugins whose .spl file no longer exists; if 'canDelPluginRegKey' is TRUE, - // their configuration in the registry is also deleted. in the 'notLoadedPluginNames' (buffer of size - // 'notLoadedPluginNamesSize') returns a list of names (up to 'maxNotLoadedPluginNames' names) of - // plugins that were not loaded but with the configuration in the registry(either removed or failed InitDLL()), - // separated by ", " + in 'numOfSkippedNotLoadedPluginNames' (if not NULL) returns the number of - // names that are not stored in 'notLoadedPluginNames'. in 'loadAllPlugins' is TRUE only when upgrading - // to a new Salamander version and all plugins should be loaded; those that fail and still - // have the configuration in the registryare should be stored in 'notLoadedPluginNames' + // their configuration in the registry is also deleted. in 'notLoadedPluginNames' (a buffer of size + // 'notLoadedPluginNamesSize') it returns a list of names (up to 'maxNotLoadedPluginNames' names) of + // plugins not loaded but having configuration in the registry (either removed or with failed InitDLL()), + // separated by ", "; in 'numOfSkippedNotLoadedPluginNames' (if not NULL) it returns the number of + // names that are not stored in 'notLoadedPluginNames'. 'loadAllPlugins' is TRUE only if upgrading + // to a new Salamander version and all plugins are to be loaded; those that fail and still + // have configuration in the registry are to be stored in 'notLoadedPluginNames' void RemoveNoLongerExistingPlugins(BOOL canDelPluginRegKey, BOOL loadAllPlugins = FALSE, char* notLoadedPluginNames = NULL, int notLoadedPluginNamesSize = 0, @@ -2870,9 +2870,9 @@ class CPlugins // those not yet added) and automatically uninstalls plugins whose .spl files disappeared void AutoInstallStdPluginsDir(HWND parent); - // handles addition of newly installed plugins (reads plugins.ver); returns TRUE if a new - // version of plugins.ver file was found (configuration must be saved so the process doesn't repeat - // on the next start of Salamander) + // handles adding newly installed plugins (reads plugins.ver); returns TRUE if a new + // version of the plugins.ver file was found (the configuration must be saved so this does not repeat + // the next time Salamander starts) BOOL ReadPluginsVer(HWND parent, BOOL importFromOldConfig); // loads all plugins and calls their ClearHistory methods @@ -2924,11 +2924,11 @@ class CPlugins // the name is based on 'regKeyName' void GetUniqueRegKeyName(char* uniqueKeyName, const char* regKeyName); - // it stores a unique FS name based on 'fsName' in 'uniqueFSName'; - // 'uniqueFSNames' (if not NULL) is an array of names to which the resulting + // Stores a unique FS name based on 'fsName' in 'uniqueFSName'; + // 'uniqueFSNames' (if not NULL) is an array of names against which the resulting // 'uniqueFSName' must also be unique; 'oldFSNames' (if not NULL) is an array of old - // fs names from previous plugin loads from which a unique name is preferably selected - // and removed (so the user's FS name doesn't change with each plugin load) + // fs names from previous plugin loads, from which a unique FS name is preferably selected + // and removed (so the user's FS name does not change on each plugin load) void GetUniqueFSName(char* uniqueFSName, const char* fsName, TIndirectArray* uniqueFSNames, TIndirectArray* oldFSNames); @@ -3133,7 +3133,7 @@ class CPlugins // adds a new timer to the PluginFSTimers array; the absolute timeout is GetTickCount() + 'relTimeout'. // Once GetTickCount() returns a value greater than or equal to that timeout, - // the FS object's Event() method is called with FSE_TIMER and 'timerParam'. + // the Event() method of the FS object 'timerOwner' is called with FSE_TIMER and 'timerParam'. // Returns TRUE on success (timer successfully added) BOOL AddPluginFSTimer(DWORD relTimeout, CPluginFSInterfaceAbstract* timerOwner, DWORD timerParam); @@ -3170,7 +3170,7 @@ class CPlugins int GetPluginSaveCount(); // after changing Salamander's language clears LastSLGName for all plugins so a new fallback - // language is chosen for a plugin (used if the plug-in does not support the language currently selected in Salamander) + // language is chosen for a plugin (used if the plugin does not support the language currently selected in Salamander) void ClearLastSLGNames(); // returns the number of plugins that can be loaded (GetLoaded() returns TRUE) @@ -3182,19 +3182,19 @@ class CPlugins BOOL GetFirstNethoodPluginFSName(char* fsName = NULL, CPluginData** nethoodPlugin = NULL); // invokes PasswordManagerEvent method for all plugins using the Password Manager. - // See CSalamanderGeneralAbstract::SetPluginUsesPasswordManager (loads unloaded plug-ins if necessary) + // See CSalamanderGeneralAbstract::SetPluginUsesPasswordManager (loads unloaded plugins if necessary) void PasswordManagerEvent(HWND parent, int event); // releases and clears each plugin's 'PluginDynMenuIcons' void ReleasePluginDynMenuIcons(); protected: - // based on the LastPlgCmdXXX variables finds the plugin and item in its menu corresponding to - // the the last executed command from the Plugins menu; 'rebuildDynMenu' is TRUE if, in the case of a - // dynamic menu, BuildMenu() should be called before searching; 'parent' is the parent message box - // window (only when 'rebuildDynMenu' is TRUE); - // if the command is found, TRUE is returned and 'pluginIndex' holds the plugin index in CPlugins::Data - // and 'menuItemIndex' holds the index in the MenuItems array + // uses the LastPlgCmdXXX variables to find the plugin and the item in its menu corresponding to + // the last command executed from the Plugins menu; 'rebuildDynMenu' is TRUE if, for a dynamic + // menu, BuildMenu() should be called before searching; 'parent' is the parent window of the + // message box (only when 'rebuildDynMenu' is TRUE); + // if the command is found, TRUE is returned and 'pluginIndex' contains the plugin index in + // CPlugins::Data and 'menuItemIndex' contains the index in the MenuItems array // otherwise FALSE is returned BOOL FindLastCommand(int* pluginIndex, int* menuItemIndex, BOOL rebuildDynMenu, HWND parent); @@ -3206,7 +3206,7 @@ class CPlugins // adds a record to the Order array; returns the index in the array on success, otherwise returns -1 int AddPluginToOrder(const char* dllName, BOOL showInBar); - // Sorts the Orders array by plugin name (used for newly added plug-ins to ensure alphabetical order) + // Sorts the Orders array by plugin name (used for newly added plugins to ensure alphabetical order) void QuickSortPluginsByName(int left, int right); // used only for the conversion from the old configuration (the visibility variable has been moved to CPluginData) @@ -3229,7 +3229,7 @@ class CSalamanderPluginEntry : public CSalamanderPluginEntryAbstract BOOL Valid; // TRUE if SetBasicPluginData was called successfully BOOL Error; // has an error already been displayed? DWORD LoadInfo; // DWORD value returned by GetLoadInformation() - TIndirectArray OldFSNames; // array of old fs-names (names from the registry, replaced during plug-in loading) + TIndirectArray OldFSNames; // array of old fs names (names from the registry, replaced during plugin loading) public: CSalamanderPluginEntry(HWND parent, CPluginData* plugin) : OldFSNames(1, 10) diff --git a/src/plugins/7zip/7za/c/7z.h b/src/plugins/7zip/7za/c/7z.h index 476815194..b7ae11cc5 100644 --- a/src/plugins/7zip/7za/c/7z.h +++ b/src/plugins/7zip/7za/c/7z.h @@ -173,11 +173,11 @@ UInt16 *SzArEx_GetFullNameUtf16_Back(const CSzArEx *p, size_t fileIndex, UInt16 SRes SzArEx_Extract( const CSzArEx *db, ILookInStream *inStream, - UInt32 fileIndex, /* index of file */ - UInt32 *blockIndex, /* index of solid block */ + UInt32 fileIndex, /* file index */ + UInt32 *blockIndex, /* solid block index */ Byte **outBuffer, /* pointer to pointer to output buffer (allocated with allocMain) */ - size_t *outBufferSize, /* buffer size for output buffer */ - size_t *offset, /* offset of stream for required file in *outBuffer */ + size_t *outBufferSize, /* size of the output buffer */ + size_t *offset, /* offset of the required file stream in *outBuffer */ size_t *outSizeProcessed, /* size of file in *outBuffer */ ISzAlloc *allocMain, ISzAlloc *allocTemp); diff --git a/src/plugins/7zip/7za/c/7zDec.c b/src/plugins/7zip/7za/c/7zDec.c index c45d6bf8d..0ac6f823f 100644 --- a/src/plugins/7zip/7za/c/7zDec.c +++ b/src/plugins/7zip/7za/c/7zDec.c @@ -412,7 +412,7 @@ static SRes SzFolder_Decode2(const CSzFolder *folder, } else if (ci == 2) { - if (unpackSize > outSize) /* check it */ + if (unpackSize > outSize) /* check size */ return SZ_ERROR_PARAM; tempBuf3 = outBufCur = outBuffer + (outSize - (size_t)unpackSize); tempSize3 = outSizeCur = (SizeT)unpackSize; diff --git a/src/plugins/7zip/7zclient.cpp b/src/plugins/7zip/7zclient.cpp index 0bdc4209f..c98af3dd3 100644 --- a/src/plugins/7zip/7zclient.cpp +++ b/src/plugins/7zip/7zclient.cpp @@ -191,7 +191,7 @@ BOOL C7zClient::FillItemData(IInArchive* archive, UINT32 index, C7zClient::CItem else itemData->SetMethod(GetAnsiString(propVariant.bstrVal)); - /* // 06F10701 is the id for 7zAES -> so it's the password :) + /* // 06F10701 is the ID for 7zAES, i.e. encryption // if (strstr(itemData->Method, "06F10701") != NULL) if (strstr(itemData->Method, "7zAES") != NULL) itemData->Encrypted = TRUE; @@ -271,7 +271,7 @@ BOOL C7zClient::AddFileDir(IInArchive* archive, UINT32 idx, } fd.PluginData = (DWORD_PTR)itemData; - // Creation Time + // Modification Time archive->GetProperty(idx, kpidMTime, &propVariant); fd.LastWrite = propVariant.filetime; @@ -333,7 +333,7 @@ BOOL C7zClient::AddFileDir(IInArchive* archive, UINT32 idx, // file length archive->GetProperty(idx, kpidSize, &propVariant); ::ConvertPropVariantToUInt64(propVariant, fd.Size.Value); - // What is better? Check on *.lnk/pif/url extensions or Unix flags or both? We do both. + // Which is better? Checking *.lnk/pif/url extensions, Unix flags, or both? We do both. fd.IsLink |= SalamanderGeneral->IsFileLink(fd.Ext); // file @@ -535,7 +535,7 @@ int C7zClient::GetArchiveItemList(IInArchive* archive, TIndirectArrayGetProperty(i, kpidMTime, &propVariant); FILETIME lastWrite = propVariant.filetime; @@ -706,7 +706,7 @@ int C7zClient::Delete(CSalamanderForOperationsAbstract* salamander, const char* updateCallbackSpec->Password = password; updateCallbackSpec->AskPassword = passwordIsDefined; - // TODO: what about delete? is it possible to load compression parameters? and do they even need to be set? + // TODO: what about delete? Can the compression parameters be loaded, and do they need to be set at all? // SetCompressionParams(outArchive, compr); // start update in a thread @@ -1079,7 +1079,7 @@ int C7zClient::Update(CSalamanderForOperationsAbstract* salamander, const char* CCompressParams* compressParams, bool passwordIsDefined, UString password) { char tmpName[MAX_PATH]; - // trim the filename from archiveName, leaving the target path where we will extract + // strip the filename from archiveName, leaving the target path where we will extract lstrcpy(tmpName, archiveName); SalamanderGeneral->CutDirectory(tmpName, NULL); DWORD err; @@ -1226,9 +1226,9 @@ int C7zClient::Update(CSalamanderForOperationsAbstract* salamander, const char* // else { if (FAILED(result) && ((FACILITY_WIN32 << 16) == (result & 0x7FFF0000))) { - // LastError error encoded into HRESULT - // There is something strange: E_OUTOFMEMORY as 0x8007000EL prints as "Not enough storage is available to complete this operation" - // even when not truncated to 16 bits while 0x80000002L prints as "Ran out of memory" + // LastError encoded as HRESULT + // Oddly, E_OUTOFMEMORY as 0x8007000EL prints as "Not enough storage is available to complete this operation" + // even without truncating to 16 bits, while 0x80000002L prints as "Ran out of memory" SysError(IDS_7Z_FATAL_ERROR, (result == E_OUTOFMEMORY) ? 0x80000002L : (result & 0xFFFF), FALSE); } else diff --git a/src/plugins/7zip/7zclient.h b/src/plugins/7zip/7zclient.h index d6bacc18b..573b45ef6 100644 --- a/src/plugins/7zip/7zclient.h +++ b/src/plugins/7zip/7zclient.h @@ -33,10 +33,10 @@ #define S_ISLNK(m) (((m) & 0170000) == 0120000) /* symbolic link */ #endif -// three states for errors. -// there are situations where TRUE/FALSE is not enough. we have an activity that can run into an error. sometimes we can -// and want to continue the activity, other times we cannot. if we can continue we return OPER_CONTINUE, -// if it cannot go on (out of memory, etc.) -> OPER_CANCEL. if everything is fine -> OPER_OK +// three error states. +// there are situations where TRUE/FALSE is not enough. we have an operation that can encounter an error. sometimes we can +// and want to continue the operation, other times we cannot. if we can continue, we return OPER_CONTINUE, +// if continuing is not possible (out of memory, etc.) -> OPER_CANCEL. if everything is OK -> OPER_OK #define OPER_OK 0 #define OPER_CONTINUE 1 #define OPER_CANCEL 2 diff --git a/src/plugins/7zip/7zip.cpp b/src/plugins/7zip/7zip.cpp index d00ff7a2e..b6416d8a3 100644 --- a/src/plugins/7zip/7zip.cpp +++ b/src/plugins/7zip/7zip.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" #include "dbg.h" @@ -54,7 +55,7 @@ int ConfigVersion = 0; // 2: ? // 3: Igor changed the default values for LZMA compression (dictionary size, etc.). There are more changes, // so Honza Patera and I agreed that when importing old configurations we will -// ignore compression settings and use the new defaults instead. +// ignore the compression settings and use these new defaults. #define CURRENT_CONFIG_VERSION 3 const char* CONFIG_VERSION = "Version"; @@ -139,12 +140,12 @@ CPluginInterfaceAbstract* WINAPI SalamanderPluginEntry(CSalamanderPluginEntryAbs { // reject older versions MessageBox(salamander->GetParentWindow(), REQUIRE_LAST_VERSION_OF_SALAMANDER, - "7-Zip" /* neprekladat! */, MB_OK | MB_ICONERROR); + "7-Zip" /* do not translate */, MB_OK | MB_ICONERROR); return NULL; } // load the language module (.slg) - HLanguage = salamander->LoadLanguageModule(salamander->GetParentWindow(), "7-Zip" /* neprekladat! */); + HLanguage = salamander->LoadLanguageModule(salamander->GetParentWindow(), "7-Zip" /* do not translate */); if (HLanguage == NULL) return NULL; @@ -444,7 +445,7 @@ void CPluginInterface::LoadConfiguration(HWND parent, HKEY regKey, CSalamanderRe { CALL_STACK_MESSAGE1("CPluginInterface::LoadConfiguration(, ,)"); - if (regKey != NULL) // load from registry + if (regKey != NULL) // load from the registry { if (!registry->GetValue(regKey, CONFIG_VERSION, REG_DWORD, &ConfigVersion, sizeof(DWORD))) ConfigVersion = 0; // default configuration @@ -457,7 +458,7 @@ void CPluginInterface::LoadConfiguration(HWND parent, HKEY regKey, CSalamanderRe // set config defaults SetDefaultConfiguration(); - if (regKey != NULL) // load from registry + if (regKey != NULL) // load from the registry { registry->GetValue(regKey, CONFIG_SHOW_EXTENDED_OPTIONS, REG_DWORD, &Config.ShowExtendedOptions, sizeof(DWORD)); registry->GetValue(regKey, CONFIG_EXTENDED_LIST_INFO, REG_DWORD, &Config.ExtendedListInfo, sizeof(DWORD)); @@ -471,7 +472,7 @@ void CPluginInterface::LoadConfiguration(HWND parent, HKEY regKey, CSalamanderRe if (ConfigVersion >= 1) { - // compress params + // compression params registry->GetValue(regKey, CONFIG_SOLID_ARCHIVE, REG_DWORD, &Config.CompressParams.SolidArchive, sizeof(DWORD)); if (registry->GetValue(regKey, CONFIG_COMPRESS_METHOD, REG_DWORD, &Config.CompressParams.Method, sizeof(DWORD)) && (Config.CompressParams.Method != CCompressParams::LZMA || ConfigVersion >= 3)) // for configuration version 3 we reset the defaults for LZMA because they differ @@ -502,7 +503,7 @@ void CPluginInterface::SaveConfiguration(HWND parent, HKEY regKey, CSalamanderRe registry->SetValue(regKey, CONFIG_COL_METHOD_WIDTH, REG_DWORD, &Config.ColumnMethodWidth, sizeof(DWORD)); // config version == 2 - // compress params + // compression params registry->SetValue(regKey, CONFIG_COMPRESS_LEVEL, REG_DWORD, &Config.CompressParams.CompressLevel, sizeof(DWORD)); registry->SetValue(regKey, CONFIG_COMPRESS_METHOD, REG_DWORD, &Config.CompressParams.Method, sizeof(DWORD)); registry->SetValue(regKey, CONFIG_DICT_SIZE, REG_DWORD, &Config.CompressParams.DictSize, sizeof(DWORD)); @@ -532,8 +533,8 @@ void CPluginInterface::Connect(HWND parent, CSalamanderConnectAbstract* salamand // when adding more extensions we must raise CURRENT_CONFIG_VERSION // BASIC SECTION - // AddViewer and AddPanelArchiver will fall under the UPGRADE SECTION - // salamander->AddViewer("*.7z", FALSE); // default (plugin install), otherwise Salamander ignores it + // AddViewer and AddPanelArchiver are handled by the UPGRADE SECTION + // salamander->AddViewer("*.7z", FALSE); // default (plugin installation), otherwise Salamander ignores it salamander->AddPanelArchiver("7z", TRUE, FALSE); @@ -969,7 +970,7 @@ BOOL CPluginInterfaceForArchiver::PackToArchive(CSalamanderForOperationsAbstract CALL_STACK_MESSAGE5("CPluginInterfaceForArchiver::PackToArchive(, %s, %s, %d, %s, ,)", fileName, archiveRoot, move, sourcePath); - // test whether the archive exists (we need to distinguish between update and create new archive) + // test whether the archive exists (we need to distinguish between updating and creating a new archive) BOOL isNewArchive = FALSE; HANDLE hArchive = ::CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hArchive == INVALID_HANDLE_VALUE) @@ -1059,7 +1060,7 @@ BOOL CPluginInterfaceForArchiver::PackToArchive(CSalamanderForOperationsAbstract // count how many items we will compress // (we could use a growing array right away, but with a large number it would fragment memory, and iterating the list twice - // will not kill us) + // is acceptable) int itemCount = 0; while ((name = next(SalamanderGeneral->GetMsgBoxParent(), 3, &dosName, &isDir, &size, &attr, &lastWrite, nextParam, &errorOccured)) != NULL) @@ -1106,12 +1107,12 @@ BOOL CPluginInterfaceForArchiver::PackToArchive(CSalamanderForOperationsAbstract BOOL ret = client.Update(salamander, fileName, sourcePath, isNewArchive, &fileList, &compressParams, passwordDefined, GetUnicodeString(password)) == OPER_OK; - // delete files afterwards if we are moving them into the archive + // delete files afterwards if moving them into the archive if (move && ret) { // first lock the archive file so we cannot delete it ourselves (bug: https://forum.altap.cz/viewtopic.php?f=3&t=3859) while (1) { - hArchive = ::CreateFile(fileName, GENERIC_READ /* I tried 0, but the system then allowed deleting the file */, + hArchive = ::CreateFile(fileName, GENERIC_READ /* Using 0 was tested, but then the system allowed the file to be deleted */, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); @@ -1180,7 +1181,7 @@ BOOL CPluginInterfaceForArchiver::PackToArchive(CSalamanderForOperationsAbstract } int endSourceSize = MAX_PATH - (int)(endSource - sourceName); // maximum number of characters for a name from the 'next' enumeration - // delete directories; if something remains inside they will not be removed and that's fine :) + // delete directories; if something remains inside, they will not be removed, which is correct // because we iterate from leaves to the root, we can delete them this way next(NULL, -1, NULL, NULL, NULL, NULL, NULL, nextParam, NULL); while ((name = next(NULL /* we do not log errors the second time */, 3, &dosName, &isDir, &size, @@ -1287,7 +1288,7 @@ CPluginInterfaceForViewer::ViewFile(const char *name, int left, int top, int wid "0x%X, %d, %d, , , , %d, %d)", name, left, top, width, height, showCmd, alwaysOnTop, returnLock, enumFilesSourceUID, enumFilesCurrentIndex); - // we do not set 'lock' or 'lockOwner'; we only need the lifetime of the file 'name' + // we do not set 'lock' or 'lockOwner'; we only need the file 'name' to remain valid // within this method HCURSOR hOldCur = SetCursor(LoadCursor(NULL, IDC_WAIT)); @@ -1313,7 +1314,7 @@ CPluginInterfaceForViewer::ViewFile(const char *name, int left, int top, int wid int err; CSalamanderPluginInternalViewerData viewerData; - // create a temporary file and pour the module dump into it + // create a temporary file and write the module dump to it FILE *outStream = fopen(tempFileName, "w"); if (!image->DumpInfo(outStream)) { @@ -1322,7 +1323,7 @@ CPluginInterfaceForViewer::ViewFile(const char *name, int left, int top, int wid fclose(outStream); delete image; - // hand the file over to Salamander - it moves it to cache and deletes it when it is done + // hand the file over to Salamander - it moves it to the cache and deletes it when it no longer uses it viewerData.Size = sizeof(viewerData); viewerData.FileName = tempFileName; viewerData.Mode = 0; // text mode diff --git a/src/plugins/7zip/7zthreads.cpp b/src/plugins/7zip/7zthreads.cpp index 44f043e12..3ee1ee6d8 100644 --- a/src/plugins/7zip/7zthreads.cpp +++ b/src/plugins/7zip/7zthreads.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -36,7 +37,7 @@ BOOL CALLBACK SubClassedProgressDlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPA return S_OK; case WM_7ZIP_ADDTEXT: - Salamander->ProgressDialogAddText((char*)lParam, TRUE); // delayed paint, to avoid slow down by frequent refresh + Salamander->ProgressDialogAddText((char*)lParam, TRUE); // Delayed paint to avoid slowdown from frequent refreshes return S_OK; case WM_7ZIP_CREATEFILE: @@ -126,7 +127,7 @@ HRESULT LaunchAndDo7ZipTask(LPTHREAD_START_ROUTINE threadProc, LPVOID args) GetExitCodeThread(hThread, &exitCode); CloseHandle(hThread); - return exitCode; // Our thread body func returns HRESULT + return exitCode; // Our thread body function returns HRESULT } MSG msg; @@ -155,9 +156,9 @@ HRESULT DoDecompress(CSalamanderForOperationsAbstract* salamander, CDecompressPa if (FAILED(result) && ((FACILITY_WIN32 << 16) == (result & 0x7FFF0000))) { - // LastError error encoded into HRESULT - // There is something strange: E_OUTOFMEMORY as 0x8007000EL prints as "Not enough storage is available to complete this operation" - // even when not truncated to 16 bits while 0x80000002L prints as "Ran out of memory" + // LastError encoded as HRESULT + // Oddly, E_OUTOFMEMORY as 0x8007000EL prints as "Not enough storage is available to complete this operation" + // even without truncating to 16 bits, while 0x80000002L prints as "Ran out of memory" SysError(label, (result == E_OUTOFMEMORY) ? 0x80000002L : (result & 0xFFFF), FALSE); } else diff --git a/src/plugins/7zip/FStreams.cpp b/src/plugins/7zip/FStreams.cpp index c04016b79..272add0e8 100644 --- a/src/plugins/7zip/FStreams.cpp +++ b/src/plugins/7zip/FStreams.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -31,8 +32,8 @@ BOOL ShowRetryAbortBox(HWND hParentWnd, int resID, DWORD err, ...) _stprintf(buf, _T("%s\n\n%s"), msg, SalamanderGeneral->GetErrorText(err)); TCHAR btnBuffer[128]; - /* used by the export_mnu.py script, which generates salmenu.mnu for the Translator - let the message box buttons handle hotkey collisions by simulating a menu + /* used by the export_mnu.py script, which generates salmenu.mnu for Translator + treat message box buttons as a menu to resolve hotkey collisions MENU_TEMPLATE_ITEM MsgBoxButtons[] = { {MNTT_PB, 0 diff --git a/src/plugins/7zip/dialogs.cpp b/src/plugins/7zip/dialogs.cpp index 9ae3c26cd..e84fd8f65 100644 --- a/src/plugins/7zip/dialogs.cpp +++ b/src/plugins/7zip/dialogs.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -389,7 +390,7 @@ CCompressParamsDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) SetComboCurSelData(GetDlgItem(HWindow, IDCfgDictSize), CompressParams->DictSize); SetComboCurSelData(GetDlgItem(HWindow, IDCfgWordSize), CompressParams->WordSize); - break; // request focus from DefDlgProc + break; // let DefDlgProc handle focus } case WM_COMMAND: @@ -434,7 +435,7 @@ CCommonDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) // horizontally and vertically center the dialog relative to the parent if (Parent != NULL) SalamanderGeneral->MultiMonCenterWindow(HWindow, Parent, TRUE); - break; // request focus from DefDlgProc + break; // let DefDlgProc handle focus case WM_COMMAND: break; @@ -483,7 +484,7 @@ CConfigurationDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) EnableWindow(GetDlgItem(HWindow, IDC_CFG_LISTINFOMETHOD), Cfg.ExtendedListInfo); CompressParamsDlg.HWindow = HWindow; - break; // request focus from DefDlgProc + break; // let DefDlgProc handle focus } case WM_COMMAND: @@ -566,7 +567,7 @@ CExtOptionsDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (!CreateChilds()) { DestroyWindow(HWindow); // error -> do not open the dialog - return FALSE; // stop processing + return FALSE; // end processing } // set archive name @@ -580,7 +581,7 @@ CExtOptionsDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) CompressParamsDlg.HWindow = HWindow; - break; // request focus from DefDlgProc + break; // let DefDlgProc handle focus } case WM_COMMAND: @@ -666,7 +667,7 @@ CEnterPasswordDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_COMMAND: { /* - // preparation for skip and skip_all + // support for skip and skip_all switch (LOWORD(wParam)) { case IDC_SKIP: return EndDialog(HWindow, DIALOG_SKIP); diff --git a/src/plugins/7zip/extract.cpp b/src/plugins/7zip/extract.cpp index 0a10c7ac9..dd3e773e8 100644 --- a/src/plugins/7zip/extract.cpp +++ b/src/plugins/7zip/extract.cpp @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #include "precomp.h" @@ -39,8 +40,8 @@ CExtractCallbackImp::~CExtractCallbackImp() DeleteCriticalSection(&CSExtract); } -// silent - if TRUE and a DataError occurs during extraction (usually an incorrect password), the file is deleted -// automatically and the user is not asked anything (used when extracting a single file for preview - F3) +// silent - if TRUE and a DataError occurs during extraction (usually because of an incorrect password), the file is deleted +// automatically and the user is not prompted (used when extracting a single file for viewing - F3) BOOL CExtractCallbackImp::Init(IInArchive* archive, const char* outDir, const FILETIME& utcLastWriteTimeDefault, DWORD attributesDefault, BOOL silentDelete /* = FALSE*/) { @@ -158,20 +159,20 @@ STDMETHODIMP CExtractCallbackImp::GetStream(UINT32 index, ISequentialOutStream** const CArchiveItemInfo* aii = ItemsToExtract[index]; if (!aii) { - // Already extracted??? Not to be extracted? + // Already extracted? Not selected for extraction? throw S_OK; } ItemsToExtract.erase(index); const CFileData* fd = aii->FileData; // fd is certainly not NULL - // because we handed over a list of CArchiveItem with all information we need, we can extract directly. - // however, we need reverse mapping (a hash function) that tells us the index of the item to use - // because this function receives the index in the archive + // Because we passed a list of CArchiveItem objects with all the information we need, we can extract directly. + // However, we need reverse mapping (a hash function) to tell us which item index to use, + // because this function receives the index within the archive. // - // we could save memory and retrieve the properties we need via ArchiveHandler->GetProperty, - // but the problem is with names: GetProperty returns path+filename relative to the archive root and if we extract - // from a different root, we would have to strip the path + // We could save memory and retrieve the properties we need via ArchiveHandler->GetProperty, + // but names are a problem: GetProperty returns path+filename relative to the archive root, and if we extract + // from a different root, we would have to strip the path. ProcessedFileInfo.Attributes = fd->Attr; ProcessedFileInfo.AttributesAreDefined = true; @@ -364,7 +365,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = } } - // release the OutStream so it can be deleted if needed + // release OutStream so the file can be deleted if (OutFileStream != NULL) OutFileStreamSpec->SetMTime(&ProcessedFileInfo.LastWrite); OutFileStream.Release(); @@ -376,7 +377,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = return FALSE; case Delete: - // if cancel, bail out + // if canceled, exit if (!SafeDeleteFile(GetAnsiString(ProcessedFileInfo.FileName), DataErrorDeleteSilent)) return FALSE; break; @@ -480,7 +481,7 @@ STDMETHODIMP CExtractCallbackImp::SetOperationResult(INT32 resultEOperationResul if (TargetDir && !ItemsToExtract.size()) { // NULL TargetDir means testing the archive - // Doing partial extract & everything has been extracted. Looks like a solid archive + // A partial extraction was requested, and everything has been extracted. The archive appears to be solid. return E_STOPEXTRACTION; } diff --git a/src/plugins/7zip/extract.h b/src/plugins/7zip/extract.h index 66415e00f..6e48142dd 100644 --- a/src/plugins/7zip/extract.h +++ b/src/plugins/7zip/extract.h @@ -99,7 +99,7 @@ class CExtractCallbackImp : public IArchiveExtractCallback, Cancel }; // behavior of the callback when a data error occurs - BOOL DataErrorSilent; // whether to ask about Keep or Delete + BOOL DataErrorSilent; // whether to prompt for Keep or Delete EOperationMode DataErrorMode; BOOL DataErrorDeleteSilent; // report an error when deleting BOOL SilentDelete; diff --git a/src/plugins/7zip/update.h b/src/plugins/7zip/update.h index a85f3b9e8..ce0d9611b 100644 --- a/src/plugins/7zip/update.h +++ b/src/plugins/7zip/update.h @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later +// CommentsTranslationProject: TRANSLATED #pragma once @@ -147,7 +148,7 @@ class CArchiveUpdateCallback : public IArchiveUpdateCallback2, public: AString ProcessedFileName; - // synchronization for calls + // call synchronization CRITICAL_SECTION CSUpdate; TIndirectArray* FileItems; diff --git a/src/plugins/automation/abortmodal.cpp b/src/plugins/automation/abortmodal.cpp index 4ef0a0a9d..f982f5f84 100644 --- a/src/plugins/automation/abortmodal.cpp +++ b/src/plugins/automation/abortmodal.cpp @@ -128,7 +128,7 @@ HRESULT AbortableModalDialogWrapper( { hr = SALAUT_E_ABORT; - // Pump out the WM_QUIT we generated. The eventual messages + // Pump out the WM_QUIT we generated. Any messages // before WM_QUIT are lost. MSG msg; while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) diff --git a/src/plugins/automation/abortmodal.h b/src/plugins/automation/abortmodal.h index 48dda8c99..d27caa392 100644 --- a/src/plugins/automation/abortmodal.h +++ b/src/plugins/automation/abortmodal.h @@ -15,10 +15,10 @@ #define WM_SAL_ABORTMODAL (WM_APP + 0) -/// Wraps a modal dialog into the dialog that can be forcibly aborted by the user. -/// \param pfnDialogFn Function to display the modal dialog. -/// \param pContext User defined value to be passed to the dialog function. -/// \return If the modal dialog was successfully executed, the return value is S_OK. +/// Wraps a modal dialog in a dialog that the user can forcibly abort. +/// \param pfnDialogFn Function that displays the modal dialog. +/// \param pContext User-defined value passed to the dialog function. +/// \return If the modal dialog was executed successfully, the return value is S_OK. /// If the modal dialog was aborted, the return value is SALAUT_E_ABORT. HRESULT AbortableModalDialogWrapper( __in class CScriptInfo* pScript, diff --git a/src/plugins/automation/abortpalette.cpp b/src/plugins/automation/abortpalette.cpp index b79955587..ab718cfab 100644 --- a/src/plugins/automation/abortpalette.cpp +++ b/src/plugins/automation/abortpalette.cpp @@ -293,8 +293,8 @@ unsigned CScriptAbortPaletteThread::Body() // We cannot delete the SC_CLOSE menu item, // since that would not disable the close button // on the title bar on Vista+ with Aero. - // Moreover the item cannot be referenced by - // position but by command only. + // Moreover, the item cannot be referenced + // by position, only by command. EnableMenuItem(hSysMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED); } else if (uId != SC_MOVE) diff --git a/src/plugins/automation/automationplug.cpp b/src/plugins/automation/automationplug.cpp index cdc4740e4..b975acebf 100644 --- a/src/plugins/automation/automationplug.cpp +++ b/src/plugins/automation/automationplug.cpp @@ -281,8 +281,8 @@ MENU_TEMPLATE_ITEM PluginMenu[] = 0, CAutomationMenuExtInterface::CmdRunFocusedScript, TRUE, // callGetState - 0, // or-mask (ignored id callGetState == TRUE) - 0, // and-mask (ignored id callGetState == TRUE) + 0, // or-mask (ignored if callGetState == TRUE) + 0, // and-mask (ignored if callGetState == TRUE) MENU_SKILLLEVEL_ALL); // open script menu @@ -296,10 +296,10 @@ MENU_TEMPLATE_ITEM PluginMenu[] = 0, MENU_SKILLLEVEL_ALL); - // for our menu items we set callGetState to TRUE, so the - // GetMenuItemState will be always called for the items which - // forces our plugin to be loaded before first menu popup - // and the items get refreshed + // for our menu items we set callGetState to TRUE, so + // GetMenuItemState is always called for those items, + // which forces our plugin to load before the first menu popup + // and refreshes the items if (g_oScriptLookup.GetCount() > 0) { @@ -319,8 +319,8 @@ MENU_TEMPLATE_ITEM PluginMenu[] = AddScriptContainerToMenu(pRootContainer, salamander, 0); } - // Salamander manages the icon list itself, so we must everytime - // create a copy of that list that we pass to menu builder. + // Salamander manages the icon list itself, so we must always + // create a copy of the list that we pass to the menu builder. CGUIIconListAbstract* pListCopy = SalamanderGUI->CreateIconList(); if (pListCopy) { diff --git a/src/plugins/automation/aututils.cpp b/src/plugins/automation/aututils.cpp index 241c76e85..90ef29105 100644 --- a/src/plugins/automation/aututils.cpp +++ b/src/plugins/automation/aututils.cpp @@ -128,9 +128,9 @@ static int DisplayError( static void AdjustSourcePosition(ULONG& line, LONG& col, CScriptEngineShim* pShim) { - // Some engines return zero-based line number, others one-based - // try to normalize to one-base line numbers since it is more - // natural for humans and editors start counting from one too. + // Some engines return zero-based line numbers, others one-based. + // Try to normalize to one-based line numbers since that is more + // natural for humans, and editors start counting from one too. if (pShim != NULL) { @@ -293,7 +293,7 @@ void QuadWordToVariant(const CQuadWord& q, __out VARIANT* var) } else { - // 64b integer is not OLE Automation type, coerce to double + // 64-bit integer is not an OLE Automation type; coerce to double V_VT(var) = VT_R8; V_R8(var) = (double)q.Value; } @@ -310,7 +310,7 @@ void QuadWordToVariant(LARGE_INTEGER q, __out VARIANT* var) } else { - // 64b integer is not OLE Automation type, coerce to double + // 64-bit integer is not an OLE Automation type; coerce to double V_VT(var) = VT_R8; V_R8(var) = (double)q.QuadPart; } diff --git a/src/plugins/automation/aututils.h b/src/plugins/automation/aututils.h index 3acab07d1..d26b9a6ce 100644 --- a/src/plugins/automation/aututils.h +++ b/src/plugins/automation/aututils.h @@ -52,7 +52,7 @@ void DisplayException(EXCEPINFO& ei, bool bFree = true); /// Releases resources associated with the EXCEPINFO structure. void FreeException(EXCEPINFO& ei); -/// Formats textual description of the system error code. +/// Formats a textual description of the system error code. void FormatErrorText( HRESULT hrCode, TCHAR* pszBuffer, @@ -67,10 +67,10 @@ UINT HashString(__in_z PCTSTR s); void QuadWordToVariant(LARGE_INTEGER q, __out VARIANT* var); void QuadWordToVariant(const CQuadWord& q, __out VARIANT* var); -/// Retrieved property value from the IDispatch interface. +/// Retrieves a property value from the IDispatch interface. /// \param pdisp Pointer to the IDispatch interface. /// \param name Name of the property to retrieve. -/// \param result Property value. +/// \param result Receives the property value. HRESULT DispPropGet(IDispatch* pdisp, PCWSTR name, VARIANT* result); HRESULT DispPropGet(IUnknown* punk, PCWSTR name, VARIANT* result); @@ -84,6 +84,6 @@ int ButtonToFriendlyNumber(int button); /// See CScriptInfo::ExecuteWorker for detailed explanation. void ResetKeyboardState(); -/// Checks if the script execution was aborted and if so, fills appropriately -/// the exception information. +/// Checks whether script execution was aborted and, if so, fills the +/// exception information accordingly. HRESULT CheckAbort(__in class CScriptInfo* pScriptInfo, __out EXCEPINFO* pExcepInfo); diff --git a/src/plugins/automation/cfgdlg.cpp b/src/plugins/automation/cfgdlg.cpp index d712a4d59..7fdd2a392 100644 --- a/src/plugins/automation/cfgdlg.cpp +++ b/src/plugins/automation/cfgdlg.cpp @@ -61,9 +61,9 @@ INT_PTR CAutomationConfigDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lPa HWND hwndList = GetDlgItem(HWindow, IDC_DIRLIST); if (hwndFrom == hwndList || GetParent(hwndFrom) == hwndList) { - // command forwarded from the list view, - // do not pass it to the CDialog::DialogProc - // since if it is IDOK the dialog will close + // command forwarded from the list view; + // do not pass it to CDialog::DialogProc, + // because IDOK would close the dialog return FALSE; } @@ -330,8 +330,8 @@ BOOL CAutomationConfigDialog::OnDirListBeginLabelEdit(NMLVDISPINFO* nmlv) _ASSERTE(IsWindow(hwndEdit)); // autocomplete must be attached before we subclass - // the edit control to not mess the subclass chain - // while unsubclassing + // the edit control so as not to disrupt the subclass chain + // during unsubclassing SHAutoComplete(hwndEdit, SHACF_FILESYS_DIRS); SubclassLabelEdit(hwndEdit); @@ -383,9 +383,9 @@ BOOL CAutomationConfigDialog::OnDirListEndLabelEdit(NMLVDISPINFO* nmlv) // accept the edited text SetWindowLongPtr(HWindow, DWLP_MSGRESULT, TRUE); - // the width of the column might be changed, - // defer recalcing the width once the new text will - // be set after we return from this notification handler + // the column width might change; + // defer recalculating it until the new text is set + // after we return from this notification handler PostMessage(HWindow, WM_USER_RECALCWIDTH, 0, 0); DirSelChanged(); diff --git a/src/plugins/automation/dispimpl.h b/src/plugins/automation/dispimpl.h index 2e09c7a1e..0bc2216ef 100644 --- a/src/plugins/automation/dispimpl.h +++ b/src/plugins/automation/dispimpl.h @@ -24,11 +24,11 @@ } /* - We must implement IDispatchEx for the very stupid VBScript engine. - We used to use simple StdDispatch implementation, but VB insists - on IDispatchEx and if it doesn't get it it simply !!!CASTS!!! - the interface pointer to the IDispatch which is not very good - with the aggregated StdDispatch interface and it caused strange + We must implement IDispatchEx for the VBScript engine. + We used to use a simple StdDispatch implementation, but VB requires + IDispatchEx and if it does not get it, it simply casts + the interface pointer to IDispatch, which does not work well + with the aggregated StdDispatch interface and caused strange crashes. */ @@ -210,8 +210,8 @@ class CDispatchImpl : public Interface, if (SUCCEEDED(hr) && pVarResult != NULL && V_VT(pVarResult) == VT_DISPATCH) { - // it seems that std DispInvoke is not able - // to coerce return value to proper pointer to + // it seems that standard DispInvoke is not able + // to coerce the return value to a proper pointer to // IDispatch in case of dual interface objects IDispatch* pdisp; diff --git a/src/plugins/automation/engassoc.cpp b/src/plugins/automation/engassoc.cpp index 8fc8f00e5..bb5835278 100644 --- a/src/plugins/automation/engassoc.cpp +++ b/src/plugins/automation/engassoc.cpp @@ -122,8 +122,8 @@ HRESULT CScriptEngineAssociations::QueryHardcodedScriptEngineAssociation( PCTSTR pszExt, __out CLSID* clsidEngine) { - // Windows really makes hard time for us to use the JScript engine. - // Use hardcoded association for .js files if everything else fails. + // Windows really makes it hard for us to use the JScript engine. + // Use a hardcoded association for .js files if everything else fails. if (_tcsicmp(pszExt, _T(".js")) == 0) { diff --git a/src/plugins/automation/entry.cpp b/src/plugins/automation/entry.cpp index f844b512b..90f397e16 100644 --- a/src/plugins/automation/entry.cpp +++ b/src/plugins/automation/entry.cpp @@ -69,7 +69,7 @@ static void WINAPI HTMLHelpCallback(HWND hWindow, UINT helpID) /// Returns the object representing the plugin. /// \param salamander Pointer to the CSalamanderPluginEntryAbstract interface. -/// \return If the function succeeds, the return value is pointer to the +/// \return If the function succeeds, the return value is a pointer to the /// plugin object. If the function fails, the return value is NULL. CPluginInterfaceAbstract* WINAPI @@ -131,9 +131,9 @@ CPluginInterfaceAbstract* return &g_oAutomationPlugin; } -/// Returns version of Open Salamander required to run this plugin. -/// \return The return value is required version of Open Salamander. -/// For list of version values see \e spl_vers.h. +/// Returns the version of Open Salamander required to run this plugin. +/// \return The return value is the required version of Open Salamander. +/// For a list of version values, see \e spl_vers.h. int WINAPI SalamanderPluginGetReqVer() { return LAST_VERSION_OF_SALAMANDER; diff --git a/src/plugins/automation/generated/readme.txt b/src/plugins/automation/generated/readme.txt index b0760b3a8..7aa822048 100644 --- a/src/plugins/automation/generated/readme.txt +++ b/src/plugins/automation/generated/readme.txt @@ -1 +1,3 @@ -V tomto adresari jsou jen automaticky generovane soubory. \ No newline at end of file +CommentsTranslationProject: TRANSLATED + +This directory contains only automatically generated files. diff --git a/src/plugins/automation/guicomponent.h b/src/plugins/automation/guicomponent.h index 32fc05429..742622192 100644 --- a/src/plugins/automation/guicomponent.h +++ b/src/plugins/automation/guicomponent.h @@ -17,7 +17,7 @@ #include "guidefs.h" /// Component base class. -/// You never use this class directly, you must create inherited class. +/// Never use this class directly; create a derived class instead. class CSalamanderGuiComponentBase : public ISalamanderGuiComponentInternal { private: diff --git a/src/plugins/automation/guicontainer.cpp b/src/plugins/automation/guicontainer.cpp index b4e85cbbb..5bf56d52d 100644 --- a/src/plugins/automation/guicontainer.cpp +++ b/src/plugins/automation/guicontainer.cpp @@ -248,7 +248,7 @@ HRESULT CSalamanderGuiContainerBase::ContainerPutMember( } else { - // Setting non-existent member to NULL is no-op. + // Setting a non-existent member to NULL is a no-op. _ASSERT(pComponent == NULL); } @@ -281,7 +281,7 @@ HRESULT CSalamanderGuiContainerBase::ContainerPutMember( if (FAILED(hr)) { - // It's not a component. + // Not a component. if (pComponent) { diff --git a/src/plugins/automation/guiform.cpp b/src/plugins/automation/guiform.cpp index b3c0b1838..11a8d70f9 100644 --- a/src/plugins/automation/guiform.cpp +++ b/src/plugins/automation/guiform.cpp @@ -109,7 +109,7 @@ CSalamanderGuiForm::~CSalamanderGuiForm() HMENU hSysMenu = GetSystemMenu(m_hWnd, FALSE); - // If the form does not have the Cancel button, disable also the + // If the form does not have a Cancel button, also disable the // close button in the title bar. if (m_nCloseCode == -1) { @@ -138,8 +138,8 @@ CSalamanderGuiForm::~CSalamanderGuiForm() DeleteMenu(hSysMenu, SC_SIZE, MF_BYCOMMAND); } - // Remove separator between "Move" and "Close" if they - // remained the only items in the sys menu. + // Remove the separator between "Move" and "Close" if they + // are the only items left in the system menu. int iMove = -1; int iClose = -1; @@ -558,8 +558,8 @@ void CSalamanderGuiForm::InternalAddComponent( } // If some attributes of the previous component (most notably - // the Text property) were changed, its dimension might - // change as well. Expand bounds of the form to hold resized + // the Text property) were changed, its dimensions might + // change as well. Expand bounds of the form to hold the resized // component. UnionBounds(prevBounds); } @@ -669,10 +669,10 @@ void CSalamanderGuiForm::UnionBounds(const SALGUI_BOUNDS& bounds) void CSalamanderGuiForm::AlignButtons() { - // Contains pointers to standard buttons (have the DialogResult - // property set) added on the form. The array is indexed by - // the exit codes (IDOK, IDCANCEL...). Element zero is spare. - // Elements 16, 17 and 18 are specific buttons, see + // Contains pointers to standard buttons (with the DialogResult + // property set) added to the form. The array is indexed by + // exit codes (IDOK, IDCANCEL...). Element zero is unused. + // Elements 16, 17, and 18 are specific buttons; see the // ButtonToFriendlyNumber function. ISalamanderGuiComponentInternal* apButtons[MAX_EXIT_BUTTONS] = { 0, @@ -777,7 +777,7 @@ void CSalamanderGuiForm::AlignButtons() else if (apButtons[IDCANCEL]) { // If there is a Cancel button on the form, make the close - // button return the Cancel as well. + // button return the Cancel code as well. m_nCloseCode = IDCANCEL; } else @@ -833,8 +833,8 @@ void CSalamanderGuiForm::AlignButtonLine( int xshift; int cxClient, cxButtons; - // Center the buttons bounding rect in the form client rect, - // calculate x-shift offset and the shift all the buttons by + // Center the buttons' bounding rect in the form client rect, + // calculate the x-shift offset, and then shift all the buttons by // that offset. GetClientRect(m_hWnd, &rcClient); cxClient = rcClient.right; diff --git a/src/plugins/automation/help/hh/salamander_help_shared.css b/src/plugins/automation/help/hh/salamander_help_shared.css index a0f833192..f259c75cd 100644 --- a/src/plugins/automation/help/hh/salamander_help_shared.css +++ b/src/plugins/automation/help/hh/salamander_help_shared.css @@ -1,3 +1,4 @@ +/* CommentsTranslationProject: TRANSLATED */ /* Cascading Style Sheet for Open Salamander Help */ /* Shared part used for both CHM and WEB */ @@ -206,14 +207,14 @@ #help_page td.hdr { - /* tmavsi seda na leve strane */ + /* darker gray on the left side */ margin: .25em; background: #dddddd; vertical-align: top; padding: 2px 4px; font-weight: bold; - width: 10%; /* zuzime levou stranu tabulky na minimum */ - padding-right :10px; /* ale nechame tam alespon 10 bodu, at to trochu vypada */ + width: 10%; /* narrow the left side of the table to the minimum */ + padding-right :10px; /* but keep at least 10 points there so it still looks decent */ white-space: nowrap; } @@ -322,4 +323,3 @@ padding-left: 4px; text-align: left; } - diff --git a/src/plugins/automation/processlist.h b/src/plugins/automation/processlist.h index 2e093b990..16af30cd8 100644 --- a/src/plugins/automation/processlist.h +++ b/src/plugins/automation/processlist.h @@ -13,6 +13,6 @@ #pragma once -// returns TRUE when window 'hWnd' belongs to process with 'dwProcessId' -// function walks through parent processes +// Returns TRUE when window 'hWnd' belongs to the process with 'dwProcessId'. +// The function walks through parent processes. BOOL WindowBelongsToProcessID(HWND hWnd, DWORD dwProcessId); diff --git a/src/plugins/automation/raiserr.h b/src/plugins/automation/raiserr.h index 11322efe7..9441efa01 100644 --- a/src/plugins/automation/raiserr.h +++ b/src/plugins/automation/raiserr.h @@ -15,7 +15,7 @@ void RaiseError(LPCOLESTR pszDescription, REFIID riid, LPCOLESTR pszProgId); -/// \param nIdDescription Idenfier of the string in the language +/// \param nIdDescription Identifier of the string in the language /// module that describes the error. void RaiseError(int nIdDescription, REFIID riid, LPCOLESTR pszProgId); diff --git a/src/plugins/automation/salamanderaut.cpp b/src/plugins/automation/salamanderaut.cpp index b3452420c..37e8dc886 100644 --- a/src/plugins/automation/salamanderaut.cpp +++ b/src/plugins/automation/salamanderaut.cpp @@ -119,7 +119,7 @@ static void WINAPI ShowMsgBoxProc(void* pContext) if (msgbox.nDlgResult == 0) { - // the most probable reason of failure is invalid arguments + // the most likely reason for the failure is invalid arguments // to SalMessageBoxEx return E_INVALIDARG; } @@ -891,7 +891,7 @@ static void CALLBACK ShowQuestionDialogProc(void* pContext) if (FAILED(hr)) { - // TODO: report better error, st. like "panel object expected" + // TODO: report a better error, e.g. "panel object expected" return hr; } } diff --git a/src/plugins/automation/scriptlist.cpp b/src/plugins/automation/scriptlist.cpp index b2f7a3054..2bc91855d 100644 --- a/src/plugins/automation/scriptlist.cpp +++ b/src/plugins/automation/scriptlist.cpp @@ -348,9 +348,9 @@ bool CScriptInfo::ExecuteWorker(EXECUTION_INFO* info) m_bSiteErrorDisplayed = false; if (!CreateEngine(info)) { - // If the error occured during parsing and was already displayed - // through the site's OnScriptError event, don't display it here. - // Otherwise display generic error message here. + // If the error occurred during parsing and was already displayed + // through the site's OnScriptError event, do not display it here. + // Otherwise, display a generic error message here. if (!m_bSiteErrorDisplayed) { SalamanderGeneral->SalMessageBox( @@ -363,42 +363,44 @@ bool CScriptInfo::ExecuteWorker(EXECUTION_INFO* info) return false; } - // workaround for WshShell.SendKeys to work properly (by john): - // Salamander is not responding properly on SendKeys (http://msdn.microsoft.com/en-us/library/8c6yea83%28VS.85%29.aspx) - // when Ctrl/Shift/Alt is still pressed (for example when script was started using Ctrl+Shift+Z hot key). - // Miranda global hot key (Ctrl+Shift+A) is triggered on (salamander ->) Ctrl+Shift+Z -> (script started ->) SendKeys("a"). - // Attempt to release pressed Ctrl/Shift/Alt using SetKeyboardState() doesn't work. - // Note: it seems that SendKeys is using API ::SendInput() beacause it doesn't work too (Miranda is activated). - // Fortunately, following hack works pretty well. + // Workaround to make WshShell.SendKeys work correctly (by john): + // Salamander does not handle SendKeys correctly while Ctrl/Shift/Alt are still pressed + // (for example, when the script was started with the Ctrl+Shift+Z hotkey): + // http://msdn.microsoft.com/en-us/library/8c6yea83%28VS.85%29.aspx + // Miranda's global hotkey (Ctrl+Shift+A) is triggered by the sequence + // Ctrl+Shift+Z in Salamander -> script start -> SendKeys("a"). + // An attempt to release pressed Ctrl/Shift/Alt with SetKeyboardState() does not work. + // SendKeys appears to use the ::SendInput() API, because that does not work either + // (Miranda is activated). Fortunately, the following workaround works well. ResetKeyboardState(); m_pShim->BeginExecution(); // Run the script. // We used to have only SetScriptState(SCRIPTSTATE_CONNECTED) here, but tracing - // the cscript.exe revealed, that it calls SCRIPTSTATE_INITIALIZED immediately - // followed by SCRIPTSTATE_STARTED. We changed the logic here to match the one - // of cscript.exe more closely. This was done primarily because of RScript22 - // won't execute a script without SCRIPTSTATE_STARTED. Hopefully, this won't - // break other engines (JScript and VBScript seems fine). + // cscript.exe revealed that it calls SCRIPTSTATE_INITIALIZED immediately, + // followed by SCRIPTSTATE_STARTED. We changed the logic here to match + // cscript.exe more closely. This was done primarily because RScript22 + // will not execute a script without SCRIPTSTATE_STARTED. Hopefully, this will not + // break other engines (JScript and VBScript seem fine). hr = m_pScript->SetScriptState(SCRIPTSTATE_INITIALIZED); if (SUCCEEDED(hr)) { hr = m_pScript->SetScriptState(SCRIPTSTATE_STARTED); } - // ActivePython returns SCRIPT_E_REPORTED if there was parse error. - // If debugging is enabled, the SCRIPT_E_PROPAGATE may be returned - // if debugger is detached while an exception is being debugged. + // ActivePython returns SCRIPT_E_REPORTED if there was a parse error. + // If debugging is enabled, SCRIPT_E_PROPAGATE may be returned + // if the debugger is detached while an exception is being debugged. _ASSERTE(SUCCEEDED(hr) || hr == SCRIPT_E_REPORTED || hr == SCRIPT_E_PROPAGATE || m_pHardError); m_pSite->SetExecutionInfo(NULL); UninitializeDebugger(&info->dbgInfo); m_pShim->EndExecution(); - // cscript.exe doesn't call SetScriptState at all at the end of the execution. But it can - // afford not calling it because the process ends afterwards. We must deal with buggy - // engines and do need to uninitialize it. + // cscript.exe does not call SetScriptState at the end of execution. + // It can afford not to, because the process exits afterwards. We must handle + // buggy engines and explicitly uninitialize them. hr = m_pScript->SetScriptState(SCRIPTSTATE_INITIALIZED); _ASSERTE(SUCCEEDED(hr)); @@ -546,7 +548,7 @@ HRESULT CScriptInfo::AbortScript() // message boxes, exit GUI loops, cancel sleeps, break // enumerators etc.). - // Set the abort event, so the kernel waits can exit (e.g. + // Set the abort event so kernel wait operations can exit (e.g. // Salamander.Sleep()). _ASSERTE(m_hAbortEvent != NULL); SetEvent(m_hAbortEvent); @@ -574,13 +576,14 @@ void CScriptInfo::ScriptEnter() hwndPalette = m_pExecInfo->pAbortPalette->GetHwnd(); _ASSERTE(IsWindow(hwndPalette)); - // Make the main window inaccessible, since the script may display - // modeless window and the user can unload the whole plugin from - // the main window in the mean time. - // NOTE: 'hwndPalette' mechanism is not used because WS_EX_TOPMOST with process tree - // checking using WindowBelongsToProcessID() look like better solution for now. - // For example unpack script is starting several command prompt windows - // so WS_EX_TOPMOST toolbar is better accessible. + // Make the main window inaccessible because the script may display a + // modeless window, and the user could unload the entire plugin from + // the main window in the meantime. + // NOTE: The 'hwndPalette' mechanism is not used because WS_EX_TOPMOST with + // process-tree checking via WindowBelongsToProcessID() looks like a better + // solution for now. + // For example, the unpack script starts several command prompt windows, + // so a WS_EX_TOPMOST toolbar is more accessible. SalamanderGeneral->LockMainWindow(TRUE, NULL, SalamanderGeneral->LoadStr(g_hLangInst, IDS_MAINWINDOWLOCKED)); } } @@ -874,7 +877,7 @@ int CScriptLookup::FillContainer( if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { - if (fd.cFileName[0] != _T('.')) // exclude . and .. as well as unix style hidden dirs + if (fd.cFileName[0] != _T('.')) // exclude . and .. as well as Unix-style hidden directories { int cSubScripts = 0; CScriptContainer* pSubContainer; @@ -1135,8 +1138,8 @@ int CScriptLookup::GetUniquier( StringCchPrintf(szName, _countof(szName), "%06X", HashFromId(nHash)); if (!registry->OpenKey(hKey, szName, hkSub)) { - // the hash key does not even exist in the registry, - // return 1st available uniquier + // the hash key does not exist in the registry, + // return the first available uniquier m_bModified = true; return 0; } @@ -1173,7 +1176,7 @@ int CScriptLookup::GetUniquier( registry->CloseKey(hkSub); // the script path was not found in the registry, - // look if we can allocate a new uniquier for this path + // check whether we can allocate a new uniquifier for this path m_bModified = true; return bitmap.Alloc(); } @@ -1208,7 +1211,7 @@ int CScriptLookup::GetUniquier( return bitmap.Alloc(); } - // no uniquier for this hash yet, start counting at zero + // no uniquifier for this hash yet; start counting from zero return 0; } @@ -1257,9 +1260,9 @@ bool CScriptLookup::Refresh(bool bForce) if (GetTickCount() - m_dwLastRefreshTime < 5000 && !bForce) { - // ignore refresh request if it comes too early - // since the last one (this prevents excessive - // disk activity when user repeatedly runs a script) + // ignore the refresh request if it comes too soon + // after the last one (this prevents excessive + // disk activity when the user repeatedly runs a script) return true; } diff --git a/src/plugins/automation/scriptlist.h b/src/plugins/automation/scriptlist.h index 08b9bfe6a..da2f2b34b 100644 --- a/src/plugins/automation/scriptlist.h +++ b/src/plugins/automation/scriptlist.h @@ -70,7 +70,7 @@ class CScriptInfo IActiveScriptError* m_pHardError; bool m_bSiteErrorDisplayed; ///< Message box shown in site's OnScriptError. class CScriptEngineShim* m_pShim; - HANDLE m_hAbortEvent; ///< Manually reset event signaled when the user requested abort. + HANDLE m_hAbortEvent; ///< Manual-reset event signaled when the user requests abort. HWND m_hwndAbortTarget; // statistics stuff diff --git a/src/plugins/automation/scriptsite.cpp b/src/plugins/automation/scriptsite.cpp index 138652f72..1eb7f6b33 100644 --- a/src/plugins/automation/scriptsite.cpp +++ b/src/plugins/automation/scriptsite.cpp @@ -195,10 +195,10 @@ HRESULT CScriptSite::OnStateChange( HRESULT CScriptSite::OnScriptError( /* [in] */ __RPC__in_opt IActiveScriptError* pScriptError) { - // May be NULL if the error raises during the parsing phase. + // May be NULL if the error occurs during the parsing phase. if (m_pExecInfo != NULL) { - // The abort palette is no longer needed, hide it now. + // The abort palette is no longer needed; delete it now. delete m_pExecInfo->pAbortPalette; m_pExecInfo->pAbortPalette = NULL; } @@ -220,10 +220,10 @@ HRESULT CScriptSite::OnScriptError( FreeException(ei); - // Never ever try to return anything else than S_OK here. + // Never return anything other than S_OK here. // If JScript.dll returns CTL_E_OUTOFMEMORY because of infinite - // recursion (see Redmine #782 bug) it keeps calling OnScriptError - // again and again if we return anything else than S_OK. + // recursion (see Redmine #782), it keeps calling OnScriptError + // repeatedly unless we return S_OK. return S_OK; } @@ -382,10 +382,10 @@ HRESULT STDMETHODCALLTYPE CScriptSite::OnScriptErrorDebug( /* [out] */ BOOL* pfEnterDebugger, /* [out] */ BOOL* pfCallOnScriptErrorWhenContinuing) { - // May be NULL if the error raises during the parsing phase. + // May be NULL if the error occurs during the parsing phase. if (m_pExecInfo != NULL) { - // The abort palette is no longer needed, hide it now. + // The abort palette is no longer needed; delete it now. delete m_pExecInfo->pAbortPalette; m_pExecInfo->pAbortPalette = NULL; } diff --git a/src/plugins/automation/shim.cpp b/src/plugins/automation/shim.cpp index 2f3af3a00..1a54e2380 100644 --- a/src/plugins/automation/shim.cpp +++ b/src/plugins/automation/shim.cpp @@ -61,7 +61,7 @@ CScriptEngineShim* CScriptEngineShim::Create(CScriptInfo* pScript) void CScriptEngineShim::AdjustSourcePosition(LONG& linePos, LONG& columnPos) { // JScript and VBScript are zero-based, - // so threat this as default behavior + // so treat this as the default behavior. linePos += 1; columnPos += 1; } @@ -159,10 +159,10 @@ bool CScriptEngineShim::DisplayErrorHook(__in EXCEPINFO* ei, __in_opt BSTR src, UNREFERENCED_PARAMETER(src); UNREFERENCED_PARAMETER(bDebug); - // Some engines (Python, Ruby) does not report abortion thru our special - // SALAUT_E_ABORT we pass into the engine, instead they raise COM - // exception. Since this shim is general and should not influence - // anything, I decided to put it here in the base shim. + // Some engines (Python, Ruby) do not report aborts through the special + // SALAUT_E_ABORT we pass to the engine; instead, they raise a COM + // exception. Because this shim is general and should not affect + // anything else, handle it here in the base shim. if (ei && ei->scode == DISP_E_EXCEPTION && m_pScript->IsAbortPending()) { return false; @@ -193,8 +193,8 @@ CScriptEngineShim* CPhpScriptEngineShim::Create(CScriptInfo* pScript) void CPhpScriptEngineShim::AdjustSourcePosition(LONG& linePos, LONG& columnPos) { - // PHP starts counting lines from one and char position - // always sets to zero. + // PHP starts line numbering at one, and the char position + // is always zero. columnPos = -1; } @@ -206,14 +206,14 @@ HRESULT CPhpScriptEngineShim::ReleaseEngine(IActiveScript* pScript) // This is needed for the buggy PHP script engine to revoke // instance from the global interface table. hr = pScript->SetScriptSite(NULL); - // Behaved engines return E_POINTER, unlike PHP, which returns S_OK + // Well-behaved engines return E_POINTER, unlike PHP, which returns S_OK, // and ActivePython, which returns E_FAIL. _ASSERTE(SUCCEEDED(hr)); hr = ReleaseEngineCore(pScript, cRef); - // Workaround for the buggy PHP script engine - // to kill the script thread and delete the engine object + // Workaround for a PHP script engine bug: + // kill the script thread and delete the engine object if (cRef == 1) { cRef = pScript->Release(); @@ -275,9 +275,9 @@ CScriptEngineShim* CGlobalRubyScriptEngineShim::Create(CScriptInfo* pScript) void CGlobalRubyScriptEngineShim::AdjustSourcePosition(LONG& linePos, LONG& columnPos) { - // Ruby seems not using position information at all, - // both the line and column is always set to zero, - // the line number is mentioned in the description + // Ruby does not seem to use position information at all: + // both the line and column are always set to zero, + // and the line number is mentioned in the description // and is one-based. linePos = columnPos = -1; } @@ -303,18 +303,17 @@ void CGlobalRubyScriptEngineShim::Site_OnLeaveScript() HRESULT CGlobalRubyScriptEngineShim::InterruptScript(IActiveScript* pScript) { // Redmine #817: - // Calling InterruptScriptThread on Ruby engine is a suicidal mission. - // What is going on? + // Calling InterruptScriptThread on the Ruby engine is unsafe. + // Behavior observed: // 1. Ruby suspends the thread executing the script (i.e. Salamander's // main thread). // 2. It sets the thread context, forcing the instruction pointer to - // be address of the internal rb_raise function. + // the address of the internal rb_raise function. // 3. The engine resumes the thread. - // 4. The thread's context is completely messed up, executing the - // rb_raise function (which does longjmp according to search results - // on Google) without correctly unwinding the stack. - // I still cannot believe this. To make the long story short, we just - // prevent calling InterruptScriptThread when running Ruby script and - // we are leaving the script to be interrupted cooperatively. + // 4. The thread's context is corrupted, executing the rb_raise function + // (which reportedly calls longjmp) without correctly unwinding the + // stack. + // In short, prevent InterruptScriptThread from being called when running + // a Ruby script and let the script be interrupted cooperatively. return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } diff --git a/src/plugins/automation/versinfo.rh2 b/src/plugins/automation/versinfo.rh2 index 694953665..c6f6e30a2 100644 --- a/src/plugins/automation/versinfo.rh2 +++ b/src/plugins/automation/versinfo.rh2 @@ -1,4 +1,5 @@ -/* +// CommentsTranslationProject: TRANSLATED +/* Automation Plugin for Open Salamander Copyright (c) 2009-2023 Milan Kase @@ -18,7 +19,7 @@ #define VERSINFO_MAJOR 1 #define VERSINFO_MINORA 7 -#define VERSINFO_MINORB 0 // POZOR: tady musi byt 0, jinak vyleti assert pri buildu +#define VERSINFO_MINORB 0 // Must be 0, otherwise the build will hit an assert. #include "spl_vers.h" // get version and build numbers diff --git a/src/plugins/checksum/checksum.h b/src/plugins/checksum/checksum.h index d2fde76ca..ccb58c3ef 100644 --- a/src/plugins/checksum/checksum.h +++ b/src/plugins/checksum/checksum.h @@ -14,7 +14,7 @@ typedef enum eHASH_TYPE HT_SHA1, HT_SHA256, HT_SHA512, - HT_COUNT // Not a hash type but # of known hash types + HT_COUNT // Not a hash type, but the count of known hash types } eHASH_TYPE; typedef struct SHashInfo diff --git a/src/plugins/checksum/checksum.rh2 b/src/plugins/checksum/checksum.rh2 index a47e02b24..4b0a33304 100644 --- a/src/plugins/checksum/checksum.rh2 +++ b/src/plugins/checksum/checksum.rh2 @@ -1,4 +1,5 @@ -// WARNING: cannot be replaced by "#pragma once" because it is included from .rc file and it seems resource compiler does not support "#pragma once" +// CommentsTranslationProject: TRANSLATED +// WARNING: cannot be replaced with "#pragma once" because this file is included from a .rc file, and the resource compiler does not seem to support "#pragma once". #ifndef __CHECKSUM_RH2 #define __CHECKSUM_RH2 @@ -7,7 +8,7 @@ #endif //defined(APSTUDIO_INVOKED) && !defined(APSTUDIO_READONLY_SYMBOLS) #define IDC_STATIC_1 300 -#include "statics.rh2" // 300 az 339 jsou timto zabrane !!! +#include "statics.rh2" // 300 to 339 are reserved by this include. #define IDS_PLUGINNAME 1 #define IDS_ABOUTTITLE 2 @@ -86,17 +87,17 @@ #define IDC_CFG_SUM_1 100 -//#define IDC_CFG_CRC IDC_CFG_SUM_1 // tenhle zapis nezkompiluje HTML Help Compiler +//#define IDC_CFG_CRC IDC_CFG_SUM_1 // this form will not compile in HTML Help Compiler #define IDC_CFG_CRC 100 -//#define IDC_CFG_MD5 (IDC_CFG_CRC+1) // tenhle zapis nezkompiluje HTML Help Compiler +//#define IDC_CFG_MD5 (IDC_CFG_CRC+1) // this form won't compile in HTML Help Compiler #define IDC_CFG_MD5 101 -//#define IDC_CFG_SHA1 (IDC_CFG_MD5+1) // tenhle zapis nezkompiluje HTML Help Compiler +//#define IDC_CFG_SHA1 (IDC_CFG_MD5+1) // HTML Help Compiler won't compile this form #define IDC_CFG_SHA1 102 -//#define IDC_CFG_SHA256 (IDC_CFG_SHA1+1) // tenhle zapis nezkompiluje HTML Help Compiler +//#define IDC_CFG_SHA256 (IDC_CFG_SHA1+1) // HTML Help Compiler won't compile this form #define IDC_CFG_SHA256 103 -//#define IDC_CFG_SHA512 (IDC_CFG_SHA256+1) // tenhle zapis nezkompiluje HTML Help Compiler +//#define IDC_CFG_SHA512 (IDC_CFG_SHA256+1) // HTML Help Compiler won't compile this form #define IDC_CFG_SHA512 104 -//#define IDC_CFG_SUM_COUNT (IDC_CFG_SHA512+1) // tenhle zapis nezkompiluje HTML Help Compiler +//#define IDC_CFG_SUM_COUNT (IDC_CFG_SHA512+1) // this form won't compile in HTML Help Compiler #define IDC_CFG_SUM_COUNT 105 #endif // __CHECKSUM_RH2 diff --git a/src/plugins/checksum/dialogs.cpp b/src/plugins/checksum/dialogs.cpp index 4e359eac5..6921a2846 100644 --- a/src/plugins/checksum/dialogs.cpp +++ b/src/plugins/checksum/dialogs.cpp @@ -179,7 +179,7 @@ void CSFVMD5Dialog::OnThreadEnd() ShowWindow(GetDlgItem(HWindow, IDC_LABEL), SW_HIDE); ShowWindow(GetDlgItem(HWindow, IDC_PROGRESS), SW_HIDE); bThreadRunning = FALSE; - if (ScrollIndex < FileList.Count) // the worker already stopped counting (it may still be running), no sync needed + if (ScrollIndex < FileList.Count) // the worker thread is no longer calculating (it may still be running), so no synchronization is needed { // update the last "calculated" item so it does not remain calculating / verifying ... SetRowsDirty(ScrollIndex, ScrollIndex); } @@ -330,11 +330,12 @@ INT_PTR CSFVMD5Dialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) int i = -1; // -1 = do not call ensure visible if (ScheduledScrollIndex != ScrollIndex) { - // at this moment items up to ScrollIndex are acknowledged as computed, - // ScrollIndex itself is calculating / verifying and the items after it remain unprocessed - // (even if they are already computed, they will surface in the next cycle) - // show the newly acknowledged computed data + the new ScrollIndex must be repainted - // (to print calculating / verifying) + // at this moment, computed data up to ScrollIndex becomes visible; + // ScrollIndex itself is calculating / verifying, and the items after it remain uncomputed + // (even if they have already been computed, they are not shown + // until the next cycle) + // repaint the newly visible computed data + the new ScrollIndex + // (display calculating / verifying) SetRowsDirty(ScrollIndex, ScheduledScrollIndex); ScrollIndex = ScheduledScrollIndex; if (bScrollToItem) @@ -413,7 +414,7 @@ INT_PTR CSFVMD5Dialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (!IsWindowEnabled(HWindow)) { // close all dialogs stacked above this one (send them WM_CLOSE and then send it here again) SalamanderGeneral->CloseAllOwnedEnabledDialogs(HWindow); - if (iThreadID != 0) // if a thread is running, close its windows too and let it finish + if (iThreadID != 0) // if a thread is running, close its windows too and let it terminate { // to avoid immediately opening another window with a new error bTerminateThread = TRUE; SalamanderGeneral->CloseAllOwnedEnabledDialogs(HWindow, iThreadID); @@ -428,7 +429,7 @@ INT_PTR CSFVMD5Dialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_DESTROY: { - if (hThread != NULL) // if we started the thread, close it and wait for it + if (hThread != NULL) // if we started the thread, request its termination and wait for it { bTerminateThread = TRUE; ThreadQueue.WaitForExit(hThread, INFINITE); @@ -461,7 +462,7 @@ CCalculateDialog::CCalculateDialog(HWND parent, BOOL alwaysOnTop, TSeedFileList* void CCalculateDialog::RefreshUI() { MSG msg; - while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) // we want responsive GUI + while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) // Keep the GUI responsive { if (!IsWindow(HWindow) || !IsDialogMessage(HWindow, &msg)) { @@ -1278,7 +1279,7 @@ INT_PTR CCalculateDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) NMLVDISPINFO* plvdi = (NMLVDISPINFO*)nmh; int index = plvdi->item.iItem; if (index < 0 || index >= FileList.Count) // while the worker thread runs, the array is not modified - break; // array size does not change = no synchronization + break; // the array size does not change, so no synchronization is needed if (plvdi->item.mask & LVIF_IMAGE) { // ScrollIndex nor the icons before it are modified by the thread, no synchronization needed @@ -1299,7 +1300,7 @@ INT_PTR CCalculateDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) } case 1: - { // Size: once added to the array it never changes = access is not synchronized + { // Size: once added to the array, it never changes, so access is not synchronized SalamanderGeneral->NumberToStr(plvdi->item.pszText, FileList[index]->Size); break; } @@ -1497,8 +1498,8 @@ BOOL CVerifyDialog::AnalyzeSourceFile() isSFV = FALSE; // not an SFV } - // WARNING: the following code must match CGenericHashAlgo::ParseDigest() !!! - // checksum at the beginning (before ' ') or checksum at the end (after ' ' or '=') and at the same time + // WARNING: the following code must remain consistent with CGenericHashAlgo::ParseDigest() !!! + // checksum at the beginning (before ' ') or at the end (after ' ' or '=') and also // the hash name at the beginning (before '(' or ' ') int posFirst, lenFirst; @@ -1810,7 +1811,7 @@ void CVerifyDialog::OnThreadEnd() { if (!nMissing && !nSkipped && !nCorrupt) { - if (fileList.Count) // while the worker thread runs, the array is not modified + if (fileList.Count) // while the worker thread is running, the number of items in the array does not change strcpy(text, LoadStr(IDS_ALLOK)); // number of items does not change = no synchronization needed else strcpy(text, LoadStr(IDS_NOFILES)); @@ -1905,7 +1906,7 @@ INT_PTR CVerifyDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) lstrcpyn(Focus_Path, fileList[i]->fileName, MAX_PATH); SalamanderGeneral->PostMenuExtCommand(CMD_FOCUSFILE, TRUE); Sleep(500); // switching to another window happens, so this Sleep should not hurt anything - Focus_Path[0] = 0; // after 0.5 seconds we no longer want the focus (handles hitting the start of Salamander's BUSY mode) + Focus_Path[0] = 0; // after 0.5 seconds we no longer need the focus (handles the case where we hit the start of Salamander's BUSY mode) } else SalamanderGeneral->SalMessageBox(HWindow, LoadStr(IDS_BUSY), LoadStr(IDS_VERIFYTITLE), MB_ICONINFORMATION); @@ -1950,7 +1951,7 @@ INT_PTR CVerifyDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) break; } - case 1: // FileExist+Size: once added to the array it never changes = no synchronization needed + case 1: // FileExist+Size: once added to the array, they do not change, so access is not synchronized { if (FileList[index]->FileExist) SalamanderGeneral->NumberToStr(plvdi->item.pszText, FileList[index]->Size); @@ -2086,7 +2087,7 @@ BOOL OpenCalculateDialog(HWND parent) int nFiles, nDirs; char sourcePath[MAX_PATH]; - // Check if nothing is selected and no focus is set + // Check whether nothing is selected and no item is focused if (SalamanderGeneral->GetPanelSelection(PANEL_SOURCE, &nFiles, &nDirs)) { int index = 0; @@ -2238,7 +2239,7 @@ CCommonDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) // Center horizontally & vertically to parent if (Parent != NULL) SalamanderGeneral->MultiMonCenterWindow(HWindow, Parent, TRUE); - break; // Need focus from DefDlgProc + break; // Need DefDlgProc to set focus } } // switch return CDialog::DialogProc(uMsg, wParam, lParam); diff --git a/src/plugins/checksum/help/hh/salamander_help_shared.css b/src/plugins/checksum/help/hh/salamander_help_shared.css index a0f833192..f259c75cd 100644 --- a/src/plugins/checksum/help/hh/salamander_help_shared.css +++ b/src/plugins/checksum/help/hh/salamander_help_shared.css @@ -1,3 +1,4 @@ +/* CommentsTranslationProject: TRANSLATED */ /* Cascading Style Sheet for Open Salamander Help */ /* Shared part used for both CHM and WEB */ @@ -206,14 +207,14 @@ #help_page td.hdr { - /* tmavsi seda na leve strane */ + /* darker gray on the left side */ margin: .25em; background: #dddddd; vertical-align: top; padding: 2px 4px; font-weight: bold; - width: 10%; /* zuzime levou stranu tabulky na minimum */ - padding-right :10px; /* ale nechame tam alespon 10 bodu, at to trochu vypada */ + width: 10%; /* narrow the left side of the table to the minimum */ + padding-right :10px; /* but keep at least 10 points there so it still looks decent */ white-space: nowrap; } @@ -322,4 +323,3 @@ padding-left: 4px; text-align: left; } - diff --git a/src/plugins/checksum/wrappers.cpp b/src/plugins/checksum/wrappers.cpp index 246efef5f..c1187331a 100644 --- a/src/plugins/checksum/wrappers.cpp +++ b/src/plugins/checksum/wrappers.cpp @@ -17,7 +17,7 @@ class CCRCAlgo : public CHashAlgo virtual bool Init(); // Init for a new file. true on success virtual bool Update(const char* buf, DWORD size); virtual bool Finalize(); - virtual int GetDigest(char* buf, DWORD bufsize); // Returns # of copied binary bytes + virtual int GetDigest(char* buf, DWORD bufsize); // Returns the number of copied binary bytes. virtual bool ParseDigest(char* buf, char* fileName, int fileNameLen, char* digest); private: @@ -45,12 +45,12 @@ class CMD5Algo : public CGenericHashAlgo virtual bool Init(); // Init for a new file. true on success virtual bool Update(const char* buf, DWORD size); virtual bool Finalize(); - virtual int GetDigest(char* buf, DWORD bufsize); // Returns # of copied binary bytes + virtual int GetDigest(char* buf, DWORD bufsize); // Returns the number of copied digest bytes. protected: virtual const char* GetID() { return "MD5"; }; virtual int GetIDLen() { return 3; }; // strlen(GetID()) - virtual int GetDigestLen() { return 16; }; // ensure DIGEST_MAX_SIZE remains large enough! + virtual int GetDigestLen() { return 16; }; // ensure DIGEST_MAX_SIZE is large enough private: CSalamanderMD5* md5; @@ -66,12 +66,12 @@ class CSHA1Algo : public CGenericHashAlgo virtual bool Init(); // Init for a new file. true on success virtual bool Update(const char* buf, DWORD size); virtual bool Finalize(); - virtual int GetDigest(char* buf, DWORD bufsize); // Returns # of copied binary bytes + virtual int GetDigest(char* buf, DWORD bufsize); // Returns the number of copied digest bytes. protected: virtual const char* GetID() { return "SHA1"; }; virtual int GetIDLen() { return 4; }; - virtual int GetDigestLen() { return 20; }; // ensure DIGEST_MAX_SIZE remains large enough! + virtual int GetDigestLen() { return 20; }; // ensure DIGEST_MAX_SIZE does not need to be increased private: CSalSHA1 sha1; @@ -87,12 +87,12 @@ class CSHA256Algo : public CGenericHashAlgo virtual bool Init(); // Init for a new file. true on success virtual bool Update(const char* buf, DWORD size); virtual bool Finalize(); - virtual int GetDigest(char* buf, DWORD bufsize); // Returns # of copied binary bytes + virtual int GetDigest(char* buf, DWORD bufsize); // Returns the number of copied digest bytes. protected: virtual const char* GetID() { return "SHA256"; }; virtual int GetIDLen() { return 6; }; - virtual int GetDigestLen() { return 32; }; // ensure DIGEST_MAX_SIZE remains large enough! + virtual int GetDigestLen() { return 32; }; // ensure DIGEST_MAX_SIZE does not need to be increased private: hash_state sha256; @@ -108,12 +108,12 @@ class CSHA512Algo : public CGenericHashAlgo virtual bool Init(); // Init for a new file. true on success virtual bool Update(const char* buf, DWORD size); virtual bool Finalize(); - virtual int GetDigest(char* buf, DWORD bufsize); // Returns # of copied binary bytes + virtual int GetDigest(char* buf, DWORD bufsize); // Returns the number of copied digest bytes. protected: virtual const char* GetID() { return "SHA512"; }; virtual int GetIDLen() { return 6; }; - virtual int GetDigestLen() { return 64; }; // ensure DIGEST_MAX_SIZE remains large enough! + virtual int GetDigestLen() { return 64; }; // ensure DIGEST_MAX_SIZE does not need to be increased private: hash_state sha512; @@ -248,7 +248,7 @@ bool CCRCAlgo::ParseDigest(char* buf, char* fileName, int fileNameLen, char* dig pos--; buf[pos] = 0; if ((int)strlen(buf) >= fileNameLen) - return false; // too long name + return false; // file name too long strcpy_s(fileName, fileNameLen, buf); return true; } @@ -260,7 +260,7 @@ bool CGenericHashAlgo::ParseDigest(char* buf, char* fileName, int fileNameLen, c int pos, len; // WARNING: the following code must match CVerifyDialog::AnalyzeSourceFile() !!! - // checksum at the beginning (before ' ') or checksum at the end (after ' ' or '=') and at the same time + // checksum at the beginning (before ' ') or at the end (after ' ' or '=') and // the hash name at the beginning (before '(' or ' ') GetFirstWord(buf, pos, len, '('); @@ -285,7 +285,7 @@ bool CGenericHashAlgo::ParseDigest(char* buf, char* fileName, int fileNameLen, c if (buf[pos] == '(') { pos++; - // What if filename contains ')'??? + // File names may contain ')'. // "openssl md5 file().txt" produces: "MD5(file().txt)= 636e5618c32f05ac9f2623169527cd3c" len = (int)strlen(buf); if (len > 0 && buf[len - 1] == ')') @@ -306,7 +306,7 @@ bool CGenericHashAlgo::ParseDigest(char* buf, char* fileName, int fileNameLen, c pos++; // skip the asterisk indicating a binary file } if ((int)strlen(buf + pos) >= fileNameLen) - return false; // too long name + return false; // file name too long strcpy_s(fileName, fileNameLen, buf + pos); return true; } diff --git a/src/plugins/checksum/wrappers.h b/src/plugins/checksum/wrappers.h index 5aaab1408..244a41d7e 100644 --- a/src/plugins/checksum/wrappers.h +++ b/src/plugins/checksum/wrappers.h @@ -13,7 +13,7 @@ class CHashAlgo virtual bool Init() = 0; // Init for a new file. true on success virtual bool Update(const char* buf, DWORD size) = 0; virtual bool Finalize() = 0; - virtual int GetDigest(char* buf, DWORD bufsize) = 0; // Returns # of copied binary bytes + virtual int GetDigest(char* buf, DWORD bufsize) = 0; // Returns the number of copied binary bytes. virtual bool ParseDigest(char* buf, char* fileName, int fileNameLen, char* digest) = 0; }; diff --git a/src/plugins/checkver/checkver.cpp b/src/plugins/checkver/checkver.cpp index 390b66584..2f6ab0425 100644 --- a/src/plugins/checkver/checkver.cpp +++ b/src/plugins/checkver/checkver.cpp @@ -72,9 +72,9 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) } if (fdwReason == DLL_PROCESS_DETACH) { - // if Altap Salamander is blocked from accessing the internet by the firewall and Salamander is closed while checkver is running, - // TRACE is destroyed before this function is called, which leads to a crash in TRACE_I, - // therefore TRACE must not be called here + // if Altap Salamander is blocked from accessing the internet by a firewall and Salamander is closed while checkver is running, + // TRACE is destroyed before this function is called, causing a crash in TRACE_I, + // so TRACE must not be called here //TRACE_I("CheckVer DLL_PROCESS_DETACH"); DeleteCriticalSection(&MainDialogIDSection); if (HModulesEnumDone != NULL) @@ -151,8 +151,8 @@ CPluginInterfaceAbstract* WINAPI SalamanderPluginEntry(CSalamanderPluginEntryAbs DWORD loadInfo = salamander->GetLoadInformation(); - // immediately after Salamander is installed, perform the version check with an open window so that - // it is visible what is happening and the user understands why internet access must be allowed + // immediately after Salamander is installed, perform the version check with the window open so that + // the user can see what is happening and understand why Internet access must be allowed // in the personal firewall if (loadInfo & LOADINFO_NEWSALAMANDERVER) LoadedOnSalInstall = TRUE; @@ -369,7 +369,7 @@ unsigned WINAPI ThreadMessageLoopBody(void* param) } data->Success = HMainDialog != NULL; - SetEvent(data->Continue); // let the main thread continue; from this point on the data are invalid (=NULL) + SetEvent(data->Continue); // let the main thread continue; from this point on, the data are no longer valid (=NULL) data = NULL; MSG msg; diff --git a/src/plugins/checkver/checkver.h b/src/plugins/checkver/checkver.h index 25bb036bf..f3d3d2a45 100644 --- a/src/plugins/checkver/checkver.h +++ b/src/plugins/checkver/checkver.h @@ -11,7 +11,7 @@ #define WM_USER_KEYDOWN WM_APP + 667 // configuration data -enum CAutoCheckModeEnum // how often the plugin window is activated +enum CAutoCheckModeEnum // how often the plugin window is shown { achmNever, achmDay, diff --git a/src/plugins/checkver/data.cpp b/src/plugins/checkver/data.cpp index b088315da..155af628d 100644 --- a/src/plugins/checkver/data.cpp +++ b/src/plugins/checkver/data.cpp @@ -157,9 +157,9 @@ const char* CONFIG_NEXTOPEN = "NextOpen"; const char* CONFIG_NUMOFERRORS = "NumOfErrors"; // ConfigVersion: 0 - no configuration was loaded from the Registry (plugin installation), -// 1 - configuration before the 'Version' value was added to the registry +// 1 - configuration from before the 'Version' value was added to the registry // 2 - Salamander 2.52: enforce new default values (set inetLAN defaults for everyone) -// 3 - Salamander 3.0: enforce new default values (show all new versions, add the "ignore this version" link, hopefully CheckVer will no longer be disabled manually) +// 3 - Salamander 3.0: enforce new default values (show all new versions, add the "ignore this version" link, hopefully CheckVer will no longer be disabled outright) // 4 - Salamander 4.0: enforce new default values int ConfigVersion = 0; // version of the configuration loaded from the registry (see above for description) @@ -357,7 +357,7 @@ void LoadConfig(HKEY regKey, CSalamanderRegistryAbstract* registry) if (regKey != NULL && !registry->GetValue(regKey, CONFIG_VERSION, REG_DWORD, &ConfigVersion, sizeof(DWORD))) ConfigVersion = 1; // configuration before the 'Version' value was added to the registry BOOL curVerIsPB = IsPBVersion(SalamanderTextVersion); - if (curVerIsPB) // the PB build tests PB versions by default + if (curVerIsPB) // in the PB build, PB versions are checked by default { int i; for (i = 0; i < inetCount; i++) @@ -606,9 +606,9 @@ BOOL CSalModuleInfo::SetVersion(const char* version) sprintf(partR + len - 1, ".%d", ch - 'a' + 1); } } - // compose the version - // bug still present in AS2.51: without adding 0.5 the values were "random", because - // when WinSCP is loaded into the process it changes CPU rounding (applies per thread) + // build the version + // bug still present in AS2.51: without adding 0.5, the values came out "random" because + // WinSCP changes the CPU rounding mode when loaded into the process (per-thread) ResolvedVersion = ((WORD)(atof(partL) * 1000 + 0.5)) << 16; if (partR[0] != 0) ResolvedVersion |= ((WORD)(atof(partR) * 100 + 0.5)); @@ -938,10 +938,10 @@ BOOL CModules::BuildDataFromScript() *(line + lineLen) = 0; if (lstrcmp(line, SCRIPT_SIGNATURE_EOF) == 0) - break; // everything loaded... + break; // all data loaded... if (count >= LoadedScriptSize - 2) - break; // time to bail out + break; // time to exit if (*lineEnd == '\r' && *(lineEnd + 1) == '\r' && *(lineEnd + 2) == '\n') { // '\r\r\n' - '\r\n' converted via FTP lineEnd += 3; @@ -1119,7 +1119,7 @@ void CModules::CompareWithInstalledModulesAndLogIt(BOOL rereadModules) { // reset the event ResetEvent(HModulesEnumDone); - // post a command so the main Salamander thread reaches us, + // post a command so that Salamander's main thread reaches us, // from which we can perform the enumeration SalGeneral->PostMenuExtCommand(CM_ENUMMODULES, FALSE); // wait until the enumeration is finished @@ -1172,9 +1172,9 @@ void CModules::CompareWithInstalledModulesAndLogIt(BOOL rereadModules) BOOL newModule = FALSE; if (installed && salMdl->GetResBeta() == mdl->GetResBeta()) { - // if the module is installed and it matches the beta/non-beta state of the scripted module, - // compare their versions (when versions match, decide by checking whether it is an IB/DB/PB/CB, - // a special build always takes precedence over a non-special build and among special builds + // if the module is installed and its beta/non-beta state matches the module from the script, + // compare their versions (if the versions match, whether it is an IB/DB/PB/CB can still decide, + // a special build always takes precedence over a non-special build, and among special builds // the build number decides) if (salMdl->GetResVer() < mdl->GetResVer() || salMdl->GetResVer() == mdl->GetResVer() && salMdl->GetSpecBld() > 0 && mdl->GetSpecBld() == 0 || // same version + installed module is a special build and the scripted module is not diff --git a/src/plugins/checkver/dialogs.cpp b/src/plugins/checkver/dialogs.cpp index dc6c58fcb..57e3a4eb0 100644 --- a/src/plugins/checkver/dialogs.cpp +++ b/src/plugins/checkver/dialogs.cpp @@ -56,7 +56,7 @@ INT_PTR CALLBACK InternetProc(HWND hWindow, UINT uMsg, WPARAM wParam, LPARAM lPa { if ((GetKeyState(VK_CONTROL) & 0x8000) == 0 && (GetKeyState(VK_SHIFT) & 0x8000) == 0) SalGeneral->OpenHtmlHelp(hWindow, HHCDisplayContext, IDD_INTERNET, FALSE); - return TRUE; // never let F1 reach the parent + return TRUE; // never let F1 propagate to the parent } case WM_APP + 55: @@ -285,7 +285,7 @@ INT_PTR CALLBACK CfgDlgProc(HWND hWindow, UINT uMsg, WPARAM wParam, LPARAM lPara { if ((GetKeyState(VK_CONTROL) & 0x8000) == 0 && (GetKeyState(VK_SHIFT) & 0x8000) == 0) SalGeneral->OpenHtmlHelp(hWindow, HHCDisplayContext, IDD_CONFIGURATION, FALSE); - return TRUE; // never let F1 reach the parent + return TRUE; // never let F1 propagate to the parent } case WM_COMMAND: @@ -376,7 +376,7 @@ INT_PTR CALLBACK CfgDlgProc(HWND hWindow, UINT uMsg, WPARAM wParam, LPARAM lPara } } BOOL autoConnect = IsDlgButtonChecked(hWindow, IDC_CFG_AUTOCONNECT) == BST_CHECKED; - if (Data.AutoConnect != autoConnect) // meaning of NextOpenOrCheckTime changed: just open the dialog / open it with an automatic version check + if (Data.AutoConnect != autoConnect) // NextOpenOrCheckTime now means: open the dialog only / open it with an automatic version check { Data.AutoConnect = autoConnect; updateNextOpenOrCheckTime = TRUE; @@ -385,7 +385,7 @@ INT_PTR CALLBACK CfgDlgProc(HWND hWindow, UINT uMsg, WPARAM wParam, LPARAM lPara } if (updateNextOpenOrCheckTime) { - if (!autoConnect || LastCheckTime.wYear == 0) // no automatic check or we have not performed one yet + if (!autoConnect || LastCheckTime.wYear == 0) // this is not an automatic check, or we have not performed one yet ZeroMemory(&NextOpenOrCheckTime, sizeof(NextOpenOrCheckTime)); // opening the window and optionally performing a check on the first load-on-start (ASAP) else GetFutureTime(&NextOpenOrCheckTime, &LastCheckTime, GetWaitDays()); // base the next check on the date of the last check @@ -554,9 +554,9 @@ MENU_TEMPLATE_ITEM AppendToSystemMenu[] = { if (tvData->FirstLoadAfterInstall) { - // on the first load after installation (without loading a configuration, i.e. installation on a machine without Salamander) the window - // is shown after two seconds so that the user, if using a personal firewall, sees why - // Salamander is accessing the internet (without a firewall, checkver should finish faster and the user + // on the first load after installation (without loading a configuration, i.e. installation on a machine without Salamander), the window + // is shown after two seconds so that a user with a personal firewall can see why + // Salamander is trying to access the internet (without a firewall, checkver should finish faster, so the user // would not see the CheckVer window at all) if (!SetTimer(hWindow, 665, 2000, NULL)) ShowMinNA_IfNotShownYet(hWindow, TRUE, TRUE); // if the timer cannot be created, show the window immediately @@ -599,7 +599,7 @@ MENU_TEMPLATE_ITEM AppendToSystemMenu[] = { if ((GetKeyState(VK_CONTROL) & 0x8000) == 0 && (GetKeyState(VK_SHIFT) & 0x8000) == 0) SalGeneral->OpenHtmlHelp(hWindow, HHCDisplayContext, IDD_MAIN, FALSE); - return TRUE; // never let F1 reach the parent + return TRUE; // never let F1 propagate to the parent } case WM_SIZE: @@ -769,7 +769,7 @@ MENU_TEMPLATE_ITEM AppendToSystemMenu[] = if (MainDlgAutoOpen2 && IsTimeExpired(&NextOpenOrCheckTime) && Data.AutoCheckMode != achmNever) { - GetFutureTime(&NextOpenOrCheckTime, 1); // if opening the dialog and the check did not finish successfully (and therefore did not set NextOpenOrCheckTime), schedule another attempt for tomorrow + GetFutureTime(&NextOpenOrCheckTime, 1); // if opening the dialog and any subsequent check did not complete successfully (and therefore did not set NextOpenOrCheckTime), schedule the next attempt for tomorrow // TRACE_I("New on Close: NextOpenOrCheckTime: " << NextOpenOrCheckTime.wDay << "." << NextOpenOrCheckTime.wMonth << "." << NextOpenOrCheckTime.wYear); } @@ -803,7 +803,7 @@ MENU_TEMPLATE_ITEM AppendToSystemMenu[] = } else { - if (autoClose && ++ErrorsSinceLastCheck >= 4) // report only the fourth error (ignore the first three to bother the user as little as possible) + if (autoClose && ++ErrorsSinceLastCheck >= 4) // report only the fourth error (ignore the first three to minimize user disruption) { autoClose = FALSE; ErrorsSinceLastCheck = 0; diff --git a/src/plugins/checkver/internet.cpp b/src/plugins/checkver/internet.cpp index 4baff3a2c..2e5b0b876 100644 --- a/src/plugins/checkver/internet.cpp +++ b/src/plugins/checkver/internet.cpp @@ -124,7 +124,7 @@ DWORD WINAPI ThreadDownload(void* param) CTDData* data = (CTDData*)param; DWORD dialogID = data->MainDialogID; BOOL firstLoadAfterInstall = data->FirstLoadAfterInstall; - SetEvent(data->Continue); // let the main thread continue; from this point on the data are invalid (=NULL) + SetEvent(data->Continue); // let the main thread continue; from this point on, the data are no longer valid (=NULL) data = NULL; // lock the DLL to prevent it from being unloaded while this function runs @@ -204,8 +204,8 @@ DWORD WINAPI ThreadDownload(void* param) default: { - // p.s. adjusted to allow version checking behind a firewall (tested at SPS) - // HTTP (experimentally much faster than FTP-passive at SPS, probably due to HTTP caching, + // adjusted to allow version checking behind a firewall (tested at SPS) + // HTTP (experimentally much faster than FTP passive at SPS, probably due to HTTP caching; // usually passes through firewalls) char scriptURL[200]; _snprintf_s(scriptURL, _TRUNCATE, "%s?version=%s&lang=%s", @@ -270,7 +270,7 @@ DWORD WINAPI ThreadDownload(void* param) PostMessage(HMainDialog, WM_USER_DOWNLOADTHREAD_EXIT, !exit, 0); // thread ends; data are loaded FreeLibrary(hLock); // release the lock LeaveCriticalSection(&MainDialogIDSection); - return 0; // let the thread die naturally + return 0; // let the thread exit normally } else { @@ -301,7 +301,7 @@ StartDownloadThread(BOOL firstLoadAfterInstall) HANDLE hThread = CreateThread(NULL, 0, ThreadDownload, &data, 0, &threadID); if (hThread == NULL) TRACE_E("Unable to create Check Version Download thread."); - else // wait until the thread takes the data + else // wait until the thread picks up the data WaitForSingleObject(data.Continue, INFINITE); CloseHandle(data.Continue); diff --git a/src/plugins/dbviewer/csvlib/csvlib.cpp b/src/plugins/dbviewer/csvlib/csvlib.cpp index 5566aa52a..00e79ac86 100644 --- a/src/plugins/dbviewer/csvlib/csvlib.cpp +++ b/src/plugins/dbviewer/csvlib/csvlib.cpp @@ -21,7 +21,7 @@ #include "csvlib.h" // only an optimization detail -extern BOOL IsAlphaNumeric[256]; // TRUE/FALSE array for characters (FALSE = not a letter nor a digit) +extern BOOL IsAlphaNumeric[256]; // TRUE/FALSE array for characters (FALSE = not a letter or digit) extern BOOL IsAlpha[256]; #define SizeOf(x) (sizeof(x) / sizeof(x[0])) @@ -194,7 +194,7 @@ CCSVParser::CCSVParser(const char* filename, bIsBigEndian = BOM == 0xFFFE; } else - { // Detect UTF8 + { // Detect UTF-8 BYTE b[3]; fread(b, 1, 3, File); if (!memcmp(b, "\xEF\xBB\xBF", 3)) diff --git a/src/plugins/dbviewer/csvlib/csvlib.h b/src/plugins/dbviewer/csvlib/csvlib.h index 228ff0ae1..e3bfc692f 100644 --- a/src/plugins/dbviewer/csvlib/csvlib.h +++ b/src/plugins/dbviewer/csvlib/csvlib.h @@ -25,7 +25,7 @@ enum CCSVParserTextQualifier struct CCSVColumn { DWORD MaxLength; // maximum number of characters in the column - char* Name; // allocated column name or NULL if it does not exist + char* Name; // allocated column name, or NULL if the column has no name // temporary variables filled during FetchRecord DWORD First; DWORD Length; @@ -75,11 +75,11 @@ class CCSVParserCore : public CCSVParserBase virtual CCSVParserStatus FetchRecord(DWORD index) = 0; protected: - // if the column does not exist at columnIndex, add a new one with MaxLength = columnLen + // if the column at columnIndex does not exist yet, add a new one with MaxLength = columnLen // returns FALSE if the column could not be added to the array - // if the column already exists, extend columnLen only when it is larger than - // the current MaxLength value in that column - // returns TRUE if the addition/update of the column succeeded + // if the column already exists, set its MaxLength to columnLen only if it is greater than the + // current MaxLength value in that column + // returns TRUE if adding/updating the column succeeded BOOL SetLongerColumn(int columnIndex, DWORD columnLen); struct CLineRating diff --git a/src/plugins/dbviewer/data.h b/src/plugins/dbviewer/data.h index b1fe5779e..fdf886fb1 100644 --- a/src/plugins/dbviewer/data.h +++ b/src/plugins/dbviewer/data.h @@ -65,7 +65,7 @@ class CDatabase BOOL Open(const char* fileName); void Close(); - // return TRUE if the database is open and all variables are initialized + // returns TRUE if the database is open BOOL IsOpened() { return Parser != NULL; } // "", "dbf", "csv" diff --git a/src/plugins/dbviewer/dbflib/dbflib.cpp b/src/plugins/dbviewer/dbflib/dbflib.cpp index 5ec99ccf7..4686099b0 100644 --- a/src/plugins/dbviewer/dbflib/dbflib.cpp +++ b/src/plugins/dbviewer/dbflib/dbflib.cpp @@ -82,7 +82,7 @@ cDBF::cDBF(const char* filename, BOOL readOnly) : fields(NULL), status(DBFE_OK), break; /* Visual dBase Version 7 */ case 0x05: hdr.version = DBF_DBASE5; - break; /* Not tested. Does it exist? */ + break; /* Not tested; existence unconfirmed. */ case 0x83: hdr.version = DBF_DBASE3; break; /* III+ w/ memo */ @@ -226,8 +226,8 @@ cDBF::cDBF(const char* filename, BOOL readOnly) : fields(NULL), status(DBFE_OK), { hdr.memoFieldsCnt++; } - /* FoxPro files can contain character fields having upto 32KB - Then the high byte is stored where count of decimals is usually stored */ + /* FoxPro files can contain character fields up to 32 KB. + In that case, the high byte is stored where the decimal count is usually stored. */ if ((fld.type == DBF_FTYPE_CHAR) && (hdr.version == DBF_FOXPRO)) { fields[i].len += (U32)fld.decimal << 8; @@ -374,7 +374,7 @@ cDBF::cDBF(const char* filename, BOOL readOnly) : fields(NULL), status(DBFE_OK), { if (!tmp || (tmp == 0xE5 /*???dBase IV sample from Delphi???*/)) { /* dBase IV or V */ - /* On offset 20 there seems to be a block length; similar info might be on ofs 4 */ + /* At offset 20, there seems to be a block length; similar information might be at offset 4. */ fseek(fmemo, 20, SEEK_SET); if ((1 != fread(&memoBlockSize, 4, 1, fmemo)) || (memoBlockSize > 32768)) { @@ -571,15 +571,15 @@ eDBFStatus cDBF::GetMemoField(U32 pos, char* buffer, U32 bufSize, U32* dataSize) break; case DBF_DBASE3: - /* This weird old format never stores the actual size of memo items/ - We must read entire block and calculate the size. - The end of data is denoted b 1A 1A sequence */ + /* This old format never stores the actual size of memo items. + We must read the entire block and calculate the size. + The end of data is denoted by a 1A 1A sequence. */ { BOOL lookFor1a = FALSE; /* 1A 1A may be split into two blocks */ if (!buffer) { - /* Faking bufSize when enquiring needed buf size makes things simpler */ + /* Using a fake bufSize when querying the required buffer size simplifies things */ bufSize = 0x7FFFFFFF; } while (bufSize > 0) diff --git a/src/plugins/dbviewer/dbflib/dbflib.h b/src/plugins/dbviewer/dbflib/dbflib.h index 473bfeb42..e510b6608 100644 --- a/src/plugins/dbviewer/dbflib/dbflib.h +++ b/src/plugins/dbviewer/dbflib/dbflib.h @@ -153,14 +153,14 @@ typedef struct _dbf_header U32 recordsCnt; /* total number of records in file */ U32 fieldsCnt; /* number of fields per record, including memo fields */ U32 memoFieldsCnt; /* number of memo fields per record */ - U32 recordSize; /* total size of record as in master DBF file */ + U32 recordSize; /* total record size as in the master DBF file */ U32 headerSize; /* total size of file header */ U32 codePage; /* codepage of DBF_FLDTYPE_CHAR fields */ } DBF_HEADER, *DBF_HEADER_PTR; typedef struct _dbf_field { - U32 len; /* total len of field in bytes */ + U32 len; /* total field length in bytes */ U32 decimals; /* count of decimal digits */ U32 posInRecord; /* position of field in record */ U8 type; /* see DBF_FTYPE_XXX */ diff --git a/src/plugins/dbviewer/dbviewer.cpp b/src/plugins/dbviewer/dbviewer.cpp index f8f667469..a4408c824 100644 --- a/src/plugins/dbviewer/dbviewer.cpp +++ b/src/plugins/dbviewer/dbviewer.cpp @@ -16,7 +16,7 @@ const char* READABLE_EN_PLUGIN_NAME = "Database Viewer"; /* -TODO: enabler sketch; Salamander needs to implement the offset method (enablersOffset) +TODO: unfinished enablers; Salamander needs to implement the offset method (enablersOffset) also add a comment for this variable in SPL_GUI.H introduce it in DBVIEWER.CPP and DEMOPLUG.CPP, where enablers are global for windows from multiple threads -> conflict */ @@ -197,7 +197,7 @@ MENU_TEMPLATE_ITEM PopupMenuTemplate[] = struct CButtonData { - int ImageIndex; // zero base index + int ImageIndex; // zero-based index WORD ToolTipResID; // resource ID with the tooltip string WORD ID; // universal command CViewerWindowEnablerEnum Enabler; // control variable used to enable the button @@ -657,7 +657,7 @@ unsigned WINAPI ViewerThreadBody(void* param) window) != NULL) { CALL_STACK_MESSAGE1("ViewerThreadBody::ShowWindow"); - // NOTE! icons obtained without the LR_SHARED flag must be destroyed in WM_DESTROY + // NOTE: icons obtained without LR_SHARED must be destroyed in WM_DESTROY. SendMessage(window->HWindow, WM_SETICON, ICON_BIG, (LPARAM)LoadIcon(DLLInstance, MAKEINTRESOURCE(IDI_MAIN))); SendMessage(window->HWindow, WM_SETICON, ICON_SMALL, @@ -1220,9 +1220,9 @@ CViewerWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) HDWP hdwp = BeginDeferWindowPos(2); if (hdwp != NULL) { - // +4: when increasing the window width the last 4 pixels of the rebar were not redrawn - // in the rebar; even after hours I could not find the reason; it works in Salamander; - // for now this workaround will do; maybe I'll remember the problem later + // +4: when increasing the window width, the last 4 pixels of the rebar were not redrawn + // in the rebar; even after several hours I did not find the cause; it works in Salamander; + // using this workaround for now; the cause may become clear later hdwp = DeferWindowPos(hdwp, HRebar, NULL, 0, 0, r.right + 4, rebarHeight, SWP_NOACTIVATE | SWP_NOZORDER); @@ -1505,7 +1505,7 @@ CViewerWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) } if (ok) - { // we've got a new name + { // new name received if (!openedFileName || !*openedFileName || _stricmp(fileName, openedFileName)) { diff --git a/src/plugins/dbviewer/dbviewer.h b/src/plugins/dbviewer/dbviewer.h index 25216e6db..f451c7fbe 100644 --- a/src/plugins/dbviewer/dbviewer.h +++ b/src/plugins/dbviewer/dbviewer.h @@ -109,7 +109,7 @@ enum CViewerWindowEnablerEnum class CViewerWindow : public CWindow { public: - HANDLE Lock; // 'lock' object or NULL (goes to the signaled state once the file is closed) + HANDLE Lock; // 'lock' object or NULL (becomes signaled only after the file is closed) CRendererWindow Renderer; int ConversionsCount; // number of conversions retrieved including "Don't convert"; without separators CCSVConfig CfgCSV; @@ -124,7 +124,7 @@ class CViewerWindow : public CWindow HIMAGELIST HHotToolBarImageList; // toolbar and menu in a colored variant DWORD Enablers[vweCount]; - BOOL IsSrcFileSelected; // valid only if Enablers[vweSelSrcFile]==TRUE: TRUE/FALSE source file is selected/unselected + BOOL IsSrcFileSelected; // valid only if Enablers[vweSelSrcFile]==TRUE: TRUE/FALSE means the source file is selected/unselected public: CViewerWindow(int enumFilesSourceUID, int enumFilesCurrentIndex); diff --git a/src/plugins/dbviewer/dialogs.cpp b/src/plugins/dbviewer/dialogs.cpp index 0274951c6..4eb1832fc 100644 --- a/src/plugins/dbviewer/dialogs.cpp +++ b/src/plugins/dbviewer/dialogs.cpp @@ -815,9 +815,9 @@ void CFindDialog::Transfer(CTransferInfo& ti) FIND_HISTORY_SIZE, FindHistory); /* if (ti.Type == ttDataToWindow) - { // initialize the searched text according to the selection in the viewer (parent of this dialog) + { // initialize the search text from the selection in the viewer (the parent of this dialog) CWindowsObject *win = WindowsManager.GetWindowPtr(Parent); - if (win != NULL && win->Is(otViewerWindow)) // double-check that this is a viewer window + if (win != NULL && win->Is(otViewerWindow)) // make sure this is a viewer window { CViewerWindow *view = (CViewerWindow *)win; char buf[FIND_TEXT_LEN]; diff --git a/src/plugins/dbviewer/parser.cpp b/src/plugins/dbviewer/parser.cpp index a9433fa5e..c56d5480f 100644 --- a/src/plugins/dbviewer/parser.cpp +++ b/src/plugins/dbviewer/parser.cpp @@ -86,7 +86,7 @@ bool IsUTF8Encoded(const char* s, int cnt) } if (nUTF8 > 0) - { // At least one 2-or-more-bytes UTF8 sequence found and no invalid sequences found + { // At least one UTF-8 sequence of 2 or more bytes found and no invalid sequences found return true; } return false; @@ -95,10 +95,10 @@ bool IsUTF8Encoded(const char* s, int cnt) void CParserInterfaceAbstract::ShowParserError(HWND hParent, CParserStatusEnum status) { if (this != NULL) - { // this is NULL when called from CDatabase::Open when opening the file failed + { // this is NULL when called from CDatabase::Open if opening the file failed if (bShowingError) { - // Avoid recursive error showing on WM_PAINT + // Avoid recursive error display on WM_PAINT return; } bShowingError = true; @@ -496,7 +496,7 @@ char* Int64ToCurrency(char* buffer, __int64 number) else { DecimalSeparatorLen--; - DecimalSeparator[DecimalSeparatorLen] = 0; // ensure a zero terminator at the end + DecimalSeparator[DecimalSeparatorLen] = 0; // ensure a null terminator at the end } */ // other DBF values use '.' as the decimal separator, so we do not use the system one @@ -528,12 +528,12 @@ void TimeStampToDate(int jdays, int* pDay, int* pMon, int* pYear, BOOL bJulianDa } else { - // old code assuming it was number of Julian days (since 1.1.4713 BC) - // 1.1.1993 is claimed to be Julian Day 2448989 - // get the number of days since 1.1.1600 (jday == 1 means 1.1.1600) + // Old code assumed this was the number of Julian days (since 1.1.4713 BC). + // 1.1.1993 is claimed to be Julian Day 2448989. + // Get the number of days since 1.1.1600 (jday == 1 means 1.1.1600). if (jdays < 2448989 - 93 * 365 - 23 - 3 * 100 * 365 - 2 * 24 - 25) { - // Before 1.1. 1600. We do no support Julian calendar introduced AFAIR around 1584 + // Before 1.1.1600. The Julian calendar, introduced around 1584, is not supported. return; } // get the number of days since 1.1.1600 (jday == 1 means 1.1.1600 @@ -617,8 +617,8 @@ CParserInterfaceDBF::GetCellText(DWORD index, size_t* textLen) case DBF_FTYPE_INT: { - // Patera 2003.06.05: Why was there short int? - // FoxPro is supposed to use this type as 32bit int! + // Patera 2003.06.05: Why was this a short int? + // FoxPro is supposed to use this type as a 32-bit int sprintf(Buffer, "%d", *((int*)text)); *textLen = strlen(Buffer); return Buffer; @@ -627,9 +627,9 @@ CParserInterfaceDBF::GetCellText(DWORD index, size_t* textLen) case DBF_FTYPE_AUTOINC: case DBF_FTYPE_INT_V7: { // Used by Visual dBase 7: - // The DOC: left-most bit used for sign, 0 means negative - // Observation: Seems to be big-endian. - // Wow! Got it! Its for faster string-based comparison (for indexing)! + // The documentation says the leftmost bit is used for the sign; 0 means negative. + // Observation: seems to be big-endian. + // This is probably for faster string-based comparison (for indexing). UINT32 val = LongSwap(*(int*)text); sprintf(Buffer, "%u", val ? (val ^ 0x80000000) : 0); @@ -671,9 +671,9 @@ CParserInterfaceDBF::GetCellText(DWORD index, size_t* textLen) } case DBF_FTYPE_DTIME: - { // Visual FoxPro DateTime field: 8BYTE type: - // Lower 4 bytes: Julian day (since 1/1/4713 BC) - // Higher 4 bytes: time in miliseconds + { // Visual FoxPro DateTime field: 8-byte value: + // Lower 4 bytes: Julian day (since 1/1/4713 BC) + // Upper 4 bytes: time in milliseconds int day, mon, year, jd; int hour, min, sec; __int64 tmp64; @@ -702,7 +702,7 @@ CParserInterfaceDBF::GetCellText(DWORD index, size_t* textLen) case DBF_FTYPE_CHAR: { const void* zero = memchr(text, 0, field->len); - // ignore terminating binary zeros + // ignore trailing zero bytes *textLen = zero ? ((char*)zero - text) : field->len; return text; } @@ -713,8 +713,8 @@ CParserInterfaceDBF::GetCellText(DWORD index, size_t* textLen) __int64 tmp64; UINT32 tmp[2]; - // according to dBase doc, this type consists of two 32bits, number of days since 1/1/4713BC and miliseconds - // VCL takes it as double whose integer part is number of miliseconds since 1/1/1 + // According to the dBase documentation, this type consists of two 32-bit values: the number of days since 1/1/4713 BC and milliseconds. + // VCL treats it as a double whose integer part is the number of milliseconds since 1/1/1. // convert from big-endian to little-endian and again, as for long & autoinc, flip the sign tmp[1] = LongSwap(*(UINT32*)text); @@ -877,7 +877,7 @@ CParserInterfaceCSV::OpenFile(const char* fileName) { WORD w; fread(&w, 1, 2, f); - IsUnicode = (w == 0xFEFF) || (w == 0xFFFE); // UTFE16 LE & BE BOM's + IsUnicode = (w == 0xFEFF) || (w == 0xFFFE); // UTF-16 LE and BE BOMs // CP_UTF8 if (w == 0xBBEF) { @@ -925,7 +925,7 @@ CParserInterfaceCSV::OpenFile(const char* fileName) if (Csv->GetStatus() != CSVE_OK) { status = TranslateCSVStatus(Csv->GetStatus()); - CloseFile(); // po Close bude Csv=NULL + CloseFile(); // after Close Csv will be NULL } } else diff --git a/src/plugins/dbviewer/parser.h b/src/plugins/dbviewer/parser.h index 03cc9afb6..2c21674fb 100644 --- a/src/plugins/dbviewer/parser.h +++ b/src/plugins/dbviewer/parser.h @@ -26,7 +26,7 @@ bool IsUTF8Encoded(const char* s, int cnt); struct CFieldInfo { - char* Name; // if NULL, the required length is stored into NameMax + char* Name; // if Name is NULL, the required length is stored in NameMax int NameMax; // if Name != NULL, specifies the buffer size (NameMax equals the number of characters plus the terminator) BOOL LeftAlign; // where the text should be aligned when displayed int TextMax; // maximum number of characters shown in this column; -1 if unknown to the parser diff --git a/src/plugins/dbviewer/renderer.h b/src/plugins/dbviewer/renderer.h index 591199c97..8e8463a10 100644 --- a/src/plugins/dbviewer/renderer.h +++ b/src/plugins/dbviewer/renderer.h @@ -96,7 +96,7 @@ class CSelection return FocusX == AnchorX && FocusY == AnchorY; } - // return TRUE if cell [x,y] had a different state in oldSelection + // return TRUE if cell [x,y] had a different state in the old selection BOOL Changed(const CSelection* old, int x, int y) { // if the selection state changed @@ -233,7 +233,7 @@ class CRendererWindow : public CWindow char DefaultCoding[210]; BOOL UseCodeTable; // should the CodeTable be used for recoding? // CodeTable matters only when UseCodeTable is TRUE - char CodeTable[256]; // translation table + char CodeTable[256]; // encoding table protected: int EnumFilesSourceUID; // source UID for enumerating viewer files @@ -301,17 +301,17 @@ class CRendererWindow : public CWindow BOOL HitTest(int x, int y, int* column, int* row, BOOL getNearest); BOOL HitTestRow(int y, int* row, BOOL getNearest); BOOL HitTestColumn(int x, int* column, BOOL getNearest); - // return TRUE if x is approximately above a divider between columns - // column and offset can be NULL + // returns TRUE if x is approximately over a column divider + // column and offset may be NULL BOOL HitTestColumnSplit(int x, int* column, int* offset); // start editing the cell under the focus // void OnEditCell(); - // find the column with the visibleIndex; if found, - // set index according to its position in Database.Column and xPos to - // its X coordinate and return TRUE; - // otherwise return FALSE + // finds the column with index visibleIndex and, if found, + // sets index to its position in Database.Column and xPos to + // its X coordinate, then returns TRUE + // otherwise returns FALSE BOOL GetColumnInfo(int visibleIndex, int* index, int* xPos); // enable/disable the timer and state variables during block dragging @@ -330,7 +330,7 @@ class CRendererWindow : public CWindow // prepare the buffer and let Salamander detect the code page void RecognizeCodePage(); - // convert characters in the text buffer + // converts characters in the text buffer void CodeCharacters(char* text, size_t textLen); void SetViewerTitle(); diff --git a/src/plugins/dbviewer/renmain.cpp b/src/plugins/dbviewer/renmain.cpp index 3cb8bf30b..1514af534 100644 --- a/src/plugins/dbviewer/renmain.cpp +++ b/src/plugins/dbviewer/renmain.cpp @@ -16,7 +16,7 @@ #define TIMER_SCROLL_ID 1 -BOOL IsAlphaNumeric[256]; // TRUE/FALSE table for characters (FALSE = neither a letter nor a digit) +BOOL IsAlphaNumeric[256]; // TRUE/FALSE array for characters (FALSE = not a letter or digit) BOOL IsAlpha[256]; //**************************************************************************** @@ -514,7 +514,7 @@ void CRendererWindow::Find(BOOL forward, BOOL wholeWords, { const CDatabaseColumn* column = Database.GetVisibleColumn(col); - // too narrow columns are not searched in non-regexp mode + // columns that are too narrow are not searched in non-regexp mode // other possible optimizations: do not search DBF_FTYPE_INT_V7, // DBF_FTYPE_TSTAMP, DBF_FTYPE_AUTOINC & DBF_FTYPE_DOUBLE columns if // the search pattern contains non-numeric characters @@ -541,7 +541,7 @@ void CRendererWindow::Find(BOOL forward, BOOL wholeWords, LPCWSTR textW = Database.GetCellTextW(column, &textLen); textLen = WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, textW, (int)textLen, buf, bufSize, NULL, NULL); if (textLen < 0) - textLen = 0; // Error - swallow it ;-) + textLen = 0; // ignore the error text = buf; } do @@ -580,7 +580,7 @@ void CRendererWindow::Find(BOOL forward, BOOL wholeWords, } return; } - } // of if (!bmSearchData || (column->Length >= patLen)) + } // end of if (!bmSearchData || (column->Length >= patLen)) } if (forward) @@ -949,7 +949,7 @@ BOOL CRendererWindow::HitTestColumnSplit(int x, int* column, int* offset) { if (i > 0 && x >= colX - 3 && x <= colX) { - // if this is not the left edge of the first column and the point overlaps a divider, we found it + // if this is not the left edge of the first column and the point is within a divider range, we found it if (column != NULL) *column = i - 1; if (offset != NULL) @@ -1495,7 +1495,7 @@ CRendererWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) return 0; } - if (uMsg == WM_MOUSEHWHEEL) // horizontall scroll, supported from Windows Vista + if (uMsg == WM_MOUSEHWHEEL) // horizontal scroll, supported from Windows Vista { short zDelta = (short)HIWORD(wParam); if ((zDelta < 0 && MouseHWheelAccumulator > 0) || (zDelta > 0 && MouseHWheelAccumulator < 0)) @@ -1844,7 +1844,7 @@ CRendererWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (xPos >= RowHeight && yPos >= RowHeight) { - // select pres bunky + // selection across cells int x, y; if (HitTest(xPos, yPos, &x, &y, FALSE)) { @@ -1869,7 +1869,7 @@ CRendererWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (xPos >= RowHeight && yPos >= RowHeight) { - // select pres bunky + // selection across cells int x, y; if (HitTest(xPos, yPos, &x, &y, FALSE)) { diff --git a/src/plugins/demoplug/archiver.cpp b/src/plugins/demoplug/archiver.cpp index 0ca72ef9f..58af6c59c 100644 --- a/src/plugins/demoplug/archiver.cpp +++ b/src/plugins/demoplug/archiver.cpp @@ -456,7 +456,7 @@ CPluginInterfaceForArchiver::PackToArchive(CSalamanderForOperationsAbstract* sal while ((name = next(SalamanderGeneral->GetMsgBoxParent(), 3, &dosName, &isDir, &size, &attr, &lastWrite, nextParam, &errorOccured)) != NULL) { - if (errorOccured == SALENUM_ERROR) // SALENUM_CANCEL cannot appear here + if (errorOccured == SALENUM_ERROR) // SALENUM_CANCEL cannot occur here TRACE_I("Not all files and directories from disk will be packed."); totalSize += size; @@ -623,7 +623,7 @@ CPluginInterfaceForArchiver::UnpackWholeArchive(CSalamanderForOperationsAbstract BOOL ret = FALSE; if (delArchiveWhenDone) - archiveVolumes->Add(fileName, -2); // FIXME: once the plugin learns multi-volume archives we must add all archive volumes here (to delete the entire archive) + archiveVolumes->Add(fileName, -2); // FIXME: once the plugin supports multi-volume archives, we must add all archive volumes here (to delete the entire archive) salamander->OpenProgressDialog("Unpacking DemoPlug Archive", FALSE, NULL, FALSE); salamander->ProgressSetTotalSize(CQuadWord(100, 0), CQuadWord(-1, -1)); @@ -797,9 +797,9 @@ CPluginInterfaceForArchiver::DeleteTmpCopy(const char* fileName, BOOL firstFile) CALL_STACK_MESSAGE3("CPluginInterfaceForArchiver::DeleteTmpCopy(%s, %d)", fileName, firstFile); /* - // message box test (message boxes should be used only in an extreme situation) - it makes a mess + // message box test (use message boxes only in extreme situations) - it causes problems // if another plugin has its own modal dialog open (cosmetic issue: the message box for this dialog is not modal - // and after closing it activates the dialog's parent) + // and activates the dialog's parent after it is closed) char buf[500]; sprintf(buf, "File \"%s\" will be deleted.", fileName); SalamanderGeneral->SalMessageBox(SalamanderGeneral->GetMsgBoxParent(), @@ -807,8 +807,8 @@ CPluginInterfaceForArchiver::DeleteTmpCopy(const char* fileName, BOOL firstFile) MB_OK | MB_ICONINFORMATION); */ - // if this is a critical shutdown it is not a good time for slow file deletion (our process will be killed soon), - // at the first subsequent plugin start in the first Salamander instance this will be deleted "calmly", + // if this is a critical shutdown, it is not a good time for slow file deletion (our process will be killed soon), + // at the first subsequent plugin start in the first Salamander instance, this will be deleted normally, // we probably cannot come up with anything better if (SalamanderGeneral->IsCriticalShutdown()) return; @@ -849,8 +849,8 @@ CPluginInterfaceForArchiver::PrematureDeleteTmpCopy(HWND parent, int copiesCount { CALL_STACK_MESSAGE2("CPluginInterfaceForArchiver::PrematureDeleteTmpCopy(, %d)", copiesCount); - // if this is a critical shutdown it is not a good time for slow file deletion (our process will be killed soon), - // at the first subsequent plugin start in the first Salamander instance this will be deleted "calmly", + // if this is a critical shutdown, it is not a good time for slow file deletion (our process will be killed soon), + // at the first subsequent plugin start in the first Salamander instance, this will be deleted normally, // we probably cannot come up with anything better if (SalamanderGeneral->IsCriticalShutdown()) return FALSE; // during a critical shutdown we do not ask any questions diff --git a/src/plugins/demoplug/demoplug.cpp b/src/plugins/demoplug/demoplug.cpp index ade705a40..5dfb55f96 100644 --- a/src/plugins/demoplug/demoplug.cpp +++ b/src/plugins/demoplug/demoplug.cpp @@ -153,7 +153,7 @@ void InitIconOverlays() // in reality large icons have been supported for a long time and can be enabled via // Desktop/Properties/???/Large Icons; note that there will be no system image list // for 32x32 icons in that case, and we should fetch the actual icon sizes from the system - // for now we ignore it and enable 48x48 only from XP where they are normally available + // for now we ignore this and enable 48x48 only from XP, where they are normally available int iconSizes[3] = {16, 32, 48}; if (!SalIsWindowsVersionOrGreater(5, 1, 0)) // not WindowsXPAndLater: not XP or later iconSizes[2] = 32; diff --git a/src/plugins/demoplug/demoplug.h b/src/plugins/demoplug/demoplug.h index b7e229e66..cacd939cd 100644 --- a/src/plugins/demoplug/demoplug.h +++ b/src/plugins/demoplug/demoplug.h @@ -330,7 +330,7 @@ class CViewerWindow : public CWindow DWORD Enablers[vweCount]; - HWND HRebar; // holds the menu bar and toolbar + HWND HRebar; // holds MenuBar and ToolBar CGUIMenuPopupAbstract* MainMenu; CGUIMenuBarAbstract* MenuBar; CGUIToolBarAbstract* ToolBar; @@ -420,7 +420,7 @@ class CDeleteProgressDlg : public CCommonDialog void Set(const char* fileName, DWORD progress, BOOL dalayedPaint); - // empties the message queue (call often enough) and allows repainting, handling Cancel, ... + // empties the message queue (call often enough), allows repainting, and handles Cancel presses // returns TRUE if the user wants to interrupt the operation BOOL GetWantCancel(); diff --git a/src/plugins/demoplug/dialogs.cpp b/src/plugins/demoplug/dialogs.cpp index 07ad76429..b241aeb04 100644 --- a/src/plugins/demoplug/dialogs.cpp +++ b/src/plugins/demoplug/dialogs.cpp @@ -39,7 +39,7 @@ CCommonDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) // horizontally and vertically center the dialog relative to the parent if (Parent != NULL) SalamanderGeneral->MultiMonCenterWindow(HWindow, Parent, TRUE); - break; // ask DefDlgProc to handle focus + break; // let DefDlgProc handle focus } } return CDialog::DialogProc(uMsg, wParam, lParam); @@ -264,7 +264,7 @@ CPathDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) CDialog::DialogProc(uMsg, wParam, lParam); return FALSE; */ - break; // ask DefDlgProc to handle focus + break; // let DefDlgProc handle focus } } return CCommonDialog::DialogProc(uMsg, wParam, lParam); @@ -382,7 +382,7 @@ BOOL CCtrlExampleDialog::CreateChilds() CGUIHyperLinkAbstract* hl; - // A hyperlink can be reached in the dialog via the keyboard if the .RC assigns it the WS_TABSTOP style. + // A HyperLink can be reached in the dialog via the keyboard if the .RC assigns it the WS_TABSTOP style. hl = SalamanderGUI->AttachHyperLink(HWindow, IDC_CE_HLOPEN, STF_UNDERLINE | STF_HYPERLINK_COLOR); if (hl == NULL) return FALSE; diff --git a/src/plugins/demoplug/fs1.cpp b/src/plugins/demoplug/fs1.cpp index 5698e1e31..67d8c1f35 100644 --- a/src/plugins/demoplug/fs1.cpp +++ b/src/plugins/demoplug/fs1.cpp @@ -471,9 +471,9 @@ void CTopIndexMem::Push(const char* path, int topIndex) ok = s - path == l && SalamanderGeneral->StrNICmp(path, Path, l) == 0; } - if (ok) // it follows -> remember the next top index + if (ok) // path follows -> remember the next top index { - if (TopIndexesCount == TOP_INDEX_MEM_SIZE) // need to remove the first top index from memory + if (TopIndexesCount == TOP_INDEX_MEM_SIZE) // discard the first stored top index { int i; for (i = 0; i < TOP_INDEX_MEM_SIZE - 1; i++) @@ -515,13 +515,13 @@ BOOL CTopIndexMem::FindAndPop(const char* path, int& topIndex) topIndex = TopIndexes[--TopIndexesCount]; return TRUE; } - else // we no longer have this value (it was not stored or low memory discarded it) + else // we no longer have this value (it was not stored or was discarded due to low memory) { Clear(); return FALSE; } } - else // request for another path -> clear the memory, a long jump occurred + else // request for a different path -> clear memory; a long jump occurred { Clear(); return FALSE; diff --git a/src/plugins/demoplug/fs2.cpp b/src/plugins/demoplug/fs2.cpp index 7bd06efb5..e9cc165b9 100644 --- a/src/plugins/demoplug/fs2.cpp +++ b/src/plugins/demoplug/fs2.cpp @@ -71,7 +71,7 @@ void CDeleteProgressDlg::EnableCancel(BOOL enable) BOOL CDeleteProgressDlg::GetWantCancel() { MSG msg; - while (PeekMessage(&msg, NULL, 0, 0, TRUE)) // give the user a brief timeslice ... + while (PeekMessage(&msg, NULL, 0, 0, TRUE)) // give the user a brief moment ... { if (!IsWindow(HWindow) || !IsDialogMessage(HWindow, &msg)) { @@ -291,7 +291,7 @@ CPluginFSInterface::ChangePath(int currentFSNameIndex, char* fsName, int fsNameI if (FatalError) { FatalError = FALSE; - return FALSE; // ListCurrentPath failed because of low memory, fatal error + return FALSE; // ListCurrentPath failed due to low memory; fatal error } char errBuf[MAX_PATH]; @@ -315,7 +315,7 @@ CPluginFSInterface::ChangePath(int currentFSNameIndex, char* fsName, int fsNameI { // try to shorten the path PathError = FALSE; if (!SalamanderGeneral->CutDirectory(path, NULL)) - return FALSE; // nothing left to shorten, fatal error + return FALSE; // the path cannot be shortened further; fatal error fileNameAlreadyCut = TRUE; if (pathWasCut != NULL) *pathWasCut = TRUE; @@ -332,7 +332,7 @@ CPluginFSInterface::ChangePath(int currentFSNameIndex, char* fsName, int fsNameI } #endif // DEMOPLUG_QUIET - if (attr != 0xFFFFFFFF && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0) // success, pick the path as current + if (attr != 0xFFFFFFFF && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0) // success, use the path as current { if (errBuf[0] != 0) // if we have a message from shortening, display it now { @@ -341,7 +341,7 @@ CPluginFSInterface::ChangePath(int currentFSNameIndex, char* fsName, int fsNameI } strcpy(Path, path); - // timer test only (useful for keep-connection-alive for example) + // timer test only (useful, for example, for keeping the connection alive) // SalamanderGeneral->KillPluginFSTimer(this, TRUE, 0); // clear existing timers for this FS first // SalamanderGeneral->AddPluginFSTimer(2000, this, 1234); @@ -502,7 +502,7 @@ CPluginFSInterface::ListCurrentPath(CSalamanderDirectoryAbstract* dir, file.LastWrite = data.ftLastWriteTime; file.Hidden = file.Attr & FILE_ATTRIBUTE_HIDDEN ? 1 : 0; // always set IconOverlayIndex; Salamander will ignore it if it doesn't apply - // read-only = slow file overlay, system = shared overlay + // read-only = slow file icon overlay, system = shared icon overlay file.IconOverlayIndex = file.Attr & FILE_ATTRIBUTE_READONLY ? 1 : file.Attr & FILE_ATTRIBUTE_SYSTEM ? 0 : ICONOVERLAYINDEX_NOTUSED; @@ -1026,7 +1026,7 @@ CPluginFSInterface::CreateDir(const char* fsName, int mode, HWND parent, char* n { cancel = FALSE; if (mode == 1) - return FALSE; // request for the standard dialog + return FALSE; // request the standard dialog #ifndef DEMOPLUG_QUIET char bufText[2 * MAX_PATH + 100]; @@ -1566,14 +1566,14 @@ BOOL DFS_IsValidPath(const char* path, CDFSPathError* err) *err = dfspeShareNameMissing; } else - return TRUE; // cesta OK + return TRUE; // path OK } } else // path specified via a drive (c:\...) { if (LowerCase[*s] >= 'a' && LowerCase[*s] <= 'z' && *(s + 1) == ':' && *(s + 2) == '\\') // "c:\..." { - return TRUE; // cesta OK + return TRUE; // path OK } else { @@ -1653,13 +1653,13 @@ CPluginFSInterface::CopyOrMoveFromFS(BOOL copy, int mode, const char* fsName, HW SalamanderGeneral->SetUserWorkedOnPanelPath(PANEL_TARGET); // default action = work with the target panel path } - return FALSE; // request for the standard dialog + return FALSE; // request the standard dialog } if (mode == 4) // error in the standard Salamander processing of the destination path { // 'targetPath' contains an invalid path; the user was notified, just let them edit it - return FALSE; // request for the standard dialog + return FALSE; // request the standard dialog } const char* title = copy ? "DFS Copy" : "DFS Move"; @@ -1688,7 +1688,7 @@ CPluginFSInterface::CopyOrMoveFromFS(BOOL copy, int mode, const char* fsName, HW if (mode == 2) // the user entered a path in the standard dialog { // resolve relative paths ourselves (Salamander cannot do that) - if ((targetPath[0] != '\\' || targetPath[1] != '\\') && // not an UNC path + if ((targetPath[0] != '\\' || targetPath[1] != '\\') && // not a UNC path (targetPath[0] == 0 || targetPath[1] != ':')) // not a standard drive path { // so it is neither Windows nor archive syntax userPart = strchr(targetPath, ':'); @@ -1720,7 +1720,7 @@ CPluginFSInterface::CopyOrMoveFromFS(BOOL copy, int mode, const char* fsName, HW userPart = s; BOOL tooLong = FALSE; int rootLen = SalamanderGeneral->GetRootPath(s, Path); - if (targetPath[0] == '\\') // "\\path" -> build root + newName + if (targetPath[0] == '\\') // "\\path" -> concatenate root + newName { s += rootLen; int len = (int)strlen(targetPath + 1); // skip the leading '\\' @@ -1732,7 +1732,7 @@ CPluginFSInterface::CopyOrMoveFromFS(BOOL copy, int mode, const char* fsName, HW *(s + len) = 0; } } - else // "path" -> combine Path + newName + else // "path" -> concatenate Path + newName { int pathLen = (int)strlen(Path); if (pathLen < rootLen) @@ -1834,7 +1834,7 @@ CPluginFSInterface::CopyOrMoveFromFS(BOOL copy, int mode, const char* fsName, HW { char* end2 = end; BOOL cut = FALSE; - while (*--end2 != '\\') // at least one backslash must follow after the root + while (*--end2 != '\\') // at least one backslash is guaranteed after the root { if (*end2 == '*' || *end2 == '?') cut = TRUE; @@ -1847,7 +1847,7 @@ CPluginFSInterface::CopyOrMoveFromFS(BOOL copy, int mode, const char* fsName, HW } } - while (end > afterRoot) // there is still more than the root + while (end > afterRoot) // there is more than the root { DWORD attrs = SalamanderGeneral->SalGetFileAttributes(userPart); if (attrs != 0xFFFFFFFF) // this part of the path exists @@ -1982,7 +1982,7 @@ CPluginFSInterface::CopyOrMoveFromFS(BOOL copy, int mode, const char* fsName, HW if (pathError) { // return 'targetPath' after adjustment (expansion of the path and possible tweaks to ".." and ".") - return FALSE; // error -> re-open the standard dialog + return FALSE; // error -> show the standard dialog again } } } @@ -2094,13 +2094,13 @@ CPluginFSInterface::CopyOrMoveFromFS(BOOL copy, int mode, const char* fsName, HW opMask++; } - /* // description of the operation destination gathered in the previous code: + /* // description of the operation target obtained by the preceding code: if (diskPath) // 'targetPath' is a Windows path, 'opMask' is the operation mask { } - else // 'targetPath' is a path on this FS ('userPart' points to the FS user-part path), 'opMask' is the operation mask + else // 'targetPath' is a path on this FS ('userPart' points to the user part of the FS path), 'opMask' is the operation mask { - // if 'rename' is TRUE we are renaming/copying a directory into itself + // if 'rename' is TRUE, this is renaming/copying a directory into itself } */ @@ -2204,7 +2204,7 @@ CPluginFSInterface::CopyOrMoveFromFS(BOOL copy, int mode, const char* fsName, HW if (!fileFromCache) // the file is not in the disk cache { // copy the file directly from DFS - // the demo plug-in does not handle overwriting files; real code should confirm overwrites here + // the demo plugin does not handle overwriting files; real code should confirm overwrites here // (the ConfirmOnFileOverwrite and ConfirmOnSystemHiddenFileOverwrite flags apply) while (1) { @@ -2475,7 +2475,7 @@ CPluginFSInterface::CopyOrMoveFromDiskToFS(BOOL copy, int mode, const char* fsNa { // 'targetPath' contains the raw path entered by the user (all we know is that it // belongs to this FS, otherwise Salamander would not call this method) - char* userPart = strchr(targetPath, ':') + 1; // v 'targetPath' musi byt fs-name + ':' + char* userPart = strchr(targetPath, ':') + 1; // 'targetPath' must contain fs-name + ':' CDFSPathError err; BOOL invPath = !DFS_IsValidPath(userPart, &err); @@ -2795,7 +2795,7 @@ CPluginFSInterface::CopyOrMoveFromDiskToFS(BOOL copy, int mode, const char* fsNa break; } - if (success && !copy && !skip) // we are doing a move and the file was not skipped -> delete the source file + if (success && !copy && !skip) // this is a move and the file was not skipped -> delete the source file { // remove the file from disk while (1) diff --git a/src/plugins/demoplug/help/hh/salamander_help_shared.css b/src/plugins/demoplug/help/hh/salamander_help_shared.css index a0f833192..f259c75cd 100644 --- a/src/plugins/demoplug/help/hh/salamander_help_shared.css +++ b/src/plugins/demoplug/help/hh/salamander_help_shared.css @@ -1,3 +1,4 @@ +/* CommentsTranslationProject: TRANSLATED */ /* Cascading Style Sheet for Open Salamander Help */ /* Shared part used for both CHM and WEB */ @@ -206,14 +207,14 @@ #help_page td.hdr { - /* tmavsi seda na leve strane */ + /* darker gray on the left side */ margin: .25em; background: #dddddd; vertical-align: top; padding: 2px 4px; font-weight: bold; - width: 10%; /* zuzime levou stranu tabulky na minimum */ - padding-right :10px; /* ale nechame tam alespon 10 bodu, at to trochu vypada */ + width: 10%; /* narrow the left side of the table to the minimum */ + padding-right :10px; /* but keep at least 10 points there so it still looks decent */ white-space: nowrap; } @@ -322,4 +323,3 @@ padding-left: 4px; text-align: left; } - diff --git a/src/plugins/demoplug/menu.cpp b/src/plugins/demoplug/menu.cpp index 1491f6634..b32947985 100644 --- a/src/plugins/demoplug/menu.cpp +++ b/src/plugins/demoplug/menu.cpp @@ -111,7 +111,7 @@ void WINAPI DEMOPLUGOperationFromDisk(const char* sourcePath, SalEnumSelection2 while ((name = next(data->Parent, 3, &dosName, &isDir, &size, &attr, &lastWrite, nextParam, &errorOccured)) != NULL) { - if (errorOccured == SALENUM_ERROR) // SALENUM_CANCEL cannot arrive here + if (errorOccured == SALENUM_ERROR) // SALENUM_CANCEL cannot occur here data->Success = FALSE; if (!isDir) totalSize += size; @@ -493,7 +493,7 @@ CPluginInterfaceForMenuExt::ExecuteMenuItem(CSalamanderForOperationsAbstract* sa { break; } - else UpdateWindow(waitWndParent); // avoid staring at leftover message box contents + else UpdateWindow(waitWndParent); // redraw the parent window to remove message box remnants SalamanderGeneral->ShowSafeWaitWindow(TRUE); } } @@ -501,7 +501,7 @@ CPluginInterfaceForMenuExt::ExecuteMenuItem(CSalamanderForOperationsAbstract* sa */ /* - // password mananger + // password manager CSalamanderPasswordManagerAbstract *passwordManager = NULL; passwordManager = SalamanderGeneral->GetSalamanderPasswordManager(); if (passwordManager != NULL) @@ -530,11 +530,11 @@ CPluginInterfaceForMenuExt::ExecuteMenuItem(CSalamanderForOperationsAbstract* sa if (passwordManager->DecryptPassword(encryptedPassword, encryptedPasswordSize, &decryptedPassword)) { TRACE_I("Decrypted password: " << decryptedPassword); - memset(decryptedPassword, 0, lstrlen(decryptedPassword)); // clear memory with plain password + memset(decryptedPassword, 0, lstrlen(decryptedPassword)); // clear the memory containing the plain text password SalamanderGeneral->Free(decryptedPassword); } - if (!encrypt) memset(encryptedPassword, 0, encryptedPasswordSize); // clear memory with scrambled password + if (!encrypt) memset(encryptedPassword, 0, encryptedPasswordSize); // clear the memory containing the scrambled password SalamanderGeneral->Free(encryptedPassword); } } @@ -759,7 +759,7 @@ CPluginInterfaceForMenuExt::ExecuteMenuItem(CSalamanderForOperationsAbstract* sa { if (!filePath) { - // error - expected a file path, not a directory + // error - expected a directory path, but found a file SalamanderGeneral->SalMessageBox(parent, "Unable to create the path specified, name has already been used for a file.", "Path Error", MB_OK | MB_ICONEXCLAMATION); continue; // ask again diff --git a/src/plugins/demoplug/thumbldr.cpp b/src/plugins/demoplug/thumbldr.cpp index 8b777dffe..eb03d7c94 100644 --- a/src/plugins/demoplug/thumbldr.cpp +++ b/src/plugins/demoplug/thumbldr.cpp @@ -16,11 +16,11 @@ // **************************************************************************** // opens the specified file and converts it into a sequence of DWORDs -// that means 24 bits for color (R, G, B) and 8 bits of padding +// i.e. 24 bits for color (R, G, B) and 8 unused bits // the size of a single row in bytes is: image_width * sizeof(DWORD) /* -// simple variant built on LoadImage, which blocks the rest of the OS -// and the loading process cannot be interrupted +// simple variant based on LoadImage, which blocks the rest of the system +// and does not allow the loading process to be interrupted CPluginInterfaceForThumbLoader::LoadThumbnail(const char *filename, int thumbWidth, int thumbHeight, CSalamanderThumbnailMakerAbstract *thumbMaker, BOOL fastThumbnail) @@ -29,18 +29,18 @@ CPluginInterfaceForThumbLoader::LoadThumbnail(const char *filename, int thumbWid IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE)); if (hSrcBitmap != NULL) { - // get the width and height of the image + // get the image width and height BITMAP srcBitmap; if (GetObject(hSrcBitmap, sizeof(BITMAP), &srcBitmap) != 0) { - // create a copy in which every pixel is represented as COLORREF + // create a copy in which each pixel is represented as COLORREF BITMAPINFO tmpBI; memset(&tmpBI, NULL, sizeof(BITMAPINFO)); tmpBI.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); tmpBI.bmiHeader.biWidth = srcBitmap.bmWidth; tmpBI.bmiHeader.biHeight = -srcBitmap.bmHeight; // send a top-down bitmap to Salamander tmpBI.bmiHeader.biPlanes = 1; - tmpBI.bmiHeader.biBitCount = 32; // R, G, B, one byte of padding + tmpBI.bmiHeader.biBitCount = 32; // R, G, B, one unused byte void* ptr; HBITMAP hTmpBitmap = HANDLES(CreateDIBSection(NULL, &tmpBI, DIB_RGB_COLORS, &ptr, NULL, NULL)); @@ -48,7 +48,7 @@ CPluginInterfaceForThumbLoader::LoadThumbnail(const char *filename, int thumbWid if (hTmpBitmap != NULL && tmpBitmapBits != NULL) { - // if the bitmap was allocated, convert it into our format + // if the bitmap was allocated successfully, convert it to the required format HDC hDC = HANDLES(GetDC(NULL)); HDC hSrcDC = HANDLES(CreateCompatibleDC(hDC)); @@ -64,9 +64,9 @@ CPluginInterfaceForThumbLoader::LoadThumbnail(const char *filename, int thumbWid HANDLES(DeleteDC(hTmpDC)); HANDLES(ReleaseDC(NULL, hDC)); - GdiFlush(); // we are going to work with raw data, ensure GDI operations are flushed + GdiFlush(); // flush pending GDI operations before working with raw data - // hand the image to Salamander for downscaling + // pass the image to Salamander for downscaling thumbMaker->SetParameters(srcBitmap.bmWidth, srcBitmap.bmHeight, 0); // int i = 0; // while (i < srcBitmap.bmHeight) @@ -82,7 +82,7 @@ CPluginInterfaceForThumbLoader::LoadThumbnail(const char *filename, int thumbWid thumbMaker->SetError(); // probably not enough memory; the file gets a simple icon } else - thumbMaker->SetError(); // it's a bitmap, but probably corrupted; the file gets a simple icon + thumbMaker->SetError(); // it is a bitmap, but it is probably corrupted; the file gets a simple icon HANDLES(DeleteObject(hSrcBitmap)); } @@ -106,7 +106,7 @@ DWORD GetClrUsed(const BITMAPINFOHEADER* bih, BOOL max) case 8: return 256; default: - return 0; // A 24 or 32 bitcount DIB has no color table + return 0; // A 24- or 32-bit DIB has no color table } } @@ -271,7 +271,7 @@ CPluginInterfaceForThumbLoader::LoadThumbnail(const char* filename, processTopDown = TRUE; height *= -1; } - // pass picture format to Open Salamander + // pass image parameters to Open Salamander if (thumbMaker->SetParameters(width, height, processTopDown ? 0 : SSTHUMB_MIRROR_VERT)) { LOGPALETTE* palette = NULL; diff --git a/src/plugins/demoplug/viewer.cpp b/src/plugins/demoplug/viewer.cpp index 5dabcc051..6f42c5ffa 100644 --- a/src/plugins/demoplug/viewer.cpp +++ b/src/plugins/demoplug/viewer.cpp @@ -72,7 +72,7 @@ MENU_TEMPLATE_ITEM PopupMenuTemplate[] = struct CButtonData { - int ImageIndex; // zero base index + int ImageIndex; // zero-based index WORD ToolTipResID; // resource ID containing the tooltip string WORD ID; // generic command ID CViewerWindowEnablerEnum Enabler; // control variable that enables the button @@ -116,7 +116,7 @@ void ReleaseViewer() ViewerAccels = NULL; } -/* // viewer thread start variant without using the CThread object +/* // variant of starting the viewer thread without using the CThread object struct CTVData { BOOL AlwaysOnTop; @@ -136,7 +136,7 @@ unsigned WINAPI ViewerThreadBody(void *param) SetThreadNameInVCAndTrace("DOP Viewer"); TRACE_I("Begin"); - // sample application crash + // application crash example // int *p = 0; // *p = 0; // ACCESS VIOLATION ! @@ -156,8 +156,8 @@ unsigned WINAPI ViewerThreadBody(void *param) if (CfgSavePosition && CfgWindowPlacement.length != 0) { WINDOWPLACEMENT place = CfgWindowPlacement; - // GetWindowPlacement respects the taskbar so if it sits at the top or left, - // the coordinates are offset by its size; correct them. + // GetWindowPlacement takes the taskbar into account, so if the taskbar is at the top or left, + // the coordinates are offset by its size. Correct them. RECT monitorRect; RECT workRect; SalamanderGeneral->MultiMonGetClipRectByRect(&place.rcNormalPosition, &workRect, &monitorRect); @@ -171,7 +171,7 @@ unsigned WINAPI ViewerThreadBody(void *param) data->ShowCmd = place.showCmd; } - // NOTE: on an existing window/dialog the top-most state is easy to apply: + // NOTE: on an existing window/dialog, making it topmost is easy: // SetWindowPos(HWindow, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); if (window->CreateEx(data->AlwaysOnTop ? WS_EX_TOPMOST : 0, @@ -204,7 +204,7 @@ unsigned WINAPI ViewerThreadBody(void *param) char name[MAX_PATH]; strcpy(name, data->Name); BOOL openFile = data->Success; - SetEvent(data->Continue); // wake the main thread; the data are no longer valid past this point (=NULL) + SetEvent(data->Continue); // let the main thread continue; past this point the data are no longer valid (=NULL) data = NULL; // if everything went well, open the requested file in the window @@ -239,8 +239,8 @@ CPluginInterfaceForViewer::ViewFile(const char *name, int left, int top, int wid BOOL *lockOwner, CSalamanderPluginViewerData *viewerData, int enumFilesSourceUID, int enumFilesCurrentIndex) { - // DemoPlug does not use 'viewerData'; otherwise we would pass the values (not references) - // via CTVData to the viewer thread... + // DemoPlug does not use 'viewerData'; otherwise the values would have to be passed + // via CTVData to the viewer thread, not by reference... CTVData data; data.AlwaysOnTop = alwaysOnTop; @@ -263,7 +263,7 @@ CPluginInterfaceForViewer::ViewFile(const char *name, int left, int top, int wid if (ThreadQueue.StartThread(ViewerThreadBody, &data)) { - // wait until the thread processes the supplied data and returns results + // wait until the thread processes the supplied data and returns the results WaitForSingleObject(data.Continue, INFINITE); } else data.Success = FALSE; @@ -287,7 +287,7 @@ class CViewerThread : public CThread BOOL* Success; int EnumFilesSourceUID; // UID of the source used to enumerate files in the viewer - int EnumFilesCurrentIndex; // index of the first viewer file in the source + int EnumFilesCurrentIndex; // index of the first file in the viewer within the source public: CViewerThread(const char* name, int left, int top, int width, int height, @@ -607,7 +607,7 @@ BOOL CViewerWindow::InitializeGraphics() BOOL ok = SalamanderGUI->CreateGrayscaleAndMaskBitmaps(hTmpColorBitmap, RGB(255, 0, 255), hTmpGrayBitmap, hTmpMaskBitmap); - if (ok) // put the obtained bitmap handles into HANDLES (manual insertion example; easier + if (ok) // put the obtained bitmap handles into HANDLES (manual insertion example) { // in this scenario DeleteObject follows immediately, so use the NOHANDLES macro with DeleteObject) HANDLES_ADD(__htBitmap, __hoCreateDIBitmap, hTmpGrayBitmap); HANDLES_ADD(__htBitmap, __hoCreateDIBitmap, hTmpMaskBitmap); @@ -746,7 +746,7 @@ CViewerWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_CREATE: { InitializeGraphics(); - DragAcceptFiles(HWindow, TRUE); // drag&drop open file + DragAcceptFiles(HWindow, TRUE); // enable drag-and-drop file opening MainMenu = SalamanderGUI->CreateMenuPopup(); if (MainMenu == NULL) return -1; @@ -801,7 +801,7 @@ CViewerWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_DESTROY: { - DragAcceptFiles(HWindow, FALSE); // drag&drop open file + DragAcceptFiles(HWindow, FALSE); // disable drag-and-drop file opening if (CfgSavePosition) { CfgWindowPlacement.length = sizeof(WINDOWPLACEMENT); @@ -878,9 +878,9 @@ CViewerWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) HDWP hdwp = HANDLES(BeginDeferWindowPos(2)); if (hdwp != NULL) { - // +4: when widening the window the last four pixels refused to repaint - // in the rebar; even after hours I could not find the cause; Salamander handles it fine; - // this workaround suffices for now; maybe I will remember the cause later + // +4: when increasing the window width, the last four pixels did not repaint + // in the rebar; the cause was not found after several hours; it works in Salamander; + // keep this workaround for now; maybe the cause will become clear later hdwp = HANDLES(DeferWindowPos(hdwp, HRebar, NULL, 0, 0, r.right + 4, rebarHeight, SWP_NOACTIVATE | SWP_NOZORDER)); diff --git a/src/plugins/demoview/demoview.h b/src/plugins/demoview/demoview.h index 8010dc2ce..20c38f300 100644 --- a/src/plugins/demoview/demoview.h +++ b/src/plugins/demoview/demoview.h @@ -140,7 +140,7 @@ class CRendererWindow : public CWindow class CViewerWindow : public CWindow { public: - HANDLE Lock; // 'lock' object or NULL (set to the signaled state once we close the file) + HANDLE Lock; // 'lock' object or NULL (set to the signaled state after the file is closed) char Name[MAX_PATH]; // file name or "" CRendererWindow Renderer; // viewer inner window HIMAGELIST HGrayToolBarImageList; // toolbar and menu in the gray variant (computed from the colored one) @@ -154,7 +154,7 @@ class CViewerWindow : public CWindow CGUIToolBarAbstract* ToolBar; int EnumFilesSourceUID; // source UID for enumerating files in the viewer - int EnumFilesCurrentIndex; // index of the current viewer file within the source + int EnumFilesCurrentIndex; // index of the current file in the viewer within the source public: CViewerWindow(int enumFilesSourceUID, int enumFilesCurrentIndex); diff --git a/src/plugins/demoview/dialogs.cpp b/src/plugins/demoview/dialogs.cpp index 2eb951eb6..7f58ec2bb 100644 --- a/src/plugins/demoview/dialogs.cpp +++ b/src/plugins/demoview/dialogs.cpp @@ -36,7 +36,7 @@ CCommonDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) // horizontally and vertically center the dialog relative to the parent if (Parent != NULL) SalamanderGeneral->MultiMonCenterWindow(HWindow, Parent, TRUE); - break; // want focus from DefDlgProc + break; // let DefDlgProc handle focus } } return CDialog::DialogProc(uMsg, wParam, lParam); @@ -98,7 +98,7 @@ class CCenteredPropertyWindow : public CWindow break; } - case WM_APP + 1000: // we should detach from the dialog (already centered) + case WM_APP + 1000: // detach from the dialog (it is already centered) { DetachWindow(); delete this; // a bit of a hack, but nobody will touch 'this' anymore, so it's fine diff --git a/src/plugins/demoview/thumbldr.cpp b/src/plugins/demoview/thumbldr.cpp index 88816776e..9d58e51f1 100644 --- a/src/plugins/demoview/thumbldr.cpp +++ b/src/plugins/demoview/thumbldr.cpp @@ -12,7 +12,7 @@ #include "precomp.h" // opens the specified file and converts it into a sequence of DWORDs -// that is, 24 bits for color (R, G, B) and 8 bits of padding +// i.e. 24 bits for color (R, G, B) and 8 unused bits // the size of a single row in bytes is: image_width * sizeof(DWORD) DWORD GetClrUsed(const BITMAPINFOHEADER* bih, BOOL max) @@ -29,7 +29,7 @@ DWORD GetClrUsed(const BITMAPINFOHEADER* bih, BOOL max) case 8: return 256; default: - return 0; // A 24 or 32 bitcount DIB has no color table + return 0; // A 24-bit or 32-bit DIB has no color table } } @@ -147,7 +147,7 @@ CPluginInterfaceForThumbLoader::LoadThumbnail(const char* filename, BOOL fastThumbnail) { BOOL stopFurtherLoaders = TRUE; // don't try next parsers - // we must call thumbMaker->SetError() when error occures and stopFurtherLoaders is TRUE + // we must call thumbMaker->SetError() when an error occurs and stopFurtherLoaders is TRUE // open the file HANDLE hFile = HANDLES_Q(CreateFile(filename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, @@ -194,7 +194,7 @@ CPluginInterfaceForThumbLoader::LoadThumbnail(const char* filename, processTopDown = TRUE; height *= -1; } - // pass picture format to Open Salamander + // pass image parameters to Open Salamander if (thumbMaker->SetParameters(width, height, processTopDown ? 0 : SSTHUMB_MIRROR_VERT)) { LOGPALETTE* palette = NULL; diff --git a/src/plugins/demoview/viewer.cpp b/src/plugins/demoview/viewer.cpp index f7518f20f..9fb315ad7 100644 --- a/src/plugins/demoview/viewer.cpp +++ b/src/plugins/demoview/viewer.cpp @@ -68,7 +68,7 @@ MENU_TEMPLATE_ITEM PopupMenuTemplate[] = struct CButtonData { - int ImageIndex; // zero base index + int ImageIndex; // zero-based index WORD ToolTipResID; // resource ID with the tooltip string WORD ID; // universal command CViewerWindowEnablerEnum Enabler; // control variable for enabling the button @@ -127,7 +127,7 @@ class CViewerThread : public CThread BOOL* Success; int EnumFilesSourceUID; // source UID for enumerating files in the viewer - int EnumFilesCurrentIndex; // index of the first viewer file within the source + int EnumFilesCurrentIndex; // index of the first file in the viewer within the source public: CViewerThread(const char* name, int left, int top, int width, int height, @@ -389,8 +389,8 @@ BOOL CViewerWindow::InitializeGraphics() hTmpColorBitmap = HANDLES(LoadBitmap(DLLInstance, MAKEINTRESOURCE(SalamanderGeneral->CanUse256ColorsBitmap() ? IDB_TOOLBAR256 : IDB_TOOLBAR16))); BOOL ok = SalamanderGUI->CreateGrayscaleAndMaskBitmaps(hTmpColorBitmap, RGB(255, 0, 255), hTmpGrayBitmap, hTmpMaskBitmap); - if (ok) // insert the acquired bitmap handles into HANDLES (example of manual insertion; simpler - { // in this situation (DeleteObject immediately follows) to use the NOHANDLES macro for DeleteObject) + if (ok) // insert the acquired bitmap handles into HANDLES (manual insertion example) + { // here DeleteObject follows immediately, so NOHANDLES with DeleteObject would be simpler HANDLES_ADD(__htBitmap, __hoCreateDIBitmap, hTmpGrayBitmap); HANDLES_ADD(__htBitmap, __hoCreateDIBitmap, hTmpMaskBitmap); } @@ -583,7 +583,7 @@ CViewerWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_DESTROY: { - DragAcceptFiles(HWindow, FALSE); // allow opening files via drag and drop + DragAcceptFiles(HWindow, FALSE); // disable drag-and-drop file opening if (CfgSavePosition) { CfgWindowPlacement.length = sizeof(WINDOWPLACEMENT); @@ -661,8 +661,8 @@ CViewerWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (hdwp != NULL) { // +4: without this offset the last four pixels of the rebar failed to repaint while resizing the window. - // I could not track down the cause even after spending several hours on it (Salamander itself works fine). - // Leave the workaround in place for now and revisit once we rediscover the root cause. + // the cause was not found after several hours; Salamander itself works fine. + // keep this workaround for now and revisit it if the root cause becomes clear. hdwp = HANDLES(DeferWindowPos(hdwp, HRebar, NULL, 0, 0, r.right + 4, rebarHeight, SWP_NOACTIVATE | SWP_NOZORDER)); @@ -729,7 +729,7 @@ CViewerWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) BOOL noMoreFiles = FALSE; char fileName[MAX_PATH]; fileName[0] = 0; - if (shiftPressed) // legacy hot-key: use Backspace (keys + commands in the menu see PictView, menu File/Other Files) + if (shiftPressed) // legacy hotkey: use Backspace instead (see PictView, File/Other Files for keys and menu commands) { ok = SalamanderGeneral->GetPreviousFileNameForViewer(EnumFilesSourceUID, &EnumFilesCurrentIndex, @@ -901,7 +901,7 @@ CViewerWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case CM_VIEWER_PASTE: { SalamanderGeneral->SalMessageBox(HWindow, "TODO: Paste", LoadStr(IDS_PLUGINNAME), MB_ICONINFORMATION | MB_OK); - Enablers[vwePaste] = FALSE; // it's OK only if it was Cut (Copy should not change it) + Enablers[vwePaste] = FALSE; // OK only if it was Cut (Copy should not change it) UpdateEnablers(); break; } diff --git a/src/plugins/diskmap/DiskMap/GUI.DirectoryLine.h b/src/plugins/diskmap/DiskMap/GUI.DirectoryLine.h index f56a26d06..dfa764e23 100644 --- a/src/plugins/diskmap/DiskMap/GUI.DirectoryLine.h +++ b/src/plugins/diskmap/DiskMap/GUI.DirectoryLine.h @@ -278,7 +278,7 @@ class CDirectoryLine : public CChildWindow int rp = p; int miswidth = pathwidth - width + this->_dotsWidth + dx[p - 1]; - dx[strlen] = miswidth; //stopper + dx[strlen] = miswidth; //sentinel while (miswidth > dx[rp]) rp++; diff --git a/src/plugins/diskmap/DiskMap/GUI.DiskMapView.h b/src/plugins/diskmap/DiskMap/GUI.DiskMapView.h index e2257571f..c63fbac8b 100644 --- a/src/plugins/diskmap/DiskMap/GUI.DiskMapView.h +++ b/src/plugins/diskmap/DiskMap/GUI.DiskMapView.h @@ -80,7 +80,7 @@ class CDiskMapView : public CChildWindow } else { - //TODO: Display something! + // TODO: Display content BitBlt(hdc, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, 0, 0, BLACKNESS); //HACK: this was put together quickly to have something for version 1.0; fortunately it should not happen too often diff --git a/src/plugins/diskmap/DiskMap/GUI.LoadAnimation.h b/src/plugins/diskmap/DiskMap/GUI.LoadAnimation.h index c49b01258..e8f04acc8 100644 --- a/src/plugins/diskmap/DiskMap/GUI.LoadAnimation.h +++ b/src/plugins/diskmap/DiskMap/GUI.LoadAnimation.h @@ -93,7 +93,7 @@ class CLoadAnimation : public CAnimation } GetTextExtentPoint32(hdc, this->_escinfo->GetString(), (int)this->_escinfo->GetLength(), &sz); this->_escinfoWidth = sz.cx; - this->_lineHeight = sz.cy; //TODO nicer! + this->_lineHeight = sz.cy; // TODO: Improve this. SelectObject(hdc, fo); this->_headersWidth = width; //return TRUE; diff --git a/src/plugins/diskmap/DiskMap/GUI.ToolTip.h b/src/plugins/diskmap/DiskMap/GUI.ToolTip.h index d527bfb4f..811fbd048 100644 --- a/src/plugins/diskmap/DiskMap/GUI.ToolTip.h +++ b/src/plugins/diskmap/DiskMap/GUI.ToolTip.h @@ -426,7 +426,7 @@ class CFileInfoTooltip : public CFrameWindow //Check normal font height GetTextExtentPoint32(hdc, TEXT("W"), 1, &sz); - this->_headerheight += sz.cy; //even when type string is empty add the space so the tooltip doesn't change its size unexpectedly + this->_headerheight += sz.cy; // reserve the space even when the type string is empty so the tooltip size does not change unexpectedly int dataheight = 0; for (int i = 0; i < TT_LINECOUNT; i++) diff --git a/src/plugins/diskmap/DiskMap/System.Lock.h b/src/plugins/diskmap/DiskMap/System.Lock.h index e2209c5cc..693b87e3a 100644 --- a/src/plugins/diskmap/DiskMap/System.Lock.h +++ b/src/plugins/diskmap/DiskMap/System.Lock.h @@ -15,7 +15,7 @@ class CLock } BOOL TryEnter() { - return InterlockedExchange(&this->_lock, 1) == 0; // before writing, 0 means acquire the lock; otherwise it was already locked (1) + return InterlockedExchange(&this->_lock, 1) == 0; // before the write, 0 means the lock was acquired; otherwise it was already locked (1) } void Enter() { diff --git a/src/plugins/diskmap/DiskMap/System.WorkerThread.h b/src/plugins/diskmap/DiskMap/System.WorkerThread.h index d02d3cf40..0dd5c03b9 100644 --- a/src/plugins/diskmap/DiskMap/System.WorkerThread.h +++ b/src/plugins/diskmap/DiskMap/System.WorkerThread.h @@ -18,7 +18,7 @@ class CMyThreadQueue : public CThreadQueue public: CMyThreadQueue(const char* queueName /* e.g., "DemoPlug Viewers" */) : CThreadQueue(queueName) {} - void Add(HANDLE hThread, DWORD tid) // adds an item to the queue, returns success + void Add(HANDLE hThread, DWORD tid) // adds an item to the queue { CS.Enter(); CThreadQueue::Add(new CThreadQueueItem(hThread, tid)); // cannot fail @@ -108,22 +108,22 @@ class CWorkerThread this->_lock = new CLock(); this->_rwlock = new CRWLock(); - this->_doDelete = FALSE; // the thread may finish before CreateThread() returns, so postpone deletion + this->_doDelete = FALSE; // the thread may finish before CreateThread() returns, so postpone deleting the object this->_hThread = CreateThread( NULL, // default security attributes 0, // use default stack size CWorkerThread::s_ThreadProc, // thread function this, // argument to thread function - (suspended) ? CREATE_SUSPENDED : 0, // use default creation flags - &this->_threadId); // returns the thread identifier + (suspended) ? CREATE_SUSPENDED : 0, // creation flags + &this->_threadId); // receives the thread identifier if (this->_hThread != NULL) ThreadQueue.Add(this->_hThread, this->_threadId); else this->_finished = TRUE; // the thread failed to start = act as if it has already finished if (selfDelete) - this->SetSelfDelete(selfDelete); // deletion of the object is now possible + this->SetSelfDelete(selfDelete); // the object can now be deleted } ~CWorkerThread() { @@ -144,7 +144,7 @@ class CWorkerThread CLock* GetLock() { return this->_lock; } CRWLock* GetRWLock() { return this->_rwlock; } - void SetSelfDelete(BOOL selfDelete) //after calling with TRUE, references to the object are unsafe and it may be destroyed at any time + void SetSelfDelete(BOOL selfDelete) // after calling with TRUE, the object may be destroyed at any time, so references to it are unsafe { this->_innerlock->Enter(); if (this->_doDelete != selfDelete) @@ -155,11 +155,11 @@ class CWorkerThread } else //if the thread has already finished { - if (selfDelete) //wants to delete me, so delete... + if (selfDelete) // wants to delete this object, so delete it... { this->_innerlock->Leave(); //first release the lock delete this; //destroy ourselves - return; //and exit quickly + return; // return immediately } } } diff --git a/src/plugins/diskmap/DiskMap/TreeMap.CDiskMap.h b/src/plugins/diskmap/DiskMap/TreeMap.CDiskMap.h index 4d2ad3eaf..1acc13a19 100644 --- a/src/plugins/diskmap/DiskMap/TreeMap.CDiskMap.h +++ b/src/plugins/diskmap/DiskMap/TreeMap.CDiskMap.h @@ -551,7 +551,7 @@ class CDiskMap BOOL ZoomOut() { if (this->_viewdir == NULL) - return FALSE; //if it is not null, the root should not be null either + return FALSE; //if _viewdir is not NULL, _rootdir should not be NULL either if (this->_viewdir != this->_rootdir) { this->_viewdir = this->_viewdir->GetParent(); @@ -585,7 +585,7 @@ class CDiskMap this->_rootdir = NULL; this->_populateworker = NULL; wrk->SetSelfDelete(TRUE); - wrk->Abort(TRUE); //TODO: do I really want to wait? + wrk->Abort(TRUE); //TODO: should this really wait? return TRUE; } diff --git a/src/plugins/diskmap/DiskMap/TreeMap.DiskMap.CDirectoryOverlay.h b/src/plugins/diskmap/DiskMap/TreeMap.DiskMap.CDirectoryOverlay.h index 996eb0c5b..84d26c544 100644 --- a/src/plugins/diskmap/DiskMap/TreeMap.DiskMap.CDirectoryOverlay.h +++ b/src/plugins/diskmap/DiskMap/TreeMap.DiskMap.CDirectoryOverlay.h @@ -420,7 +420,7 @@ class CDirectoryOverlay : public CDiskMapOverlay else //text pixel { if (tx > titlewidth) - titlewidth = tx; //extend the maximum text length + titlewidth = tx; //extend the maximum text width txt_data[cxp] = 0xff; //text pixel will be white @@ -429,7 +429,7 @@ class CDirectoryOverlay : public CDiskMapOverlay for (int px = 0; px < 4; px++) { if ((px == 0) && (py == 0)) - continue; //no need for the center + continue; //center pixel not needed int txa = CDirectoryOverlay_shadowdata[py * 4 + px]; if (tx - px > 0) diff --git a/src/plugins/diskmap/DiskMap/TreeMap.DiskMap.CDiskMapOverlay.h b/src/plugins/diskmap/DiskMap/TreeMap.DiskMap.CDiskMapOverlay.h index 8a6633440..69b6d5bff 100644 --- a/src/plugins/diskmap/DiskMap/TreeMap.DiskMap.CDiskMapOverlay.h +++ b/src/plugins/diskmap/DiskMap/TreeMap.DiskMap.CDiskMapOverlay.h @@ -40,7 +40,7 @@ class CSelectedCushionOverlay : public CDiskMapOverlay BOOL Paint(CZBitmap* pix, HDC refDC) { if (this->_selected == FALSE) - return TRUE; //ok, but nothing to draw + return TRUE; //nothing is drawn int width = pix->GetWidth(); int height = pix->GetHeight(); diff --git a/src/plugins/diskmap/DiskMap/TreeMap.FileData.CZDirectory.cpp b/src/plugins/diskmap/DiskMap/TreeMap.FileData.CZDirectory.cpp index 8e24b651a..5e25e621a 100644 --- a/src/plugins/diskmap/DiskMap/TreeMap.FileData.CZDirectory.cpp +++ b/src/plugins/diskmap/DiskMap/TreeMap.FileData.CZDirectory.cpp @@ -204,7 +204,7 @@ INT64 CZDirectory::PopulateDir(CWorkerThread* mythread, TCHAR* path, int pos, si realsize = 0; disksize = 0; } - else if (datasize == 0) //everything ok, but empty + else if (datasize == 0) //no error, but empty { this->_dircount++; dircount++; @@ -294,7 +294,7 @@ INT64 CZDirectory::PopulateDir(CWorkerThread* mythread, TCHAR* path, int pos, si this->_files->At(fre) = f; } //if (((filecount + dircount) > MAXREPORTEDFILES) || (GetTickCount() - lastTime > 500)) //either many files or 0.5 sec elapsed - if ((GetTickCount() - lastTime > 250) && (filecount + dircount) > 0) //if 0.25 sec elapsed and at least something new was found + if ((GetTickCount() - lastTime > 250) && (filecount + dircount) > 0) //if 0.25 sec have elapsed and at least something new was found { this->_root->IncStats(filecount, dircount, tsize); lastTime = GetTickCount(); diff --git a/src/plugins/diskmap/DiskMap/TreeMap.FileData.CZFile.cpp b/src/plugins/diskmap/DiskMap/TreeMap.FileData.CZFile.cpp index ece9a762a..11910503c 100644 --- a/src/plugins/diskmap/DiskMap/TreeMap.FileData.CZFile.cpp +++ b/src/plugins/diskmap/DiskMap/TreeMap.FileData.CZFile.cpp @@ -10,7 +10,7 @@ size_t CZFile::GetFullName(TCHAR* buff, size_t size) size_t pos = 0; if (this->_parent) pos = this->_parent->GetFullName(buff, size); - if ((pos + this->_namelen + 1) < size) //pos = path + null terminator; total = path + ( '\\' + name length ) + null < size + if ((pos + this->_namelen + 1) < size) //pos = path + null terminator; total = path + ( '\\' + name length ) + null terminator < size { if (pos && buff[pos - 1] != TEXT('\\')) { diff --git a/src/plugins/diskmap/DiskMap/TreeMap.Graphics.CCushionGraphics.h b/src/plugins/diskmap/DiskMap/TreeMap.Graphics.CCushionGraphics.h index 635d9b39f..ca4407bdf 100644 --- a/src/plugins/diskmap/DiskMap/TreeMap.Graphics.CCushionGraphics.h +++ b/src/plugins/diskmap/DiskMap/TreeMap.Graphics.CCushionGraphics.h @@ -5,8 +5,8 @@ #include -// precaution against runtime check failure in the debug version: the original macro casted RGB to WORD, -// so it reported data loss (RED component) +// precaution against a runtime check failure in the debug version: the original macro casts RGB to WORD, +// so it reports data loss (RED component) #undef GetGValue #define GetGValue(rgb) ((BYTE)(((rgb) >> 8) & 0xFF)) @@ -126,7 +126,7 @@ class CCushionGraphics BOOL Load(BYTE* dta, int size) { - if (size < 10) //10-byte header... 8 header + 2 version bytes + if (size < 10) //10-byte header... 8 header bytes + 2 version bytes { //_tcscpy(errbuff, TEXT("Internal error: Wrong data size")); //errlen = _tcslen(errbuff); @@ -212,7 +212,7 @@ class CCushionGraphics BYTE* aby = NULL; BOOL isAlpha = FALSE; - while (tbs + 4 <= end) // position + 4bytes chunk info + while (tbs + 4 <= end) // current position + 4-byte chunk info { mxc = *(unsigned short*)tbs; tbs += 2; //Chunk ID @@ -242,7 +242,7 @@ class CCushionGraphics break; case 0x4645: //EF (end of file) if (mxs != 0) - return FALSE; //EF always empty! + return FALSE; //EF must always be empty EFfound = TRUE; break; case 0x4642: //BF (fixed border info) @@ -257,9 +257,9 @@ class CCushionGraphics fil = *(unsigned short*)tbs; tbs += 2; if (fit + fib > h) - return FALSE; //fixed height is bigger then image height + return FALSE; //fixed height exceeds image height if (fir + fil > w) - return FALSE; //fixed width is bigger then image width + return FALSE; //fixed width exceeds image width break; case 0x4144: //DA (Alpha channel) tbd = aby; diff --git a/src/plugins/diskmap/DiskMap/TreeMap.TreeData.h b/src/plugins/diskmap/DiskMap/TreeMap.TreeData.h index ba20227ff..6c5036ca4 100644 --- a/src/plugins/diskmap/DiskMap/TreeMap.TreeData.h +++ b/src/plugins/diskmap/DiskMap/TreeMap.TreeData.h @@ -157,7 +157,7 @@ class CTreeMapRendererBase return dirHorizontal; break; } - return dirNULL; //TODO: error! + return dirNULL; //TODO: bug } //virtual ERenderDecision Decide(CCushionRow *csr, double width, double length, int level, EDirection lastdir, INT64 datasize, INT64 remainingdata, int i, int remainingfiles) virtual ERenderDecision Decide(CCushionRow* csr, double width, double length, INT64 datasize, INT64 remainingdata) = 0; diff --git a/src/plugins/diskmap/DiskMap/Utils.Array.h b/src/plugins/diskmap/DiskMap/Utils.Array.h index dd141cdd8..b5ff20a0c 100644 --- a/src/plugins/diskmap/DiskMap/Utils.Array.h +++ b/src/plugins/diskmap/DiskMap/Utils.Array.h @@ -92,7 +92,7 @@ class TAutoDirectArray { free(Blocks[_count / BlockSize]); } - if (!_count) //used them all + if (!_count) // all elements used up { free(Blocks); Blocks = NULL; @@ -104,7 +104,7 @@ class TAutoDirectArray CDynamicArray * const &operator[](float index); // function is never called, but if it is missing // MSVC does terrible things */ - DATA_TYPE& operator[](int index) //returns the element at the position + DATA_TYPE& operator[](int index) // returns the element at the given position { return Blocks[index / BlockSize][index % BlockSize]; } diff --git a/src/plugins/diskmap/DiskMap/Utils.CStringFormatter.h b/src/plugins/diskmap/DiskMap/Utils.CStringFormatter.h index 254401be3..88e80f9ea 100644 --- a/src/plugins/diskmap/DiskMap/Utils.CStringFormatter.h +++ b/src/plugins/diskmap/DiskMap/Utils.CStringFormatter.h @@ -271,7 +271,7 @@ class CStringFormatter static const int maxexp = sizeof expch / sizeof TCHAR - 2; size_t len = 0; int exp = 0; - //C4244 ok: we only need the first few digits because we compute the short form "1.45TB" + //C4244 is OK: we only need the first few digits because we compute the short form "1,45TB" double rs = (double)(__int64)size; while (rs >= 1024 && exp < maxexp) { diff --git a/src/plugins/diskmap/DiskMapPlugin/DiskMapPlugin.cpp b/src/plugins/diskmap/DiskMapPlugin/DiskMapPlugin.cpp index 74f1dc9b9..050d56acf 100644 --- a/src/plugins/diskmap/DiskMapPlugin/DiskMapPlugin.cpp +++ b/src/plugins/diskmap/DiskMapPlugin/DiskMapPlugin.cpp @@ -87,7 +87,7 @@ class CSalamanderCallback : public CSalamanderCallbackAbstract char focusPath[MAX_PATH]; lstrcpyn(focusPath, FocusPathBuf, MAX_PATH); FocusPathBuf[0] = 0; - if (focusPath[0] != 0) // only if we were not unlucky (we did not hit the beginning of Salamander's BUSY mode) + if (focusPath[0] != 0) // only if we were not unlucky (that is, we did not hit the start of Salamander's BUSY mode) { LPTSTR name; if (SalamanderGeneral->CutDirectory(focusPath, &name)) @@ -104,7 +104,7 @@ class CSalamanderCallback : public CSalamanderCallbackAbstract char focusPath[MAX_PATH]; lstrcpyn(focusPath, FocusPathBuf, MAX_PATH); FocusPathBuf[0] = 0; - if (focusPath[0] != 0) // only if we were not unlucky (we did not hit the beginning of Salamander's BUSY mode) + if (focusPath[0] != 0) // only if we did not enter at the start of Salamander's BUSY mode { SalamanderGeneral->SkipOneActivateRefresh(); // the main window will not refresh when switching from the viewer //SalamanderGeneral->ChangePanelPath(PANEL_SOURCE, focusPath); @@ -212,8 +212,8 @@ char* LoadStr(int resID) if ((5000 - (act - buffer) == size + 1) && (act > buffer)) { // if the string was exactly at the end of the buffer, it could - // be a truncated string -- if we can move the window - // to the beginning of the buffer, load the string once again + // have been truncated; if we can move the window + // to the beginning of the buffer, load the string again act = buffer; goto RELOAD; } @@ -714,7 +714,7 @@ BOOL WINAPI CPluginInterfaceForMenuExt::ExecuteMenuItem(CSalamanderForOperations //TODO: there should be a prompt asking the user for the path and confirming it... - if (curPathIsDisk) // 'path' is the path to a file/directory, perform the requested action with it + if (curPathIsDisk) // 'path' is the path to a file or directory; perform the requested action on it { //TRACE_I("Opening(" << curPath << ")." /*"): " << GetErrorText(error)*/); OpenDiskMapWindow(parent, curPath); @@ -724,7 +724,7 @@ BOOL WINAPI CPluginInterfaceForMenuExt::ExecuteMenuItem(CSalamanderForOperations //TRACE_I("Not disk."); } - return FALSE; // do not unselect items in the panel + return FALSE; // do not deselect items in the panel } default: SalamanderGeneral->ShowMessageBox("Unknown command.", "DEMOPLUG", MSGBOX_ERROR); diff --git a/src/plugins/diskmap/DiskMapPlugin/DiskMapPlugin.h b/src/plugins/diskmap/DiskMapPlugin/DiskMapPlugin.h index ba27b7ca4..b95bf651c 100644 --- a/src/plugins/diskmap/DiskMapPlugin/DiskMapPlugin.h +++ b/src/plugins/diskmap/DiskMapPlugin/DiskMapPlugin.h @@ -1,10 +1,10 @@ // SPDX-FileCopyrightText: 2023 Open Salamander Authors // SPDX-License-Identifier: GPL-2.0-or-later -// The following ifdef block is the standard way of creating macros which make exporting +// The following ifdef block is the standard way of creating macros that make exporting // from a DLL simpler. All files within this DLL are compiled with the ZAREVAKDISKMAPPLUGIN_EXPORTS -// symbol defined on the command line. this symbol should not be defined on any project -// that uses this DLL. This way any other project whose source files include this file see +// symbol defined on the command line. This symbol should not be defined in any project +// that uses this DLL. This way, any other project whose source files include this file sees // ZAREVAKDISKMAPPLUGIN_API functions as being imported from a DLL, whereas this DLL sees symbols // defined with this macro as being exported. diff --git a/src/plugins/filecomp/cwbase.cpp b/src/plugins/filecomp/cwbase.cpp index 5562a1dbc..9f9185329 100644 --- a/src/plugins/filecomp/cwbase.cpp +++ b/src/plugins/filecomp/cwbase.cpp @@ -145,9 +145,9 @@ void CFilecompCoWorkerBase::ScrictCompare( while (++iterator < end && IsSpaceX(*iterator)) if (*iterator == '\n') line++, linebreaks++; - // Whitespace containing one linebreak matches whitespace without - // linebreaks. It is represented by ' ' in compare data. - // Blank line matches any sequence of one or more blanklines. Blank + // Whitespace containing one line break matches whitespace without + // line breaks. It is represented by ' ' in compare data. + // A blank line matches any sequence of one or more blank lines. A blank // line can contain any whitespace. It is represented by '\n' in // compare data. Strict.CompareData[i].push_back( @@ -203,13 +203,13 @@ void CFilecompCoWorkerBase::ScrictCompare( if (d == -1) CFilecompWorker::CException::Raise(IDS_INTERNALERROR, 0); - // TODO once I implement strict mode this should be handled + // TODO once strict mode is implemented, this should be handled // if (d == 0) // shift-boundaries is called before RemoveSingleCharMatches ShiftBoundaries(Strict.EditScript, Strict.CompareData); - // remove sigle char matches + // remove single-char matches RemoveSingleCharMatches(); // build line scripts @@ -403,7 +403,7 @@ void CFilecompCoWorkerBase::ShiftBoundaries(CEditScript& editScript, CCom for (CEditScript::iterator change = editScript.begin(); change < editScript.end(); ++change) { - // ignore changes occured only in other file + // ignore changes that occurred only in the other file if (change->Length[f] == 0) continue; diff --git a/src/plugins/filecomp/cwoptim.cpp b/src/plugins/filecomp/cwoptim.cpp index b28defa7d..0d5dd39ef 100644 --- a/src/plugins/filecomp/cwoptim.cpp +++ b/src/plugins/filecomp/cwoptim.cpp @@ -232,11 +232,11 @@ void CFilecompCoWorkerOptimized::Compare(CTextFileReader (&reader)[2]) this->CancelFlag); if (d == -1) CFilecompWorker::CException::Raise(IDS_INTERNALERROR, 0); - /* if (d == 0) We now let the file display - { - throw CFilecompWorker::CFilesDontDifferException(); - } - }*/ + /* if (d == 0) We now let the file be displayed + { + throw CFilecompWorker::CFilesDontDifferException(); + } + }*/ // shift-boundaries, call before RemoveSingleCharMatches this->ShiftBoundaries(editScript, compareData); diff --git a/src/plugins/filecomp/dialogs.cpp b/src/plugins/filecomp/dialogs.cpp index f311d0547..b6b49cbfb 100644 --- a/src/plugins/filecomp/dialogs.cpp +++ b/src/plugins/filecomp/dialogs.cpp @@ -133,7 +133,7 @@ LRESULT CCompareFilesDialog::DragDropEditProc(HWND hWnd, UINT uMsg, WPARAM wPara CCompareFilesDialog* pParent = (CCompareFilesDialog*)WindowsManager.GetWindowPtr(GetParent(hWnd)); if (!pParent) - return NULL; // What's wrong? + return NULL; // Parent dialog not found if (WM_DROPFILES == uMsg) { @@ -170,7 +170,7 @@ CCompareFilesDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) SG->InstallWordBreakProc(hWnd1); // install WordBreakProc into the combo box SG->InstallWordBreakProc(hWnd2); // install WordBreakProc into the combo box - // I believe OldEditProc1 and OldEditProc2 are equal. But I am rather paranoic... + // OldEditProc1 and OldEditProc2 should be equal, but keep both separately to be safe. OldEditProc1 = (WNDPROC)GetWindowLongPtr(hWnd1, GWLP_WNDPROC); OldEditProc2 = (WNDPROC)GetWindowLongPtr(hWnd2, GWLP_WNDPROC); SetWindowLongPtr(hWnd1, GWLP_WNDPROC, (LONG_PTR)DragDropEditProc); diff --git a/src/plugins/filecomp/dialogs.h b/src/plugins/filecomp/dialogs.h index a739dbe4b..54b396777 100644 --- a/src/plugins/filecomp/dialogs.h +++ b/src/plugins/filecomp/dialogs.h @@ -65,7 +65,7 @@ struct CColorsCfgButton { int TextID; // button label identifier int ColorLineNumFG; // index of the FG color for the first button or -1 (FG cannot be configured) - int ColorLineNumBK; // index of the BG color for the first button or -1 (the button will not be visible) + int ColorLineNumBK; // index of the BK color for the first button or -1 (the button will not be visible) int ColorTextFG; // index of the FG color for the second button or -1 (FG cannot be configured) int ColorTextBK; // index of the BG color for the second button or -1 (the button will not be visible) }; diff --git a/src/plugins/filecomp/dialogs2.cpp b/src/plugins/filecomp/dialogs2.cpp index 48506ea2c..d173d0371 100644 --- a/src/plugins/filecomp/dialogs2.cpp +++ b/src/plugins/filecomp/dialogs2.cpp @@ -522,7 +522,7 @@ void CPreviewWindow::RePaint() void CPreviewWindow::SetFont(LOGFONT* font) { CALL_STACK_MESSAGE1("CPreviewWindow::SetFont()"); - // load the font + // create the font if (HFont) DeleteObject(HFont); HDC hdc = GetDC(NULL); diff --git a/src/plugins/filecomp/dialogs4.cpp b/src/plugins/filecomp/dialogs4.cpp index ae269ec7c..d3668da0e 100644 --- a/src/plugins/filecomp/dialogs4.cpp +++ b/src/plugins/filecomp/dialogs4.cpp @@ -218,7 +218,7 @@ class CCenteredPropertyWindow : public CWindow break; } - case WM_APP + 1000: // we should detach from the dialog (centering is done) + case WM_APP + 1000: // detach from the dialog after centering { DetachWindow(); delete this; // a bit of a hack, but nothing will touch 'this' anymore so it's fine diff --git a/src/plugins/filecomp/dlg_com.cpp b/src/plugins/filecomp/dlg_com.cpp index d6a9901e4..34c18bb55 100644 --- a/src/plugins/filecomp/dlg_com.cpp +++ b/src/plugins/filecomp/dlg_com.cpp @@ -88,7 +88,7 @@ CCommonDialog::CCommonDialog(int resID, HWND hParent, CObjectOrigin origin) { // horizontal and vertical centering of the dialog over the parent CenterWindow(HWindow); - break; // I want focus from DefDlgProc + break; // let DefDlgProc set the focus } } return CDialog::DialogProc(uMsg, wParam, lParam); diff --git a/src/plugins/filecomp/filecache.cpp b/src/plugins/filecomp/filecache.cpp index 3855c9ced..514d5954f 100644 --- a/src/plugins/filecomp/filecache.cpp +++ b/src/plugins/filecomp/filecache.cpp @@ -7,7 +7,7 @@ #define SECTOR_SIZE 4096 // We seek at offsets being multiples of SECTOR_SIZE #define BUFFER_SIZE (2 * 1024 * 1024) // We read at most this amount from a file at a sequence of BLOCK_READ_SIZE reads -#define BLOCK_READ_SIZE (32 * 1024) // Atomic size of one ReadFile. BUFFER_SIZE must be a multiple of BLOCK_READ_SIZE +#define BLOCK_READ_SIZE (32 * 1024) // Size of a single ReadFile call. BUFFER_SIZE must be a multiple of BLOCK_READ_SIZE CCachedFile::CCachedFile(/*DWORD minViewSize*/) { @@ -77,9 +77,9 @@ LPBYTE CCachedFile::ReadBuffer(QWORD offset, DWORD size, const int& CancelFlag) ; DWORD err; - // Space for optimization: Instead of dummy SetFilePointer and possibly partially rereading - // what we already have, we can do some memcpy. But then we might not read from sector boundary - BufferOffset = offset / SECTOR_SIZE * SECTOR_SIZE; // Align to "cluster" size + // Optimization opportunity: instead of calling SetFilePointer redundantly and possibly rereading + // data we already have, we could use memcpy. But then we might not read from a sector boundary + BufferOffset = offset / SECTOR_SIZE * SECTOR_SIZE; // Align to the sector size li.QuadPart = BufferOffset; DataInBufSize = 0; err = SetFilePointer(File, li.LowPart, &li.HighPart, FILE_BEGIN); @@ -92,7 +92,7 @@ LPBYTE CCachedFile::ReadBuffer(QWORD offset, DWORD size, const int& CancelFlag) DWORD nTotalToRead = (DWORD)__max(size + (offset - BufferOffset), (DWORD)__min(BufferSize, FileSize - BufferOffset)); DWORD initialTicks = GetTickCount(); - // Reading 32KB chunks bases on code for File Compare in Salamand.exe + // Reading 32KB chunks is based on the code for File Compare in Salamand.exe // Reading 2MB in 32KB blocks is reportedly the fastest approach on W2K & WXP, // but slightly slower on Vista, when both files reside on the same HDD, // than reading 2MB at once. diff --git a/src/plugins/filecomp/filecomp.cpp b/src/plugins/filecomp/filecomp.cpp index b9a096822..382f5fabc 100644 --- a/src/plugins/filecomp/filecomp.cpp +++ b/src/plugins/filecomp/filecomp.cpp @@ -317,7 +317,7 @@ void CPluginInterface::LoadConfiguration(HWND parent, HKEY regKey, CSalamanderRe } UpdateDefaultColors(Colors, Palette); - // Do not allow normalization if Normaliz.dll not present + // Do not allow normalization if Normaliz.dll is not present if (!PNormalizeString) DefCompareOptions.NormalizationForm = FALSE; } @@ -689,7 +689,7 @@ CFilecompThread::Body() } if (!dialogBox || !succes) - break; // leave the message loop + break; // exit the message loop LLAUNCHFC: diff --git a/src/plugins/filecomp/filecomp.rh2 b/src/plugins/filecomp/filecomp.rh2 index 8ab67b553..51eaabf29 100644 --- a/src/plugins/filecomp/filecomp.rh2 +++ b/src/plugins/filecomp/filecomp.rh2 @@ -1,4 +1,5 @@ -// WARNING: cannot be replaced by "#pragma once" because it is included from .rc file and it seems resource compiler does not support "#pragma once" +// CommentsTranslationProject: TRANSLATED +// WARNING: cannot be replaced with "#pragma once" because this file is included from a .rc file, and the resource compiler does not seem to support "#pragma once". #ifndef __FILECOMP_RH2 #define __FILECOMP_RH2 @@ -7,7 +8,7 @@ #endif //defined(APSTUDIO_INVOKED) && !defined(APSTUDIO_READONLY_SYMBOLS) #define IDC_STATIC_1 300 -#include "statics.rh2" // 300 az 339 jsou timto zabrane !!! +#include "statics.rh2" // 300 to 339 are reserved by this include. #define IDI_FCICO 500 #define IDC_SPLIT_VERT 501 @@ -18,7 +19,7 @@ //*********************************************************************************** // -// texty +// strings // #define IDS_PLUGINNAME 1000 @@ -122,7 +123,7 @@ //*********************************************************************************** // -// virtualni IDcka - pouze pro vazbu s helpem +// virtual IDs - used only for help mapping // #define IDH_KEYBOARD 400 diff --git a/src/plugins/filecomp/mainwnd.cpp b/src/plugins/filecomp/mainwnd.cpp index 8939e48da..ac2761b1a 100644 --- a/src/plugins/filecomp/mainwnd.cpp +++ b/src/plugins/filecomp/mainwnd.cpp @@ -705,7 +705,7 @@ BOOL CMainWindow::RebuildFileViewScripts(BOOL& cancel) SetForegroundWindow(HWindow); UpdateWindow(HWindow); - return TRUE; // ok + return TRUE; // success } // something went wrong @@ -880,7 +880,7 @@ void CMainWindow::SpawnWorker(const char* path1, const char* path2, if (!worker->Create(ThreadQueue)) { delete worker; - SetEvent(WorkerEvent); // so we do not wait for it in vain + SetEvent(WorkerEvent); // so we do not wait for it unnecessarily TRACE_I("Nepovedlo se spustit diff worker thread."); } else @@ -962,8 +962,8 @@ bool CMainWindow::TextFilesDiffer(CTextCompareResults* res, char* message TTextFileViewWindow* leftFileView = (TTextFileViewWindow*)FileView[fviLeft]; TTextFileViewWindow* rightFileView = (TTextFileViewWindow*)FileView[fviRight]; - // taking ownership of the data; from now on I must release it - // passed in CTextCompareResults + // take ownership of the data; from now on it must be deallocated here + // when passed in CTextCompareResults leftFileView->SetData(res->Files[0].Text, res->Files[0].Lines, res->Files[0].LineScript); rightFileView->SetData(res->Files[1].Text, res->Files[1].Lines, res->Files[1].LineScript); @@ -1076,7 +1076,7 @@ CMainWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_TIMER: { - if (wParam == 666) // we should post CM_EXIT; the modal dialog should be gone by now + if (wParam == 666) // post CM_EXIT; the modal dialog should be gone by now { KillTimer(HWindow, 666); PostMessage(HWindow, WM_COMMAND, CM_EXIT, 0); @@ -1167,7 +1167,7 @@ CMainWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) UINT state = GetMenuState(GetMenu(HWindow), CM_PREVDIFF, MF_BYCOMMAND); if (state & (MF_DISABLED | MF_GRAYED)) { - if (DifferencesCount > 0) // Petr: when I scroll the view somewhere else I want Alt+Arrow to focus the difference (hunting it manually is a pain); with just one diff it did not work at all, otherwise only by jumping to next/previous + if (DifferencesCount > 0) // Petr: if the view is scrolled elsewhere, Alt+Arrow should focus the difference; with only one difference this did not work at all, otherwise it worked only by switching to next/previous SelectDifference(SelectedDifference, CM_PREVDIFF); return 0; } @@ -1198,7 +1198,7 @@ CMainWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) UINT state = GetMenuState(GetMenu(HWindow), CM_NEXTDIFF, MF_BYCOMMAND); if (state & (MF_DISABLED | MF_GRAYED)) { - if (DifferencesCount > 0) // Petr: when I scroll the view somewhere else I want Alt+Arrow to focus the difference (hunting it manually is a pain); with just one diff it did not work at all, otherwise only by jumping previous/next + if (DifferencesCount > 0) // Petr: when the view is scrolled away, Alt+Arrow should focus the difference (finding it manually is a pain); with only one difference, it did not work at all, otherwise it only worked by switching to previous/next SelectDifference(SelectedDifference, CM_NEXTDIFF); return 0; } @@ -2228,10 +2228,11 @@ CMainWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_USER_ACTIVATEWINDOW: { - // if the window is disabled, a message box is likely sitting on top of it; - // bringing this window to the front would activate it (an issue in an older SS version - // where comparing identical files showed this window, then a message box about the match, - // and finally this message arrived, stealing focus from the box and activating the window underneath) + // if the window is disabled, a message box is likely displayed above it; + // bringing this window to the front would activate it (this happened in an older SS version + // when the user compared two identical files: this window appeared first, + // then a message box reporting the match popped up, and finally this message arrived, + // stealing focus from the message box and activating the window underneath) if (IsWindowEnabled(HWindow)) { ShowWindow(HWindow, ShowCmd /*SW_SHOW*/); diff --git a/src/plugins/filecomp/mtxtout.cpp b/src/plugins/filecomp/mtxtout.cpp index 2dc7b6c65..0947f87e0 100644 --- a/src/plugins/filecomp/mtxtout.cpp +++ b/src/plugins/filecomp/mtxtout.cpp @@ -49,7 +49,7 @@ bool FontHasChangedX(CChar* ViewerFontMapping, HDC memDC, int fontWidth, int fon rect.bottom = fontHeight; // NOTE: GetCharWidth32 still returns the same width for all characters, // although DrawTextEx does not! - if (DrawTextExX(memDC, ch, 1, &rect, DT_LEFT | DT_TOP | DT_CALCRECT | DT_NOPREFIX | DT_SINGLELINE | DT_NOCLIP, NULL)) // with DT_NOCLIP can be 2 x faster + if (DrawTextExX(memDC, ch, 1, &rect, DT_LEFT | DT_TOP | DT_CALCRECT | DT_NOPREFIX | DT_SINGLELINE | DT_NOCLIP, NULL)) // DT_NOCLIP can be up to 2x faster { if (rect.right - rect.left != fontWidth) { diff --git a/src/plugins/filecomp/mtxtout.h b/src/plugins/filecomp/mtxtout.h index 4ee383c51..499f5a1ad 100644 --- a/src/plugins/filecomp/mtxtout.h +++ b/src/plugins/filecomp/mtxtout.h @@ -63,7 +63,7 @@ class TMappedTextOut if (sizeof(CChar) > 1) CalcMappingIfNeeded(hdc, lpString, cbCount); const CChar* s = lpString; - if (cbCount >= BufferSize) // realloc buffer if needed + if (cbCount >= BufferSize) // Reallocate the buffer if needed { size_t newSize = __max(cbCount + 1, BufferSize * 2); CChar* buf = (CChar*)realloc(Buffer, newSize * sizeof(CChar)); diff --git a/src/plugins/filecomp/textio.cpp b/src/plugins/filecomp/textio.cpp index be43eea09..88f823447 100644 --- a/src/plugins/filecomp/textio.cpp +++ b/src/plugins/filecomp/textio.cpp @@ -207,7 +207,7 @@ bool CTextFileReader::IsValidUTF16(int endian) // U+FFFE and U+FFFF must not occur in normal UCS-4 data. // (see http://www.cl.cam.ac.uk/~mgk25/unicode.html) // - // Additionaly, we do not expect zero characters to appear in text files. + // Additionally, we do not expect zero characters to appear in text files. // if (c == 0 || c == 0xFFFE || c == 0xFFFF) { @@ -256,7 +256,7 @@ bool CTextFileReader::IsUTF16Text() int histOdd[256]; int histEven[256]; - // model probability density of odd and even bytes by 256-bin histograms + // Model the probability density of odd and even bytes using 256-bin histograms fill_n(histOdd, 256, 0); fill_n(histEven, 256, 0); int i = 0; @@ -292,8 +292,8 @@ bool CTextFileReader::IsUTF16Text() TRACE_I("Is valid UTF-16BE. " << isValidUTF16BE); if (isValidUTF16 && isValidUTF16BE) { - // determine endians by comparing entropy in odd and even bytes, the high - // order bytes should have lower entropy than low order bytes + // Determine endianness by comparing the entropy of odd and even bytes; the high- + // order bytes should have lower entropy than the low-order bytes double oe = 0, ee = 0; double p; // we normalize probabilities to have nonzero values by adding 1/256 to @@ -331,8 +331,8 @@ bool CTextFileReader::IsUTF16Text() bool CTextFileReader::IsUTF8Text() { - // TODO Use file prefix stored in `Buffer' to test whether the data are UTF-8 - // text file. `BufferedCharacters' tells ho many bytes is stored in `Buffer'. + // TODO Use the file prefix stored in `Buffer' to test whether the data are a UTF-8 + // text file. `BufferedCharacters' tells how many bytes are stored in `Buffer'. // do we have enough data for reliable reasoning? // TODO adjust the threshold as needed @@ -404,7 +404,7 @@ bool CTextFileReader::IsUTF8Text() } if (nUTF8 > 0) - { // At least one 2-or-more-bytes UTF8 sequence found and no invalid sequences found + { // At least one UTF-8 sequence of 2 bytes or more was found, and no invalid sequences were found Type = ftText; Encoding = encUTF8; } @@ -435,9 +435,9 @@ void CTextFileReader::EstimateFileType() } } - // if the test above did not recognize Unicode text file or we already know - // the file is text with know encoding but unknown input-enc table, we use - // RecognizeFileType from SS API + // If the test above did not recognize a Unicode text file, or if we already know + // the file is text with a known encoding but an unknown input-encoding table, we use + // RecognizeFileType from the SS API if (Type == ftUnknown || // unknown type Encoding == encUnknown || // text file, but unknown encoding // text file, known encoding, but unknown input-enc table @@ -526,7 +526,7 @@ void CTextFileReader::Get(char*& buffer, size_t& size, const int& cancel) if (Buffer == NULL || BufferSize < Size + 1) { - // reserve 1 char more at the end, for possible new-line insertion + // reserve one extra character at the end for possible newline insertion char* ret = (char*)realloc(Buffer, Size + 1); if (!ret) CFilecompWorker::CException::Raise(IDS_LOWMEM_TRY_BINARY, 0); @@ -645,7 +645,7 @@ void CTextFileReader::Get(wchar_t*& buffer, size_t& size, const int& cancel) // TODO // - // In addition to the encoding alternatives, Unicode also specifies various + // In addition to encoding alternatives, Unicode also defines various // Normalization Forms, which provide reasonable subsets of Unicode, // especially to ***REMOVE ENCODING AMBIGUITIES*** caused by the presence of // precomposed and compatibility characters: @@ -655,8 +655,8 @@ void CTextFileReader::Get(wchar_t*& buffer, size_t& size, const int& cancel) // // see the FoldString function in the Windows API // - // this has to be optional 'Ignore difference caused by unicode encoding - // ambiguilties', test for surrogates afterwards + // this has to be optional: 'Ignore differences caused by Unicode encoding + // ambiguities'; test for surrogates afterwards } template @@ -739,7 +739,7 @@ void CTextFileReader::ReadASCII8(wchar_t*& buffer, size_t& size, const int& canc int ret = 0; if (Size > 0) { - // estimage length + // estimate length ret = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, Buffer, int(Size), NULL, 0); if (ret == 0) CFilecompWorker::CException::Raise(IDS_ERRORUNICODE, GetLastError(), Name); @@ -749,7 +749,7 @@ void CTextFileReader::ReadASCII8(wchar_t*& buffer, size_t& size, const int& canc if (cancel) throw CFilecompWorker::CAbortByUserException(); - // reserve 1 char more at the end, for possible new-line insertion + // reserve one extra character at the end for possible newline insertion size = ret; buffer = (wchar_t*)malloc((size + 1) * sizeof(wchar_t)); if (!buffer) @@ -777,7 +777,7 @@ void CTextFileReader::ReadUTF8(wchar_t*& buffer, size_t& size, const int& cancel BufferedCharacters = 0; size_t allocated = Size; // worst case estimate (each UTF-8 byte codes one UCS-4 char) - // reserve 1 char more at the end, for possible new-line insertion + // reserve one extra character at the end for possible newline insertion buffer = (wchar_t*)malloc((allocated + 1) * sizeof(wchar_t)); if (!buffer) CFilecompWorker::CException::Raise(IDS_LOWMEM, 0); @@ -811,11 +811,11 @@ void CTextFileReader::ReadUTF8(wchar_t*& buffer, size_t& size, const int& cancel // U-00200000 – U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx // U-04000000 – U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - // we do not control if the code is correct, if the input has incorrect - // code, the resulting mapping is undefined + // We do not verify whether the encoding is correct; if the input contains + // invalid byte sequences, the resulting mapping is undefined. // - // we use masking by 0x3f instead of subtracking 0x80 to protect from - // invalid values in input coding + // We use masking with 0x3f instead of subtracting 0x80 to protect against + // invalid values in the input encoding. if (z <= 0x7F) utf32 = z; elif (z <= 0xDF) @@ -892,7 +892,7 @@ void CTextFileReader::ReadUTF8(wchar_t*& buffer, size_t& size, const int& cancel if (size + convertToSurrogates >= allocated) { allocated *= 2; - // reserve 1 char more at the end, for possible new-line insertion + // reserve one extra character at the end for possible newline insertion wchar_t* ret = (wchar_t*)realloc(buffer, (allocated + 1) * sizeof(wchar_t)); if (!ret) CFilecompWorker::CException::Raise(IDS_LOWMEM, 0); @@ -943,7 +943,7 @@ void CTextFileReader::ReadUTF16(wchar_t*& buffer, size_t& size, const int& cance } buffer = (wchar_t*)Buffer; - size = Size / 2; // TODO warn if byte is missing + size = Size / 2; // TODO warn if a byte is missing Buffer = NULL; // the buffer was passed to the caller BufferedCharacters = 0; @@ -967,7 +967,7 @@ void CTextFileReader::ReadUTF32(wchar_t*& buffer, size_t& size, const int& cance // needed) size_t allocated = Size / 4; - // reserve 1 char more at the end, for possible new-line insertion + // reserve one extra character at the end for possible newline insertion buffer = (wchar_t*)malloc((allocated + 1) * sizeof(wchar_t)); if (!buffer) CFilecompWorker::CException::Raise(IDS_LOWMEM, 0); @@ -1011,7 +1011,7 @@ void CTextFileReader::ReadUTF32(wchar_t*& buffer, size_t& size, const int& cance if (size + convertToSurrogates >= allocated) { allocated *= 2; - // reserve 1 char more at the end, for possible new-line insertion + // reserve one extra character at the end for possible newline insertion wchar_t* ret = (wchar_t*)realloc(buffer, (allocated + 1) * sizeof(wchar_t)); if (!ret) CFilecompWorker::CException::Raise(IDS_LOWMEM, 0); diff --git a/src/plugins/filecomp/todo.txt b/src/plugins/filecomp/todo.txt index 36ab3dd1d..4d7b69cbe 100644 --- a/src/plugins/filecomp/todo.txt +++ b/src/plugins/filecomp/todo.txt @@ -1,23 +1,24 @@ -Prekopavka --ignore differences caused by ambiguilties in unicode encoding --ShiftBoundaries: mozna optimalizovat pomoci listu --odstranit _ASSERT --vyhazet _CrtCheckMemory() --DiscardConfusingLines puvodni diff pouziva trik -- DiscardConfusingLines +CommentsTranslationProject: TRANSLATED -Prechod na Unicode: --hlasit uzivateli surrogates (zatim ne, teprve az budem umet korektne makat s asijskejma fontama) +Rework +- Ignore differences caused by ambiguities in Unicode encoding. +- ShiftBoundaries: perhaps optimize it using a list. +- Remove _ASSERT. +- Remove _CrtCheckMemory(). +- The original diff uses the DiscardConfusingLines trick. --Plug-in File Comparator porovn soubor se sebou samm, ani by uivatele - varoval, e dl cosi ne zrovna uitenho. - To bychom mohli detekovat a zobrazit nejaky messagebox, ne? - "There is same file in the left and right panel." Nebo neco takoveho? --Pridat feature, compare multiple files: - -najde prunik mnozin nazvu souboru z obou panelu - -rozdilne soubory vyleje do sesnamu ze ktereho pujde volat compare --zprehlednit help-keyboard strukturovat jako napovedu k less --nekomu se ztraceji ikonky v toolbare - Na zaver: File Comparator som spustil asi 10 - 12x - > z toho asi 3-4x ostal bez ikon, prikladam screen shot (.GIF) - > zobrazili sa bud pri znovu otvoreni FC alebo pri praci s nim. - > Prikladam REPERT o mojom SYSTEME: +Transition to Unicode: +- Report surrogate pairs to the user, but not yet; wait until we can work correctly with Asian fonts. + +- The File Comparator plug-in compares a file with itself without warning the user that this is not especially useful. + We could detect that and show a message box, for example: + "The same file is in the left and right panel." +- Add a feature to compare multiple files: + - Find the intersection of the file-name sets from both panels. + - Put the differing files into a list from which compare can be invoked. +- Clarify the keyboard-help section and structure it more like the less help. +- Toolbar icons disappear for some users. + Final note: I started File Comparator about 10 to 12 times. + > About 3 to 4 times it stayed without icons; I am attaching a screenshot (.GIF). + > They appeared either when FC was opened again or while working with it. + > I am attaching a report about my system. diff --git a/src/plugins/filecomp/viewwnd.cpp b/src/plugins/filecomp/viewwnd.cpp index 067c8719e..74747a3f6 100644 --- a/src/plugins/filecomp/viewwnd.cpp +++ b/src/plugins/filecomp/viewwnd.cpp @@ -454,7 +454,7 @@ CFileViewWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) SendMessage(HWindow, WM_HSCROLL, charsToScroll < 0 ? SB_LINEUP : SB_LINEDOWN, 0); } } - return TRUE; // the event is handled; do not emulate scrollbar clicking (happens when FALSE is returned) + return TRUE; // the event is handled; do not emulate scrollbar clicks (that happens when FALSE is returned) } case WM_RBUTTONUP: @@ -617,7 +617,7 @@ BOOL CTextFileViewWindowBase::RebuildScript( line = Script[0][*change].GetLine(); size_t context = Context; - if (line < size_t(Context)) // sometimes there is not enough lines + if (line < size_t(Context)) // sometimes there are not enough lines { size_t sline; if (((CTextFileViewWindowBase*)Siblink)->Script[0][*change].IsBlank()) @@ -999,7 +999,7 @@ void CTextFileViewWindowBase::UpdateSelection(int x, int y) { CALL_STACK_MESSAGE3("CTextFileViewWindowBase::UpdateSelection(%d, %d)", x, y); if (!DataValid || !Tracking) - return; // just to be safe + return; // defensive check if (x < LineNumWidth) x = LineNumWidth; if (y < 0) diff --git a/src/plugins/filecomp/viewwnd3.cpp b/src/plugins/filecomp/viewwnd3.cpp index b5a6c46ee..56e31a8ab 100644 --- a/src/plugins/filecomp/viewwnd3.cpp +++ b/src/plugins/filecomp/viewwnd3.cpp @@ -819,7 +819,7 @@ CHexFileViewWindow::CalculateOffset(int x, int y) if ((hOffs + FontWidth / 2) / FontWidth < BytesPerLine / 4 * 13) { - // Inside hexa block + // Inside the hex block //offset += (hOffs + FontWidth/2)/FontWidth/3; int i = ((hOffs + FontWidth / 2) / FontWidth + 2) / 13; int j = ((hOffs + FontWidth / 2 - i * 13 * FontWidth) / FontWidth + 1) / 3; diff --git a/src/plugins/filecomp/worker.cpp b/src/plugins/filecomp/worker.cpp index 3975e0e08..1fa497829 100644 --- a/src/plugins/filecomp/worker.cpp +++ b/src/plugins/filecomp/worker.cpp @@ -217,7 +217,7 @@ void CFilecompWorker::GuardedBody() for (i = 0; i <= 1; i++) { // Patera 2008.12.28: FILE_SHARE_WRITE added to support files locked by others - // NOTE: IntViewer can open such files, users wants FC to support them as well + // NOTE: IntViewer can open such files; users want FC to support them as well // See https://forum.altap.cz/viewtopic.php?t=2675 // See also CHexFileViewWindow::SetData() Files[i].File = CreateFile(Files[i].Name, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, diff --git a/src/plugins/filecomp/worker2.cpp b/src/plugins/filecomp/worker2.cpp index b56ed3d9d..36ca6d150 100644 --- a/src/plugins/filecomp/worker2.cpp +++ b/src/plugins/filecomp/worker2.cpp @@ -331,7 +331,7 @@ int CFilecompWorker::FindDifferencesBody(CCachedFile (&cf)[2], QWORD changeOffs, } } - // compare data in chunks of the requested size + // compare data in blocks of the requested size DWORD size = (DWORD)__min(blokSize, remain); ptr0 = cf[0].ReadBuffer(offset, size, CancelFlag); @@ -371,5 +371,5 @@ int CFilecompWorker::FindDifferencesBody(CCachedFile (&cf)[2], QWORD changeOffs, } } - return 0; // succes + return 0; // success } diff --git a/src/plugins/folders/dialogs.cpp b/src/plugins/folders/dialogs.cpp index 16ec79e52..668b625a2 100644 --- a/src/plugins/folders/dialogs.cpp +++ b/src/plugins/folders/dialogs.cpp @@ -26,7 +26,7 @@ CCommonDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) // horizontally and vertically center the dialog relative to the parent if (Parent != NULL) SalamanderGeneral->MultiMonCenterWindow(HWindow, Parent, TRUE); - break; // request focus from DefDlgProc + break; // let DefDlgProc set the focus } } return CDialog::DialogProc(uMsg, wParam, lParam); diff --git a/src/plugins/folders/folders.cpp b/src/plugins/folders/folders.cpp index c11781f25..a9e1a78ca 100644 --- a/src/plugins/folders/folders.cpp +++ b/src/plugins/folders/folders.cpp @@ -76,12 +76,12 @@ CPluginInterfaceAbstract* WINAPI SalamanderPluginEntry(CSalamanderPluginEntryAbs { // reject older versions MessageBox(salamander->GetParentWindow(), REQUIRE_LAST_VERSION_OF_SALAMANDER, - "Folders" /* neprekladat! */, MB_OK | MB_ICONERROR); + "Folders" /* do not translate */, MB_OK | MB_ICONERROR); return NULL; } // load the language module (.slg) - HLanguage = salamander->LoadLanguageModule(salamander->GetParentWindow(), "Folders" /* neprekladat! */); + HLanguage = salamander->LoadLanguageModule(salamander->GetParentWindow(), "Folders" /* do not translate */); if (HLanguage == NULL) return NULL; @@ -91,7 +91,7 @@ CPluginInterfaceAbstract* WINAPI SalamanderPluginEntry(CSalamanderPluginEntryAbs // obtain the interface providing customized Windows controls used in Salamander SalamanderGUI = salamander->GetSalamanderGUI(); - if (!InitializeWinLib("Folders" /* neprekladat! */, DLLInstance)) + if (!InitializeWinLib("Folders" /* do not translate */, DLLInstance)) return NULL; SetWinLibStrings("Invalid number!", LoadStr(IDS_PLUGINNAME)); @@ -101,7 +101,7 @@ CPluginInterfaceAbstract* WINAPI SalamanderPluginEntry(CSalamanderPluginEntryAbs VERSINFO_VERSION_NO_PLATFORM, VERSINFO_COPYRIGHT, LoadStr(IDS_PLUGIN_DESCRIPTION), - "FOLDERS" /* neprekladat! */, NULL, "fld"); + "FOLDERS" /* do not translate */, NULL, "fld"); salamander->SetPluginHomePageURL("www.altap.cz"); diff --git a/src/plugins/folders/fs1.cpp b/src/plugins/folders/fs1.cpp index ed4c97a24..ae7647558 100644 --- a/src/plugins/folders/fs1.cpp +++ b/src/plugins/folders/fs1.cpp @@ -121,7 +121,7 @@ CPluginInterfaceForFS::ExecuteOnFS(int panel, CPluginFSInterfaceAbstract* plugin IShellFolder* newFolder; LPITEMIDLIST newPIDL; - if (isDir == 2) // up-dir + if (isDir == 2) // parent directory { if (CutLastItemFromIL(fs->CurrentPIDL, &newFolder, &newPIDL)) { @@ -311,9 +311,9 @@ CPluginDataInterface::CompareFilesFromFS(const CFileData* file1, const CFileData if (pidl1 == pidl2) return 0; if (pidl1 == NULL) - return -1; // the ".." directory arrives here and has pidl==NULL + return -1; // the ".." directory ends up here with pidl==NULL if (pidl2 == NULL) - return 1; // the ".." directory arrives here and has pidl==NULL + return 1; // the ".." directory ends up here with pidl==NULL while (1) { @@ -330,7 +330,7 @@ CPluginDataInterface::CompareFilesFromFS(const CFileData* file1, const CFileData if (end2->mkid.cb == 0) return 0; // PIDLs are identical else - return -1; // the first PIDL is shorter, thus "lesser" + return -1; // the first PIDL is shorter, so it is "less" } else { diff --git a/src/plugins/folders/fs2.cpp b/src/plugins/folders/fs2.cpp index 0ae966a6d..f69d42a46 100644 --- a/src/plugins/folders/fs2.cpp +++ b/src/plugins/folders/fs2.cpp @@ -19,7 +19,7 @@ CPluginFSInterface::CPluginFSInterface() // Desktop -> CurrentPIDL if (FAILED(SHGetSpecialFolderLocation(NULL, CSIDL_DESKTOP, &CurrentPIDL))) { - // the Desktop PIDL is empty, but we obtain it cleanly + // The Desktop PIDL is an empty PIDL, but we still obtain it explicitly CurrentPIDL = NULL; TRACE_E("SHGetSpecialFolderLocation failed on CSIDL_DESKTOP"); } @@ -90,7 +90,7 @@ BOOL WINAPI CPluginFSInterface::GetFullName(CFileData& file, int isDir, char* buf, int bufSize) { buf[0] = 0; - // lstrcpyn(buf, Path, bufSize); // if the path does not fit, the name definitely will not either (an error will be reported) + // lstrcpyn(buf, Path, bufSize); // if the path does not fit, the name definitely will not fit either (an error will be reported) if (isDir == 2) return SalamanderGeneral->CutDirectory(buf, NULL); // up-dir else @@ -132,7 +132,7 @@ CPluginFSInterface::ChangePath(int currentFSNameIndex, char* fsName, int fsNameI if (ErrorState == fesFatal) { ErrorState = fesOK; - return FALSE; // ListCurrentPath failed due to memory, fatal error + return FALSE; // ListCurrentPath failed due to insufficient memory, fatal error } return TRUE; diff --git a/src/plugins/ftp/ctrlcon.h b/src/plugins/ftp/ctrlcon.h index 0efd1a333..292132b56 100644 --- a/src/plugins/ftp/ctrlcon.h +++ b/src/plugins/ftp/ctrlcon.h @@ -12,10 +12,10 @@ // returns 'buf' char* CopyStr(char* buf, int bufSize, const char* txt, int size); -// helper function for decomposing a string with initial FTP commands (separated by ';') +// helper function for splitting a string with initial FTP commands (separated by ';') // into individual commands; returns TRUE if another command is available (the // command is returned in 's'); 'next' is an IN/OUT variable, initialize it to -// the start of the string and leave it unchanged between calls to GetToken +// the start of the string and do not modify it between calls to GetToken BOOL GetToken(char** s, char** next); // command codes for PrepareFTPCommand (parameters in [] are passed through the ellipsis) @@ -53,7 +53,7 @@ enum CFtpCmdCode BOOL PrepareFTPCommand(char* buf, int bufSize, char* logBuf, int logBufSize, CFtpCmdCode ftpCmd, int* cmdLen, ...); -// helper function for preparing error texts +// helper function for preparing error messages const char* GetFatalErrorTxt(int fatalErrorTextID, char* errBuf); // helper function for preparing error texts const char* GetOperationFatalErrorTxt(int opFatalError, char* errBuf); @@ -164,13 +164,13 @@ class CLogData unsigned short Port; // port used on the server char* User; // user name - BOOL CtrlConOrWorker; // TRUE/FALSE = logging the "control connection" from the panel / from a worker + BOOL CtrlConOrWorker; // TRUE/FALSE = the "control connection" log is from the panel / from a worker BOOL WorkerIsAlive; // TRUE/FALSE = the worker exists / no longer exists // the "control connection" we are logging (NULL == FS no longer exists); // WARNING: we must not access the "control connection" object - nesting critical sections is forbidden CControlConnectionSocket* CtrlCon; BOOL Connected; // TRUE/FALSE == active/inactive "control connection" (panel and worker) - int DisconnectNum; // if (CtrlCon==NULL && !WorkerIsAlive), holds the number describing how old the dead log is (so that we always delete starting from the longest dead log) + int DisconnectNum; // if (CtrlCon==NULL && !WorkerIsAlive), holds how long the log has been dead (so that we always delete the log that has been dead the longest first) CDynString Text; // the actual log text int SkippedChars; // number of skipped characters since the last output to the edit window in Logs @@ -244,9 +244,9 @@ class CLogs // called after logging parameters change in the configuration void ConfigChanged(); - // adds logs to the combo box; returns the focus in 'focusIndex' (must not be NULL) based on - // 'prevItemUID' (the UID of the item we want to select, it may also be -1); if 'prevItemUID' - // is not found, it returns -1 in 'focusIndex'; in 'empty' (must not be NULL) it returns TRUE if + // adds logs to the combo box; stores the focus index in 'focusIndex' (must not be NULL) based on + // 'prevItemUID' (the UID of the item to select, which may also be -1); if 'prevItemUID' + // is not found, it stores -1 in 'focusIndex'; stores TRUE in 'empty' (must not be NULL) if // no logs exist void AddLogsToCombo(HWND combo, int prevItemUID, int* focusIndex, BOOL* empty); @@ -357,14 +357,14 @@ class CListingCache CListingCache(); ~CListingCache(); - // returns TRUE if a usable listing of the path 'path' (of type 'pathType') is available on the - // server 'host', where user 'user' is connected on port 'port'; the listing is returned in the - // allocated string 'cachedListing' (must not be NULL; returning NULL means an allocation error), - // the string length is returned in 'cachedListingLen' (must not be NULL); the caller is - // responsible for deallocation; the date when the listing was captured is returned in - // 'cachedListingDate' (must not be NULL); 'path' returns the exact text of the cached path (as - // provided by the server when it was inserted into the cache); 'path' is a buffer of size - // 'pathBufSize' bytes + // returns TRUE if a usable listing of path 'path' (of type 'pathType') is available on server + // 'host' for user 'user' connected on port 'port'; the listing is returned in an allocated + // string via 'cachedListing' (the parameter must not be NULL; a NULL returned pointer + // indicates a memory allocation error), its length is returned in 'cachedListingLen' (must not + // be NULL); the caller is responsible for deallocation; the date when the listing was captured + // is returned in 'cachedListingDate' (must not be NULL); 'path' receives the exact text of the + // cached path (as returned by the server when it was inserted into the cache); 'path' is a + // buffer of size 'pathBufSize' bytes // can be called from any thread BOOL GetPathListing(const char* host, unsigned short port, const char* user, CFTPServerPathType pathType, char* path, int pathBufSize, @@ -493,9 +493,9 @@ class CSendCmdUserIfaceAbstract // CanFinishSending() that // returns FALSE virtual void HandleDataConTimeout(DWORD* start) = 0; // called only if - // BeforeWaitingForFinish - // returns TRUE in - // 'useTimeout' + // BeforeWaitingForFinish() + // sets 'useTimeout' to + // TRUE virtual HANDLE GetFinishedEvent() = 0; // once it is signaled, // CanFinishSending() is // tested again @@ -881,21 +881,21 @@ class CControlConnectionSocket : public CSocket // checks whether 'ServerSystem' contains the name 'systemName' BOOL IsServerSystem(const char* systemName); - // if the "control connection" is closed, offers the user to reopen it (WARNING: does not set the - // working directory on the server); returns TRUE when the "control connection" is ready for use, - // and in that case sets SetStartTime() (so further waiting can continue after a possible - // reconnect); 'notInPanel' is TRUE for a detached FS (not in a panel); if 'notInPanel' is FALSE, - // the connection is in a panel - if 'leftPanel' is TRUE it is the left panel, otherwise the right - // panel; 'parent' is the thread's foreground window (after ESC is pressed it is used to detect - // whether ESC was pressed in this window and not, for example, in another application; in the - // main thread this is SalamanderGeneral->GetMsgBoxParent() or a dialog opened by the plugin); - // 'parent' is also the parent of any error message boxes; 'userBuf' + 'userBufSize' is the buffer - // for a new user name on the FTP server (it may change during reconnect); 'reconnected' (if not - // NULL) returns TRUE when the connection was restored (the "control connection" was reopened); if - // 'setStartTimeIfConnected' is FALSE and reconnecting is unnecessary, SetStartTime() is not set; - // 'totalAttemptNum' + 'retryMsg' + 'reconnectErrResID' + 'useFastReconnect' are parameters for - // StartControlConnection(); 'userRejectsReconnect' (if not NULL) returns TRUE if the user refuses - // to perform a reconnect + // if the "control connection" is closed, offers to reopen it (WARNING: does not set the + // working directory on the server); returns TRUE if the "control connection" is ready for use, + // and in that case also sets SetStartTime() (so any further waiting can continue after a possible + // reconnect); 'notInPanel' is TRUE for a detached file system (not in a panel); if 'notInPanel' + // is FALSE, the connection is in a panel - if 'leftPanel' is TRUE, it is the left panel; + // otherwise it is the right panel; 'parent' is the thread's foreground window (after ESC is + // pressed, it is used to detect whether ESC was pressed in this window and not, for example, in + // another application; in the main thread this is SalamanderGeneral->GetMsgBoxParent() or a + // dialog opened by the plugin); 'parent' is also the parent of any error message boxes; + // 'userBuf' + 'userBufSize' is a buffer for the new user name on the FTP server (it may change + // during reconnect); 'reconnected' (if not NULL) returns TRUE if the connection was restored (the + // "control connection" was reopened); if 'setStartTimeIfConnected' is FALSE and reconnecting is + // not needed, SetStartTime() is not set; 'totalAttemptNum' + 'retryMsg' + + // 'reconnectErrResID' + 'useFastReconnect' are parameters for StartControlConnection(); + // 'userRejectsReconnect' (if not NULL) returns TRUE if the user refuses to reconnect // can be called only from the main thread (uses wait windows, etc.) BOOL ReconnectIfNeeded(BOOL notInPanel, BOOL leftPanel, HWND parent, char* userBuf, int userBufSize, BOOL* reconnected, BOOL setStartTimeIfConnected, @@ -903,8 +903,8 @@ class CControlConnectionSocket : public CSocket BOOL* userRejectsReconnect, int reconnectErrResID, BOOL useFastReconnect); - // sends a command to the FTP server and returns the server's reply (WARNING: does not return - // replies of type FTP_D1_MAYBESUCCESS - it automatically waits for the next server reply); + // sends a command to the FTP server and returns the server's reply (WARNING: replies of type + // FTP_D1_MAYBESUCCESS are not returned - it automatically waits for the next server reply); // 'parent' is the thread's foreground window (after ESC is pressed it is used to detect whether // ESC was pressed in this window and not, for example, in another application; in the main thread // this is SalamanderGeneral->GetMsgBoxParent() or a dialog opened by the plugin); 'parent' is also @@ -915,25 +915,25 @@ class CControlConnectionSocket : public CSocket // first ESC sends "ABOR" (probably only makes sense for commands with a data connection) and the // connection is aborted only after the second ESC; if 'allowCmdAbort' is FALSE, the connection is // aborted after the first ESC; if 'resetWorkingPathCache' is TRUE, ResetWorkingPathCache() is - // called after sending the command (used when the command may change the current working - // directory); if 'resetCurrentTransferModeCache' is TRUE, ResetCurrentTransferModeCache() is called - // after sending the command (used when the command may change the current transfer mode); returns - // TRUE if sending the command or aborting it and receiving the reply succeeded; 'cmdAborted' - // (if not NULL) returns TRUE when the command was successfully aborted; the reply code is returned - // in 'ftpReplyCode' (must not be NULL) - it is valid (!=-1) even when 'cmdAborted' == TRUE; the + // called after sending the command (used when the command may change the current working path); + // if 'resetCurrentTransferModeCache' is TRUE, ResetCurrentTransferModeCache() is called after + // sending the command (used when the command may change the current transfer mode); returns TRUE + // if sending the command or aborting it and receiving the reply succeeded; 'cmdAborted' (if not + // NULL) returns TRUE when the command was successfully aborted; the reply code is returned in + // 'ftpReplyCode' (must not be NULL) - it is valid (!=-1) even when 'cmdAborted' == TRUE; the // reply text is stored in the buffer 'ftpReplyBuf' (maximum size 'ftpReplyBufSize'), // null-terminated - if it is longer than the buffer, it is simply truncated; if - // 'specialUserInterface' is NULL, the standard wait window is used for the user interface, - // otherwise the object provided via 'specialUserInterface' should be used (for example when - // listing the current path); - // returns FALSE if the connection was interrupted (on timeout it automatically closes the - // connection hard - sending "QUIT" makes no sense); if 'canRetry' is not NULL, the error text can - // be returned in 'retryMsg' (buffer of size 'retryMsgBufSize') - 'canRetry' returns TRUE; otherwise - // the error is shown in a message box ('canRetry' is either NULL or FALSE is returned there); - // can be called only from the main thread (uses wait windows, etc.) + // 'specialUserInterface' is NULL, the standard wait window is used for the user interface; + // otherwise, the object provided via 'specialUserInterface' is used (for example when listing the + // current path); + // returns FALSE if the connection is interrupted (on timeout it automatically forcibly closes the + // connection - sending "QUIT" makes no sense); if 'canRetry' is not NULL, the error text may be + // returned in 'retryMsg' (a buffer of size 'retryMsgBufSize') and TRUE is returned in 'canRetry'; + // otherwise, the error is shown in a message box ('canRetry' is either NULL or FALSE is returned + // in it); can be called only from the main thread (uses wait windows, etc.) // - // WARNING: when aborting commands ('allowCmdAbort'==TRUE) the system for receiving server replies - // is not fully resolved (servers return either one reply just for ABOR or two replies + // WARNING: when aborting commands ('allowCmdAbort'==TRUE), the handling of server replies is not + // fully resolved (servers return either one reply just for ABOR or two replies // (list + abort); unfortunately both use code 226, so it is impossible to tell which case // occurred) - this is handled by trying to receive everything the server sends in one // packet (it probably sends both replies together); any additional replies are ignored as @@ -1061,20 +1061,20 @@ class CControlConnectionSocket : public CSocket char* userBuf, int userBufSize, BOOL isVMS, BOOL isDir); // sends a request to open a "listen" port (either on the local machine or on the proxy server) for - // the data connection 'dataConnection'; inputs 'listenOnIP' + 'listenOnPort' specify the IP+port - // where the "listen" port should be opened (makes sense only without a proxy server); - // 'parent' is the thread's foreground window (after ESC is pressed it is used to detect whether ESC + // the data connection 'dataConnection'; on input, 'listenOnIP' + 'listenOnPort' specify the IP+port + // where the "listen" port should be opened (relevant only without a proxy server); + // 'parent' is the thread's foreground window (after ESC is pressed, it is used to detect whether ESC // was pressed in this window and not, for example, in another application; in the main thread this // is SalamanderGeneral->GetMsgBoxParent() or a dialog opened by the plugin); 'parent' is also the // parent of any error message boxes; 'waitWndTime' is the delay before displaying the wait window; - // returns TRUE on success - 'listenOnIP' + 'listenOnPort' then contain the IP+port where we wait - // for the FTP server to connect; returns FALSE if an interruption or error occurred; if retrying is - // meaningful, the connection is forcibly closed (we could send "QUIT", but for now we simplify - // our lives) and the error text is returned in 'retryMsg' (buffer of size 'retryMsgBufSize', must - // not be 0) and 'canRetry' (must not be NULL) returns TRUE; if retrying makes no sense, the error - // is shown in a message box and 'canRetry' returns FALSE (the connection is not interrupted); - // 'errBuf' is a helper buffer of size 'errBufSize' (must not be 0) - used for texts displayed in - // message boxes; + // returns TRUE on success - 'listenOnIP' + 'listenOnPort' then contain the IP+port where the + // connection from the FTP server is expected; returns FALSE if an interruption or error occurs; if + // retrying makes sense, the connection is forcibly closed ("QUIT" could be sent instead, but this is + // kept simpler for now), the error text is returned in 'retryMsg' (buffer of size 'retryMsgBufSize', + // must not be 0), and 'canRetry' (must not be NULL) returns TRUE; if retrying does not make sense, + // the error is shown in a message box and 'canRetry' returns FALSE (the connection is not + // interrupted); 'errBuf' is a helper buffer of size 'errBufSize' (must not be 0), used for texts + // displayed in message boxes; // can be called only from the main thread (uses wait windows, etc.) BOOL OpenForListeningAndWaitForRes(HWND parent, CDataConnectionSocket* dataConnection, DWORD* listenOnIP, unsigned short* listenOnPort, @@ -1229,7 +1229,7 @@ class CClosedCtrlConChecker protected: CRITICAL_SECTION DataSect; // critical section for accessing the object's data - // array of closed sockets that we check (whenever FTPCMD_CLOSECONNOTIF is received) + // array of closed sockets to check (whenever FTPCMD_CLOSECONNOTIF is received) TIndirectArray CtrlConSockets; BOOL CmdNotPost; // FALSE if the FTPCMD_CLOSECONNOTIF command has already been posted diff --git a/src/plugins/ftp/ctrlcon1.cpp b/src/plugins/ftp/ctrlcon1.cpp index b215277b9..9c99b2205 100644 --- a/src/plugins/ftp/ctrlcon1.cpp +++ b/src/plugins/ftp/ctrlcon1.cpp @@ -118,9 +118,9 @@ CControlConnectionSocket::~CControlConnectionSocket() HANDLES(CloseHandle(NewEvent)); HANDLES(DeleteCriticalSection(&EventCritSect)); - // Logs cannot touch the "control connection" (nested critical sections are forbidden), - // this call synchronizes only the validity of the pointer to the "control connection" (not the object contents, - // therefore it can be at the very end of the destructor) + // Logs cannot access the "control connection" (nested critical sections are forbidden), + // this call synchronizes only the validity of the pointer to the "control connection" (not the object contents, + // so it can be at the very end of the destructor) if (LogUID != -1) Logs.ClosingConnection(LogUID); } @@ -227,7 +227,7 @@ void CControlConnectionSocket::WaitForEventOrESC(HWND parent, CControlConnection CALL_STACK_MESSAGE3("CControlConnectionSocket::WaitForEventOrESC(, , , , %d, , , %d)", milliseconds, waitForUserIfaceFinish); - const DWORD cycleTime = 200; // period of testing the ESC key press in ms (200 = 5 times per second) + const DWORD cycleTime = 200; // ESC key polling interval in ms (200 = 5 times per second) DWORD timeStart = GetTickCount(); DWORD restOfWaitTime = milliseconds; // remaining waiting time @@ -263,7 +263,7 @@ void CControlConnectionSocket::WaitForEventOrESC(HWND parent, CControlConnection DWORD waitRes = MsgWaitForMultipleObjects(1, &watchedEvent, FALSE, waitTime, QS_ALLINPUT); // first check for ESC press (so we do not ignore it for the user) - if (milliseconds != 0 && // if the timeout is zero, we are only pumping messages, ignore ESC + if (milliseconds != 0 && // if the timeout is zero, we are only pumping messages; do not handle ESC ((GetAsyncKeyState(VK_ESCAPE) & 0x8001) && GetForegroundWindow() == parent || // ESC key pressed waitWnd != NULL && waitWnd->GetWindowClosePressed() || // close button in the wait window userIface != NULL && userIface->GetWindowClosePressed())) // close button in the user interface @@ -314,7 +314,7 @@ void CControlConnectionSocket::WaitForEventOrESC(HWND parent, CControlConnection *event = ccsevTimeout; // no time remains *data1 = 0; *data2 = 0; - break; // report timeout + break; // report a timeout } } } @@ -351,7 +351,7 @@ void CControlConnectionSocket::SetConnectionParameters(const char* host, unsigne ProxyServer = NULL; else { - ProxyServer = Config.FTPProxyServerList.MakeCopyOfProxyServer(proxyServerUID, NULL); // ignore lack of memory (automatically "not used (direct connection)") + ProxyServer = Config.FTPProxyServerList.MakeCopyOfProxyServer(proxyServerUID, NULL); // ignore out-of-memory; it will automatically be "not used (direct connection)" if (ProxyServer != NULL) { if (ProxyServer->ProxyEncryptedPassword != NULL) @@ -415,8 +415,8 @@ enum CStartCtrlConStates // states of the automaton for CControlConnectionSocket // connect to the FTP server (retrieved IP is in 'auxServerIP') sccsConnect, - // retry the connection (based on Config.DelayBetweenConRetries + Config.ConnectRetries), - // if it should not retry anymore, it transitions to the state from 'noRetryState' + if 'fastRetry' is TRUE, it must not + // retry the connection (according to Config.DelayBetweenConRetries and Config.ConnectRetries), + // if it should no longer retry, it transitions to the state from 'noRetryState' + if 'fastRetry' is TRUE, it must not // wait before the next attempt sccsRetry, @@ -432,7 +432,7 @@ enum CStartCtrlConStates // states of the automaton for CControlConnectionSocket // retry the login (without waiting and losing the connection) - only transitions to sccsStartLoginScript - cannot be used with a proxy server!!! sccsRetryLogin, - // end of the method (successful or unsuccessful - according to 'ret' TRUE/FALSE) + // end of the method (successful or unsuccessful, depending on whether 'ret' is TRUE or FALSE) sccsDone }; @@ -562,7 +562,7 @@ BOOL CControlConnectionSocket::StartControlConnection(HWND parent, char* user, i if (serverTimeout < 1000) serverTimeout = 1000; // at least one second - // store the focus from 'parent' (if the focus is not from 'parent', store NULL) + // remember the focused window in 'parent' (store NULL if the focus is not within 'parent') HWND focusedWnd = GetFocus(); HWND hwnd = focusedWnd; while (hwnd != NULL && hwnd != parent) @@ -594,13 +594,13 @@ BOOL CControlConnectionSocket::StartControlConnection(HWND parent, char* user, i { const char* txt = GetProxyScriptText(proxyType, FALSE); if (txt[0] == 0) - txt = GetProxyScriptText(fpstNotUsed, FALSE); // undefined script = "not used (direct connection)" script - SOCKS 4/4A/5, HTTP 1.1 + txt = GetProxyScriptText(fpstNotUsed, FALSE); // no script defined = the "not used (direct connection)" script - SOCKS 4/4A/5, HTTP 1.1 lstrcpyn(proxyScriptText, txt, PROXYSCRIPT_MAX_SIZE); } DWORD auxServerIP = ServerIP; srvAddr.s_addr = auxServerIP; - ResetWorkingPathCache(); // after connecting to the server it is necessary to determine the working dir - ResetCurrentTransferModeCache(); // after connecting to the server it is necessary to set the transfer mode (it should be ASCII, but we do not trust it) + ResetWorkingPathCache(); // after connecting to the server, the working directory must be determined + ResetCurrentTransferModeCache(); // after connecting to the server, the transfer mode must be set (it should be ASCII, but that is not trusted) HANDLES(LeaveCriticalSection(&SocketCritSect)); const char* proxyScriptExecPoint = NULL; @@ -630,7 +630,7 @@ BOOL CControlConnectionSocket::StartControlConnection(HWND parent, char* user, i CStartCtrlConStates state = (auxServerIP == INADDR_NONE ? sccsGetIP : sccsConnect); - if (retryMsg != NULL) // simulate the state when the connection was interrupted directly in this method - "retry" connection + if (retryMsg != NULL) // simulate the state as if the connection had been interrupted directly in this method - retry the connection { lstrcpyn(errBuf, retryMsg, 300); // store the retry message in errBuf (for sccsOperationFatalError) opFatalErrorTextID = reconnectErrResID != -1 ? reconnectErrResID : IDS_SENDCOMMANDERROR; @@ -645,7 +645,7 @@ BOOL CControlConnectionSocket::StartControlConnection(HWND parent, char* user, i if (ProcessProxyScript(proxyScriptText, &proxyScriptExecPoint, proxyLastCmdReply, &proxyScriptParams, host, &port, NULL, NULL, errBuf2, NULL)) { - if (proxyScriptParams.NeedUserInput()) // theoretically should not happen + if (proxyScriptParams.NeedUserInput()) // should theoretically not happen { // only proxyScriptParams->NeedProxyHost can be TRUE (otherwise ProcessProxyScript would return an error) strcpy(errBuf, LoadStr(IDS_PROXYSRVADREMPTY)); lstrcpyn(errBuf, errBuf2, 300); @@ -656,7 +656,7 @@ BOOL CControlConnectionSocket::StartControlConnection(HWND parent, char* user, i else proxyScriptStartExecPoint = proxyScriptExecPoint; } - else // theoretically should never happen (saved scripts are validated) + else // this should theoretically never happen (saved scripts are validated) { lstrcpyn(errBuf, errBuf2, 300); opFatalError = -1; // error is directly in errBuf @@ -673,7 +673,7 @@ BOOL CControlConnectionSocket::StartControlConnection(HWND parent, char* user, i { case sccsGetIP: // obtain an IP address from the textual address of the FTP server { - if (!GetHostByAddress(host, 0)) // must be outside the SocketCritSect section + if (!GetHostByAddress(host, 0)) // must be outside the SocketCritSect critical section { // no chance of success -> report an error sprintf(formatBuf, LoadStr(IDS_GETIPERROR), host); opFatalErrorTextID = -1; // the text is in 'formatBuf' @@ -727,7 +727,7 @@ BOOL CControlConnectionSocket::StartControlConnection(HWND parent, char* user, i case ccsevIPReceived: // data1 == IP, data2 == error { - if (data1 != INADDR_NONE) // we have an IP + if (data1 != INADDR_NONE) // we have the IP address { HANDLES(EnterCriticalSection(&SocketCritSect)); auxServerIP = ServerIP = data1; @@ -814,7 +814,7 @@ BOOL CControlConnectionSocket::StartControlConnection(HWND parent, char* user, i ResetBuffersAndEvents(); // empty the buffers (discard old data) and discard old events if (useWelcomeMessage) - welcomeMessage.Clear(); // clear the previous attempt (only makes sense after a "retry") + welcomeMessage.Clear(); // clear the welcome message from the previous attempt (only makes sense after a "retry") if ((proxyType == fpstSocks5 || proxyType == fpstHTTP1_1) && proxyScriptParams.ProxyUser[0] != 0 && proxyScriptParams.ProxyPassword[0] == 0) @@ -825,7 +825,7 @@ BOOL CControlConnectionSocket::StartControlConnection(HWND parent, char* user, i proxyScriptParams.ProxyPassword, PASSWORD_MAX_SIZE, TRUE, connectingToAs, FALSE) .Execute() != IDCANCEL) - { // value change -> we must update the originals as well + { // value changed -> we must update the originals as well HANDLES(EnterCriticalSection(&SocketCritSect)); if (ProxyServer != NULL) ProxyServer->SetProxyPassword(proxyScriptParams.ProxyPassword); @@ -887,7 +887,7 @@ BOOL CControlConnectionSocket::StartControlConnection(HWND parent, char* user, i fatalErrorTextID = -1; // the description is directly in 'errBuf' else fatalErrorTextID = IDS_OPENCONTIMEOUT; - noRetryState = sccsFatalError; // if retry is not performed, execute sccsFatalError + noRetryState = sccsFatalError; // if retry is not performed, transition to sccsFatalError state = sccsRetry; break; } @@ -906,12 +906,12 @@ BOOL CControlConnectionSocket::StartControlConnection(HWND parent, char* user, i sprintf(formatBuf, LoadStr(IDS_OPENCONERROR), host, inet_ntoa(srvAddr), port); } opFatalErrorTextID = -1; // the text is in 'formatBuf' - noRetryState = sccsOperationFatalError; // if retry is not performed, execute sccsOperationFatalError + noRetryState = sccsOperationFatalError; // if retry is not performed, transition to sccsOperationFatalError if (opFatalError == -1 && errBuf[0] == 0) // simple error -> convert it to sccsFatalError { fatalErrorTextID = -1; lstrcpyn(errBuf, formatBuf, 300); - noRetryState = sccsFatalError; // if retry is not performed, execute sccsFatalError + noRetryState = sccsFatalError; // if retry is not performed, transition to sccsFatalError } state = sccsRetry; } @@ -931,14 +931,14 @@ BOOL CControlConnectionSocket::StartControlConnection(HWND parent, char* user, i opFatalError = error; sprintf(formatBuf, LoadStr(IDS_OPENCONERROR), host, inet_ntoa(srvAddr), port); opFatalErrorTextID = -1; // the text is in 'formatBuf' - noRetryState = sccsOperationFatalError; // if retry is not performed, execute sccsOperationFatalError + noRetryState = sccsOperationFatalError; // if retry is not performed, transition to sccsOperationFatalError state = sccsRetry; } break; } case sccsRetry: // try connecting again (based on Config.DelayBetweenConRetries + Config.ConnectRetries), - { // if it should no longer try, transition to the state from 'noRetryState' + if 'fastRetry' is TRUE, + { // if no more retries should be attempted, transition to the state in 'noRetryState'; if 'fastRetry' is TRUE, // do not wait before the next attempt // Resend AUTH TLS if needed if (EncryptControlConnection) @@ -984,7 +984,7 @@ BOOL CControlConnectionSocket::StartControlConnection(HWND parent, char* user, i *s1 = 0; // trim end-of-line characters from the last error text // when the server closes the control connection, keep-alive changes to 'kamNone', therefore: - // prepare keep-alive for further use + set keep-alive to 'kamForbidden' (a normal command is in progress) + // prepare keep-alive for further use and set it to 'kamForbidden' (a normal command is in progress) ReleaseKeepAlive(); WaitForEndOfKeepAlive(parent, 0); // cannot open the wait window (it is in the 'kamNone' state) @@ -995,7 +995,7 @@ BOOL CControlConnectionSocket::StartControlConnection(HWND parent, char* user, i // if necessary, close the socket; the system will attempt a graceful shutdown (we will not learn the result) CloseSocket(NULL); Logs.SetIsConnected(logUID, IsConnected()); - Logs.RefreshListOfLogsInLogsDlg(); // display "connection inactive" + Logs.RefreshListOfLogsInLogsDlg(); // "connection inactive" in the log state = sccsConnect; // try to connect again (the IP is already known) } @@ -1044,7 +1044,7 @@ BOOL CControlConnectionSocket::StartControlConnection(HWND parent, char* user, i s++; if (*s == '\n') { - if (*(s + 1) == '\n') // remove an empty line in the text + if (*(s + 1) == '\n') // remove the empty line in the text memmove(s, s + 1, strlen(s + 1) + 1); s++; } @@ -1075,7 +1075,7 @@ BOOL CControlConnectionSocket::StartControlConnection(HWND parent, char* user, i if (now - start < (DWORD)delayBetweenConRetries * 1000) { // rebuild the text for the retry wait window (contains the countdown) DWORD wait = delayBetweenConRetries * 1000 - (now - start); - if (now != start) // it makes no sense the first time + if (now != start) // no point on the first pass { _snprintf_s(retryBuf, _TRUNCATE, LoadStr(IDS_WAITINGTORETRYSUF), buf, (1 + (wait - 1) / 1000), attemptNum, Config.GetConnectRetries() + 1); @@ -1122,7 +1122,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = { // gives up further login attempts state = sccsDone; run = FALSE; - // actionCanceled = TRUE; // do not log cancel in "retry" + // actionCanceled = TRUE; // do not log cancellation during "retry" } else { @@ -1134,7 +1134,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = else { SalamanderGeneral->WaitForESCRelease(); // measure to prevent interrupting the next action after every ESC in the previous message box - waitWnd.Show(TRUE); // wants to continue waiting + waitWnd.Show(TRUE); // continue waiting } } break; @@ -1208,7 +1208,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = case ccsevTimeout: { fatalErrorTextID = IDS_WAITFORLOGTIMEOUT; - noRetryState = sccsFatalError; // if retry is not performed, execute sccsFatalError + noRetryState = sccsFatalError; // if retry is not performed, transition to sccsFatalError state = sccsRetry; break; } @@ -1221,7 +1221,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = int replyCode; HANDLES(EnterCriticalSection(&SocketCritSect)); - while (ReadFTPReply(&reply, &replySize, &replyCode)) // while we have some server response + while (ReadFTPReply(&reply, &replySize, &replyCode)) // while we have a server reply { if (useWelcomeMessage) welcomeMessage.Append(reply, replySize); @@ -1256,11 +1256,11 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = if (FTP_DIGIT_1(replyCode) == FTP_D1_TRANSIENTERROR || FTP_DIGIT_1(replyCode) == FTP_D1_ERROR) // e.g. 421 Service not available, closing control connection { - if (state == sccsServerReady) // if we are not reporting another error yet + if (state == sccsServerReady) // if we are not already reporting another error { CopyStr(errBuf, 300, reply, replySize); fatalErrorTextID = -1; // the error text is in 'errBuf' - noRetryState = sccsFatalError; // if retry is not performed, execute sccsFatalError + noRetryState = sccsFatalError; // if retry is not performed, transition to sccsFatalError retryLogError = FALSE; // the error is already in the log, do not add it again state = sccsRetry; } @@ -1274,7 +1274,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = } else // not an FTP server { - if (state == sccsServerReady) // if we are not reporting another error yet + if (state == sccsServerReady) // if we are not already reporting another error { opFatalErrorTextID = IDS_NOTFTPSERVERERROR; CopyStr(errBuf, 300, reply, replySize); @@ -1292,7 +1292,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = if (state == sccsServerReady) // close without a reason { fatalErrorTextID = IDS_CONNECTIONLOSTERROR; - noRetryState = sccsFatalError; // if retry is not performed, execute sccsFatalError + noRetryState = sccsFatalError; // if retry is not performed, transition to sccsFatalError state = sccsRetry; } if (data1 != NO_ERROR) @@ -1344,7 +1344,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = &proxyScriptParams, NULL, NULL, proxySendCmdBuf, proxyLogCmdBuf, errBuf, NULL)) { - if (sslisNone == SSLInitSequence && proxyScriptParams.NeedUserInput()) // it is necessary to enter some data (user, password, etc.) + if (sslisNone == SSLInitSequence && proxyScriptParams.NeedUserInput()) // some data needs to be entered (user, password, etc.) { if (proxyScriptParams.NeedProxyHost) { @@ -1485,7 +1485,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = } if (proxySendCmdBuf[0] == 0) // end of the login script { - if (proxyLastCmdReply == -1) // the script contains no command sent to the server - e.g. commands skipped because they contain optional variables + if (proxyLastCmdReply == -1) // the script contains no command to send to the server - e.g. commands skipped because they contain optional variables { fatalErrorTextID = IDS_INCOMPLETEPRXSCR2; state = sccsFatalError; @@ -1495,7 +1495,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = if (FTP_DIGIT_1(proxyLastCmdReply) == FTP_D1_SUCCESS) // e.g. 230 User logged in, proceed { state = sccsDone; - ret = TRUE; // SUCCESS, we are logged in! + ret = TRUE; // success, logged in } else // FTP_DIGIT_1(proxyLastCmdReply) == FTP_D1_PARTIALSUCCESS // e.g. 331 User name okay, need password { @@ -1561,7 +1561,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = case ccsevTimeout: { fatalErrorTextID = IDS_SNDORABORCMDTIMEOUT; - noRetryState = sccsFatalError; // if retry is not performed, execute sccsFatalError + noRetryState = sccsFatalError; // if retry is not performed, transition to sccsFatalError state = sccsRetry; allBytesWritten = TRUE; // no longer important, the socket will be closed break; @@ -1578,7 +1578,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = HANDLES(EnterCriticalSection(&SocketCritSect)); BOOL sectLeaved = FALSE; - while (ReadFTPReply(&reply, &replySize, &replyCode)) // while we have some server response + while (ReadFTPReply(&reply, &replySize, &replyCode)) // while we have a server reply { if (useWelcomeMessage) welcomeMessage.Append(reply, replySize); @@ -1588,7 +1588,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = { if ((FTP_DIGIT_1(replyCode) == FTP_D1_ERROR) && CompressData && !_strnicmp(proxySendCmdBuf, "MODE Z", sizeof("MODE Z") - 1)) { - // Server does not support compression -> swallow the error, disable compression and go on + // Server does not support compression -> ignore the error, disable compression, and continue replyCode = 200; // Emulate Full success CompressData = FALSE; Logs.LogMessage(logUID, LoadStr(IDS_MODEZ_LOG_UNSUPBYSERVER), -1); @@ -1614,8 +1614,8 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = FTP_DIGIT_1(replyCode) == FTP_D1_ERROR) // e.g. 530 Not logged in (invalid password) { if (FTP_DIGIT_1(replyCode) == FTP_D1_TRANSIENTERROR) - { // convenient handling of the "too many users" error - no questions, immediately "retry" - // drawback: with this code comes a message that may require changing user/password + { // convenient handling of the "too many users" error - retry immediately without prompting +// possible issue: this code may be followed by a message that requires changing the user/password retryLoginWithoutAsking = TRUE; } @@ -1668,7 +1668,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = if (dlg.LoginChanged && event != ccsevClosed && !proxyUsed) { // retry login (without waiting and closing the connection) - handles responses such as "invalid user/password" state = sccsRetryLogin; - // allBytesWritten = TRUE; // the connection will not be closed, we must wait (besides, once a reply arrived, it is likely the whole command was sent) + // allBytesWritten = TRUE; // the connection will not be closed, so we must wait (once a reply has arrived, the whole command was presumably sent) } } else // cancel @@ -1687,7 +1687,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = opFatalErrorTextID = IDS_LOGINERROR; // CopyStr(errBuf, 300, reply, replySize); // done earlier - before leaving the critical section opFatalError = -1; // the error text is in 'errBuf' - noRetryState = sccsOperationFatalError; // if retry is not performed, execute sccsOperationFatalError + noRetryState = sccsOperationFatalError; // if retry is not performed, transition to sccsOperationFatalError retryLogError = FALSE; // the error is already in the log, do not add it again state = sccsRetry; allBytesWritten = TRUE; // no longer important, the socket will be closed @@ -1701,11 +1701,11 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = } else // not an FTP server { - if (state == sccsProcessLoginScript) // if we are not reporting another error yet + if (state == sccsProcessLoginScript) // if we are not already reporting another error { opFatalErrorTextID = IDS_NOTFTPSERVERERROR; CopyStr(errBuf, 300, reply, replySize); - opFatalError = -1; // the "error" (reply) is directly in errBuf + opFatalError = -1; // the "error" reply is already in errBuf state = sccsOperationFatalError; fatalErrLogMsg = FALSE; // already in the log, no point adding it again allBytesWritten = TRUE; // no longer important, the socket will be closed @@ -1722,7 +1722,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = if (state == sccsProcessLoginScript) // close without a reason { fatalErrorTextID = IDS_CONNECTIONLOSTERROR; - noRetryState = sccsFatalError; // if retry is not performed, execute sccsFatalError + noRetryState = sccsFatalError; // if retry is not performed, transition to sccsFatalError state = sccsRetry; } if (data1 != NO_ERROR) @@ -1747,7 +1747,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = int err; CCertificate* unverifiedCert; if (!EncryptSocket(logUID, &err, &unverifiedCert, &errID, errBuf, 300, - NULL /* it's always NULL for the control connection */)) + NULL /* for the control connection this is always NULL */)) { allBytesWritten = TRUE; // no longer important, the socket will be closed if (errBuf[0] == 0) @@ -1816,7 +1816,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = } } } - else // Error! OpenSSL libs not found? Or not W2K+? + else // Error: OpenSSL libraries not found, or the system is not W2K+ { allBytesWritten = TRUE; // no longer important, the socket will be closed state = sccsFatalError; @@ -1864,7 +1864,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = { while (state == sccsProcessLoginScript) { - // pick an event on the socket + // select an event on the socket CControlConnectionSocketEvent event; DWORD data1, data2; WaitForEventOrESC(parent, &event, &data1, &data2, 0, NULL, NULL, FALSE); // do not wait, just receive events @@ -1875,7 +1875,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = { opFatalErrorTextID = IDS_SENDCOMMANDERROR; opFatalError = error; - noRetryState = sccsOperationFatalError; // if retry is not performed, execute sccsOperationFatalError + noRetryState = sccsOperationFatalError; // if retry is not performed, transition to sccsOperationFatalError state = sccsRetry; break; } @@ -1888,11 +1888,11 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = int replyCode; HANDLES(EnterCriticalSection(&SocketCritSect)); - while (ReadFTPReply(&reply, &replySize, &replyCode)) // while we have some server response + while (ReadFTPReply(&reply, &replySize, &replyCode)) // while we have any server reply { Logs.LogMessage(logUID, reply, replySize); - if (replyCode == -1 || // not an FTP reply + if (replyCode == -1 || // not an FTP response FTP_DIGIT_1(replyCode) == FTP_D1_TRANSIENTERROR || // description of a temporary error FTP_DIGIT_1(replyCode) == FTP_D1_ERROR) // description of an error { @@ -1900,10 +1900,10 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = CopyStr(errBuf, 300, reply, replySize); SkipFTPReply(replySize); opFatalError = -1; // the "error" (reply) is directly in errBuf - noRetryState = sccsOperationFatalError; // if retry is not performed, execute sccsOperationFatalError + noRetryState = sccsOperationFatalError; // if retry is not performed, transition to sccsOperationFatalError retryLogError = FALSE; // the error is already in the log, do not add it again state = sccsRetry; - break; // no need to read another message + break; // no need to read another reply } SkipFTPReply(replySize); } @@ -1914,7 +1914,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = if (state == sccsProcessLoginScript) // close without a reason { fatalErrorTextID = IDS_CONNECTIONLOSTERROR; - noRetryState = sccsFatalError; // if retry is not performed, execute sccsFatalError + noRetryState = sccsFatalError; // if retry is not performed, transition to sccsFatalError state = sccsRetry; } if (data1 != NO_ERROR) @@ -2080,7 +2080,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = errBuf, 300, NULL)) { ret = FALSE; // we are no longer connected - break; // go perform the "retry" + break; // perform the "retry" } } } @@ -2101,13 +2101,13 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = HANDLES(LeaveCriticalSection(&SocketCritSect)); } else - ret = FALSE; // error -> connection closed - go perform the "retry" + ret = FALSE; // error -> connection closed - proceed with the "retry" } if (ret && workDir != NULL && !GetCurrentWorkingPath(parent, workDir, workDirBufSize, FALSE, &canRetry, errBuf, 300)) { - ret = FALSE; // error -> connection closed - go perform the "retry" + ret = FALSE; // error -> connection closed - proceed with the "retry" } if (canRetry && !ret) // assumes 'errBuf' has been set @@ -2166,7 +2166,7 @@ BOOL CControlConnectionSocket::ReconnectIfNeeded(BOOL notInPanel, BOOL leftPanel { if (retryMsg == NULL) // connection interrupted for an unknown reason - display it and ask about reconnecting { - // if we have not yet displayed what led to the connection closing, do it now + // if we have not yet reported what led to the connection closing, do it now CheckCtrlConClose(notInPanel, leftPanel, parent, FALSE); BOOL reconnectToSrv = FALSE; diff --git a/src/plugins/ftp/ctrlcon2.cpp b/src/plugins/ftp/ctrlcon2.cpp index 66aedbffc..6c76d3bc2 100644 --- a/src/plugins/ftp/ctrlcon2.cpp +++ b/src/plugins/ftp/ctrlcon2.cpp @@ -191,7 +191,7 @@ BOOL CDynString::Append(const char* str, int len) Buffer = newBuf; Allocated = size; } - else // insufficient memory, tough luck... + else // insufficient memory { TRACE_E(LOW_MEMORY); return FALSE; @@ -258,7 +258,7 @@ void CControlConnectionSocket::CloseControlConnection(HWND parent) serverTimeout = 1000; // at least a second SetStartTime(); - // Remember the focus from 'parent' (if the focus is not from 'parent', store NULL) + // Remember the focused window in 'parent' (store NULL if the focus is not within 'parent') HWND focusedWnd = GetFocus(); HWND hwnd = focusedWnd; while (hwnd != NULL && hwnd != parent) @@ -362,7 +362,7 @@ void CControlConnectionSocket::CloseControlConnection(HWND parent) int replySize; HANDLES(EnterCriticalSection(&SocketCritSect)); - while (ReadFTPReply(&reply, &replySize)) // process responses from the server as long as we have any + while (ReadFTPReply(&reply, &replySize)) // while we have any server replies { Logs.LogMessage(logUID, reply, replySize); @@ -411,7 +411,7 @@ void CControlConnectionSocket::CloseControlConnection(HWND parent) if (!socketClosed) { - CloseSocket(NULL); // close the socket (if it is open); the system will attempt a "graceful" shutdown (we won't learn the result) + CloseSocket(NULL); // close the socket (if it is open); the system will attempt a "graceful" shutdown (the result is unknown) Logs.SetIsConnected(logUID, IsConnected()); Logs.RefreshListOfLogsInLogsDlg(); // show the "connection inactive" notification } @@ -444,7 +444,7 @@ void CControlConnectionSocket::CheckCtrlConClose(BOOL notInPanel, BOOL leftPanel char* auxConnectionLostMsg = ConnectionLostMsg; HANDLES(LeaveCriticalSection(&EventCritSect)); - if (found || // the ccsevClosed event is waiting for us—the user still does not know that the connection is closed + if (found || // the ccsevClosed event is still pending; the user still does not know that the connection is closed auxConnectionLostMsg != NULL) // we cached the message captured when the connection closed (at that moment it only went into the log) { char errBuf[300]; @@ -459,7 +459,7 @@ void CControlConnectionSocket::CheckCtrlConClose(BOOL notInPanel, BOOL leftPanel BOOL haveErr = FALSE; HANDLES(EnterCriticalSection(&SocketCritSect)); - while (ReadFTPReply(&reply, &replySize, &replyCode)) // process responses from the server as long as we have any + while (ReadFTPReply(&reply, &replySize, &replyCode)) // while we have a server response { Logs.LogMessage(logUID, reply, replySize, TRUE); @@ -485,7 +485,7 @@ void CControlConnectionSocket::CheckCtrlConClose(BOOL notInPanel, BOOL leftPanel lstrcpyn(errBuf, ConnectionLostMsg, 300); else errBuf[0] = 0; - SalamanderGeneral->Free(ConnectionLostMsg); // it is no longer needed + SalamanderGeneral->Free(ConnectionLostMsg); // no longer needed ConnectionLostMsg = NULL; HANDLES(LeaveCriticalSection(&SocketCritSect)); } @@ -510,7 +510,7 @@ void CControlConnectionSocket::CheckCtrlConClose(BOOL notInPanel, BOOL leftPanel lstrcpyn(errBuf, ConnectionLostMsg, 300); else errBuf[0] = 0; - SalamanderGeneral->Free(ConnectionLostMsg); // it is no longer needed + SalamanderGeneral->Free(ConnectionLostMsg); // no longer needed ConnectionLostMsg = NULL; HANDLES(LeaveCriticalSection(&SocketCritSect)); } @@ -572,8 +572,8 @@ BOOL CControlConnectionSocket::ReadFTPReply(char** reply, int* replySize, int* r CALL_STACK_MESSAGE1("CControlConnectionSocket::ReadFTPReply(, ,)"); #ifdef _DEBUG - if (SocketCritSect.RecursionCount == 0 /* does not catch the situation when - the section is used by another thread */ + if (SocketCritSect.RecursionCount == 0 /* does not catch the situation where + another thread uses the section */ ) TRACE_E("Incorrect call to CControlConnectionSocket::ReadFTPReply: not from section SocketCritSect!"); #endif @@ -586,8 +586,8 @@ void CControlConnectionSocket::SkipFTPReply(int replySize) CALL_STACK_MESSAGE2("CControlConnectionSocket::SkipFTPReply(%d)", replySize); #ifdef _DEBUG - if (SocketCritSect.RecursionCount == 0 /* does not catch the situation when - the section is used by another thread */ + if (SocketCritSect.RecursionCount == 0 /* does not catch the situation where + another thread uses the section */ ) TRACE_E("Incorrect call to CControlConnectionSocket::SkipFTPReply: not from section SocketCritSect!"); #endif @@ -622,9 +622,9 @@ BOOL CControlConnectionSocket::Write(const char* buffer, int bytesToWrite, DWORD HANDLES(EnterCriticalSection(&SocketCritSect)); BOOL ret = FALSE; - if (Socket != INVALID_SOCKET) // the socket is connected + if (Socket != INVALID_SOCKET) // socket is connected { - if (BytesToWriteCount == BytesToWriteOffset) // nothing is waiting to be sent, we can transmit + if (BytesToWriteCount == BytesToWriteOffset) // nothing is waiting to be sent; we can send { if (BytesToWriteCount != 0) TRACE_E("Unexpected value of BytesToWriteCount."); @@ -637,7 +637,7 @@ BOOL CControlConnectionSocket::Write(const char* buffer, int bytesToWrite, DWORD // a command in the SendFTPCommand() method must be adjusted int sentLen = send(Socket, buffer + len, bytesToWrite - len, 0); - if (sentLen != SOCKET_ERROR) // at least something was sent successfully (or rather taken over by Windows; delivery is uncertain) + if (sentLen != SOCKET_ERROR) // at least some data was sent successfully (or rather accepted by Windows; delivery is uncertain) { len += sentLen; if (len >= bytesToWrite) // has everything been sent? @@ -649,16 +649,16 @@ BOOL CControlConnectionSocket::Write(const char* buffer, int bytesToWrite, DWORD else { DWORD err = WSAGetLastError(); - if (err == WSAEWOULDBLOCK) // nothing else can be sent (Windows no longer have buffer space) + if (err == WSAEWOULDBLOCK) // nothing else can be sent (Windows no longer has buffer space available) { ret = TRUE; break; // stop sending (the rest will be done after FD_WRITE) } - else // send error + else // sending error { if (error != NULL) *error = err; - break; // return the error + break; // return an error } } } @@ -669,24 +669,24 @@ BOOL CControlConnectionSocket::Write(const char* buffer, int bytesToWrite, DWORD // a command in the SendFTPCommand() method must be adjusted int sentLen = SSLLib.SSL_write(SSLConn, buffer + len, bytesToWrite - len); - if (sentLen >= 0) // at least something was sent successfully (or rather taken over by Windows; delivery is uncertain) + if (sentLen >= 0) // at least some data was sent successfully (or rather accepted by Windows; delivery is uncertain) { len += sentLen; if (len >= bytesToWrite) // has everything been sent? { ret = TRUE; - break; // stop sending (there is nothing left) + break; // stop sending (nothing is left) } } else { DWORD err = SSLtoWS2Error(SSLLib.SSL_get_error(SSLConn, sentLen)); - if (err == WSAEWOULDBLOCK) // nothing else can be sent (Windows no longer have buffer space) + if (err == WSAEWOULDBLOCK) // nothing else can be sent (Windows no longer has buffer space) { ret = TRUE; break; // stop sending (the rest will be done after FD_WRITE) } - else // send error + else // sending error { if (error != NULL) *error = err; @@ -695,7 +695,7 @@ BOOL CControlConnectionSocket::Write(const char* buffer, int bytesToWrite, DWORD } } - if (ret) // successful send, 'len' holds the number of bytes sent (the rest is sent after FD_WRITE is received) + if (ret) // send succeeded; 'len' holds the number of bytes sent (the rest will be sent after FD_WRITE) { if (allBytesWritten != NULL) *allBytesWritten = (len >= bytesToWrite); @@ -713,7 +713,7 @@ BOOL CControlConnectionSocket::Write(const char* buffer, int bytesToWrite, DWORD BytesToWrite = newBuf; BytesToWriteAllocatedSize = newSize; } - else // not enough memory to store data in our buffer (only TRACE reports the error) + else // insufficient memory to store the data in our buffer (only TRACE reports the error) { TRACE_E(LOW_MEMORY); ret = FALSE; @@ -805,7 +805,7 @@ BOOL CControlConnectionSocket::SendKeepAliveCmd(int logUID, const char* ftpCmd) void CControlConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) { CALL_STACK_MESSAGE3("CControlConnectionSocket::ReceiveNetEvent(0x%IX, %d)", lParam, index); - DWORD eventError = WSAGETSELECTERROR(lParam); // extract error code of event + DWORD eventError = WSAGETSELECTERROR(lParam); // extract the event error code switch (WSAGETSELECTEVENT(lParam)) // extract event { case FD_CLOSE: // sometimes arrives before the final FD_READ; we must first try FD_READ and, if it succeeds, post FD_CLOSE again (another FD_READ may succeed before it) @@ -825,19 +825,19 @@ void CControlConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) BOOL genEvent = FALSE; if (eventError == NO_ERROR) { - if (Socket != INVALID_SOCKET) // the socket is connected + if (Socket != INVALID_SOCKET) // socket is connected { BOOL lowMem = FALSE; if (ReadBytesAllocatedSize - ReadBytesCount < CRTLCON_BYTESTOREADONSOCKET) // the 'ReadBytes' buffer is small { - if (ReadBytesOffset > 0) // is it possible to move data within the buffer? + if (ReadBytesOffset > 0) // can data be shifted within the buffer? { memmove(ReadBytes, ReadBytes + ReadBytesOffset, ReadBytesCount - ReadBytesOffset); ReadBytesCount -= ReadBytesOffset; ReadBytesOffset = 0; } - if (ReadBytesAllocatedSize - ReadBytesCount < CRTLCON_BYTESTOREADONSOCKET) // the 'ReadBytes' buffer is still small + if (ReadBytesAllocatedSize - ReadBytesCount < CRTLCON_BYTESTOREADONSOCKET) // the 'ReadBytes' buffer is still too small { int newSize = ReadBytesCount + CRTLCON_BYTESTOREADONSOCKET + CRTLCON_BYTESTOREADONSOCKETPREALLOC; @@ -847,7 +847,7 @@ void CControlConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) ReadBytes = newBuf; ReadBytesAllocatedSize = newSize; } - else // not enough memory to store data in our buffer (only TRACE reports the error) + else // insufficient memory to store the data in our buffer (only TRACE reports the error) { TRACE_E(LOW_MEMORY); lowMem = TRUE; @@ -865,7 +865,7 @@ void CControlConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) { if (len > 0) { - ReadBytesCount += len; // adjust the number of bytes read by the newly received ones + ReadBytesCount += len; // adjust the number of bytes read by the newly read bytes ret = TRUE; genEvent = TRUE; if (WSAGETSELECTEVENT(lParam) == FD_CLOSE) @@ -888,7 +888,7 @@ void CControlConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) { if (len > 0) { - ReadBytesCount += len; // adjust the number of bytes read by the newly received ones + ReadBytesCount += len; // increment the number of bytes read by the newly read bytes ret = TRUE; genEvent = TRUE; if (WSAGETSELECTEVENT(lParam) == FD_CLOSE) @@ -912,7 +912,7 @@ void CControlConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) // do not generate an event for this unexpected error (solution: the user presses ESC) } } - else // reporting an error in FD_READ (according to the help only WSAENETDOWN) + else // FD_READ error report (according to the documentation, only WSAENETDOWN) { if (WSAGETSELECTEVENT(lParam) != FD_CLOSE) // let FD_CLOSE handle the error itself { @@ -925,7 +925,7 @@ void CControlConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) char* reply; int replySize; int replyCode; - while (ReadFTPReply(&reply, &replySize, &replyCode)) // process responses from the server as long as we have any + while (ReadFTPReply(&reply, &replySize, &replyCode)) // while we have a server response { Logs.LogMessage(LogUID, reply, replySize); BOOL run = TRUE; @@ -988,7 +988,7 @@ void CControlConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) if (kaDataConnection->FinishDataTransfer(replyCode)) { // release the data connection via the SocketsThread method call HANDLES(EnterCriticalSection(&SocketCritSect)); - kaDataConnection = KeepAliveDataCon; // prevent double destruction (if the main thread waits for destruction, it is already NULL) + kaDataConnection = KeepAliveDataCon; // prevent double destruction (if the main thread is waiting for destruction, KeepAliveDataCon is already NULL here) KeepAliveDataCon = NULL; KeepAliveDataConState = kadcsNone; HANDLES(LeaveCriticalSection(&SocketCritSect)); @@ -1038,12 +1038,12 @@ void CControlConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) // consume extra messages from the server (e.g. WarFTPD generates them when LISTing an inaccessible directory) HANDLES(EnterCriticalSection(&SocketCritSect)); - while (ReadFTPReply(&reply, &replySize, &replyCode)) // process responses from the server as long as we have any + while (ReadFTPReply(&reply, &replySize, &replyCode)) // while we have a server response { Logs.LogMessage(LogUID, reply, replySize); SkipFTPReply(replySize); } - break; // abort... + break; // stop... } HANDLES(EnterCriticalSection(&SocketCritSect)); if (!run) @@ -1087,7 +1087,7 @@ void CControlConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) { if (BytesToWriteCount > BytesToWriteOffset) // we have remaining data, send the rest from the 'BytesToWrite' buffer { - if (Socket != INVALID_SOCKET) // the socket is connected + if (Socket != INVALID_SOCKET) // socket is connected { int len = 0; if (!SSLConn) @@ -1096,24 +1096,24 @@ void CControlConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) { int sentLen = send(Socket, BytesToWrite + BytesToWriteOffset + len, BytesToWriteCount - BytesToWriteOffset - len, 0); - if (sentLen != SOCKET_ERROR) // at least something was sent successfully (or rather taken over by Windows; delivery is uncertain) + if (sentLen != SOCKET_ERROR) // at least some data was sent successfully (or rather accepted by Windows; delivery is uncertain) { len += sentLen; if (len >= BytesToWriteCount - BytesToWriteOffset) // has everything been sent? { ret = TRUE; - break; // stop sending (there is nothing left) + break; // stop sending (nothing left) } } else { err = WSAGetLastError(); - if (err == WSAEWOULDBLOCK) // nothing else can be sent (Windows no longer have buffer space) + if (err == WSAEWOULDBLOCK) // nothing else can be sent (Windows no longer has buffer space) { ret = TRUE; break; // stop sending (the rest will be done after FD_WRITE) } - else // different error - reset the buffer + else // another error - reset the buffer { BytesToWriteOffset = 0; BytesToWriteCount = 0; @@ -1128,7 +1128,7 @@ void CControlConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) { int sentLen = SSLLib.SSL_write(SSLConn, BytesToWrite + BytesToWriteOffset + len, BytesToWriteCount - BytesToWriteOffset - len); - if (sentLen >= 0) // at least something was sent successfully (or rather taken over by Windows; delivery is uncertain) + if (sentLen >= 0) // at least some data was sent successfully (or rather accepted by Windows; delivery is uncertain) { len += sentLen; if (len >= BytesToWriteCount - BytesToWriteOffset) // has everything been sent? @@ -1140,12 +1140,12 @@ void CControlConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) else { err = SSLtoWS2Error(SSLLib.SSL_get_error(SSLConn, sentLen)); - if (err == WSAEWOULDBLOCK) // nothing else can be sent (Windows no longer have buffer space) + if (err == WSAEWOULDBLOCK) // nothing else can be sent (Windows no longer has buffer space) { ret = TRUE; break; // stop sending (the rest will be done after FD_WRITE) } - else // different error - reset the buffer + else // another error - reset the buffer { BytesToWriteOffset = 0; BytesToWriteCount = 0; @@ -1171,13 +1171,13 @@ void CControlConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) { // May occur: the main thread manages to call CloseSocket() before FD_WRITE is delivered //TRACE_E("Unexpected situation in CControlConnectionSocket::ReceiveNetEvent(FD_WRITE): Socket is not connected."); - BytesToWriteCount = 0; // error — reset the buffer + BytesToWriteCount = 0; // error: reset the buffer BytesToWriteOffset = 0; // do not generate an event for this unexpected error (solution: the user presses ESC) } } } - else // reporting an error in FD_WRITE (according to the help only WSAENETDOWN) + else // FD_WRITE error report (according to the documentation, only WSAENETDOWN) { genEvent = TRUE; err = eventError; @@ -1219,8 +1219,8 @@ void CControlConnectionSocket::SocketWasClosed(DWORD error) AddEvent(ccsevClosed, error, 0); // Inform the user about the control connection closing if it does not happen - // during a socket operation (when the user would be told about a timeout or a "kick" - // leading to disconnection from the FTP server) + // during a socket operation (which would report a timeout or a "kick" + // leading to disconnection from the FTP server) ClosedCtrlConChecker.Add(this); HANDLES(EnterCriticalSection(&SocketCritSect)); @@ -1280,14 +1280,14 @@ void CClosedCtrlConChecker::Check(HWND parent) CmdNotPost = TRUE; int k; - for (k = 0; k < CtrlConSockets.Count; k++) // for all stored closed control connections (may already be deallocated) + for (k = 0; k < CtrlConSockets.Count; k++) // for all stored closed control connections (they may already be deallocated) { CControlConnectionSocket* ctrlCon = CtrlConSockets[k]; int i; - for (i = 0; i < FTPConnections.Count; i++) // try to find a FS using 'ctrlCon' (the FS may already be closed) + for (i = 0; i < FTPConnections.Count; i++) // try to find an FS using 'ctrlCon' ('FS' may already be closed) { CPluginFSInterface* fs = FTPConnections[i]; - if (fs->Contains(ctrlCon)) // found a FS with a closed control connection + if (fs->Contains(ctrlCon)) // found an FS with a closed control connection { fs->CheckCtrlConClose(parent); // if the user has not been informed yet, notify them now break; @@ -1371,8 +1371,8 @@ class CLogsDlgThread : public CThread CALL_STACK_MESSAGE1("CLogsDlgThread::Body()"); // 'sendWMClose': the dialog sets this to TRUE when WM_CLOSE is received - // while a modal dialog is open above the logs dialog; once that - // modal dialog finishes, WM_CLOSE is sent to the logs dialog again + // while a modal dialog is open over the log dialog; once that + // modal dialog closes, WM_CLOSE is sent to the log dialog again BOOL sendWMClose = FALSE; LogsDlg->SendWMClose = &sendWMClose; @@ -1386,7 +1386,7 @@ class CLogsDlgThread : public CThread else { HWND dlg = LogsDlg->HWindow; - if (AlwaysOnTop) // handle always-on-top at least "statically" (not in the system menu) + if (AlwaysOnTop) // handle always-on-top at least statically (it is not in the system menu) SetWindowPos(dlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); SetForegroundWindow(dlg); @@ -1578,7 +1578,7 @@ void CLogs::SetLogToEdit(HWND edit, int logUID, BOOL update) void CLogs::ConfigChanged() { HANDLES(EnterCriticalSection(&LogCritSect)); - if (!Config.EnableLogging) // tear down the data + if (!Config.EnableLogging) // clear the data { Data.DestroyMembers(); if (!Data.IsGood()) @@ -1685,8 +1685,8 @@ void CLogs::LimitClosedConLogs() for (i = Data.Count - 1; i >= 0; i--) { CLogData* d = Data[i]; - if (d->CtrlCon == NULL && !d->WorkerIsAlive && // log of a closed connection (dead log) - d->DisconnectNum < firstSurvival) // it is an overly old log + if (d->CtrlCon == NULL && !d->WorkerIsAlive && // log for a closed connection (dead log) + d->DisconnectNum < firstSurvival) // this log is too old { Data.Delete(i); if (!Data.IsGood()) @@ -1849,7 +1849,7 @@ BOOL CLogs::ActivateLogsDlg(int showLogUID) if (t != NULL) { if ((LogsThread = t->Create(AuxThreadQueue)) == NULL) - { // the thread did not start, error + { // thread did not start, error delete t; delete LogsDlg; LogsDlg = NULL; @@ -1983,7 +1983,7 @@ void CLogs::SaveLog(HWND parent, const char* itemName, int uid) } if (uid != -1) - break; // writing only one log, stop here + break; // writing only one log, stop if (i + 1 < Data.Count) // write a separator { @@ -2003,7 +2003,7 @@ void CLogs::SaveLog(HWND parent, const char* itemName, int uid) HANDLES(CloseHandle(file)); SetCursor(oldCur); - if (err != NO_ERROR) // report the error + if (err != NO_ERROR) // display the error { sprintf(buf, LoadStr(IDS_SAVELOGERROR), SalamanderGeneral->GetErrorText(err)); SalamanderGeneral->SalMessageBox(parent, buf, LoadStr(IDS_FTPERRORTITLE), diff --git a/src/plugins/ftp/ctrlcon3.cpp b/src/plugins/ftp/ctrlcon3.cpp index 1efa3ce3d..5a462f832 100644 --- a/src/plugins/ftp/ctrlcon3.cpp +++ b/src/plugins/ftp/ctrlcon3.cpp @@ -64,7 +64,7 @@ void CSendCmdUserIfaceWaitWnd::Init(HWND parent, const char* logCmd, const char* { char buf[500]; char errBuf[300]; - if (waitWndText == NULL) // standard text of the wait window + if (waitWndText == NULL) // use the standard wait window text { lstrcpyn(errBuf, logCmd, 300); // trim the CRLF from the command char* s = errBuf + strlen(errBuf); @@ -153,7 +153,7 @@ BOOL CControlConnectionSocket::SendFTPCommand(HWND parent, const char* ftpCmd, c CSetWaitCursorWindow* winParent = NULL; if (parentIsEnabled) // we cannot leave the parent enabled (the wait window is not modal) { - // store the focus from 'parent' (if the focus is not from 'parent', store NULL) + // save the current focus in 'parent' (if focus is not in 'parent', store NULL) focusedWnd = GetFocus(); HWND hwnd = focusedWnd; while (hwnd != NULL && hwnd != parent) @@ -229,7 +229,7 @@ BOOL CControlConnectionSocket::SendFTPCommand(HWND parent, const char* ftpCmd, c if (aborting && auxCanSendOOBData) { - // notify the server about the abort (see RFC 959 - sending the ABOR command) + // notify the server of the abort (see RFC 959: sending the ABOR command) HANDLES(EnterCriticalSection(&SocketCritSect)); if (Socket != INVALID_SOCKET && BytesToWriteCount == 0) // "always true" (all data should have been sent) @@ -319,11 +319,11 @@ BOOL CControlConnectionSocket::SendFTPCommand(HWND parent, const char* ftpCmd, c { if (userIface->HandleESC(parent, state == sfcsSendCommand, allowCmdAbort)) { // cancel - if (allowCmdAbort && state == sfcsSendCommand) // cancel for the command -> start aborting the command + if (allowCmdAbort && state == sfcsSendCommand) // command cancel -> start aborting the command { state = sfcsAbortCommand; - // allBytesWritten = TRUE; // we must wait until the command is sent before starting to send the abort - // we will not display the wait window again; in theory sending should never stall -> ignore it (the user will wait without the wait window) + // allBytesWritten = TRUE; // we must wait until the command is sent before starting the abort + // we will not show the wait dialog again; in theory, sending should never stall, so we do not handle it (the user will wait without the dialog) } else // cannot use abort (we must close the connection) or cancel while aborting the command { @@ -380,14 +380,14 @@ BOOL CControlConnectionSocket::SendFTPCommand(HWND parent, const char* ftpCmd, c { // replies of type FTP_D1_MAYBESUCCESS are logged only (we are waiting for the server's "last word") if (event != ccsevClosed) { - if (!aborting) // send command - { // state can also be sfcsAbortCommand; then we must abort the command even if it succeeded just now (the user ordered an abort) + if (!aborting) // send the command unless it is being aborted + { // state can also be sfcsAbortCommand; then we must abort the command even if it has just succeeded (the user requested an abort) if (state != sfcsAbortCommand) { state = sfcsDone; *ftpReplyCode = replyCode; CopyStr(ftpReplyBuf, ftpReplyBufSize, reply, replySize); - ret = TRUE; // SUCCESS, we have the server's reply! (for sending we only care about a single server reply) + ret = TRUE; // SUCCESS, we have the server reply! (when sending, only one server reply matters) } // else; // continue waiting for the abort command (we have not sent ABOR yet) SkipFTPReply(replySize); @@ -408,8 +408,8 @@ BOOL CControlConnectionSocket::SendFTPCommand(HWND parent, const char* ftpCmd, c { // this is the reply for the sent or aborted command; we will still try to read // additional server replies (some servers send one more for ABOR) - if (!cmdReplyReceived) // return the first reply (it should belong to the command but it may be - { // for ABOR as well) - ignore any possible second reply (to ABOR) + if (!cmdReplyReceived) // return the first reply (it should belong to the command, but it may also be for ABOR) + { // ignore any possible second reply (to ABOR) state = sfcsDone; *ftpReplyCode = replyCode; CopyStr(ftpReplyBuf, ftpReplyBufSize, reply, replySize); @@ -493,7 +493,7 @@ BOOL CControlConnectionSocket::SendFTPCommand(HWND parent, const char* ftpCmd, c switch (event) { case ccsevUserIfaceFinished: - break; // CanFinishSending() will hopefully return TRUE now + break; // CanFinishSending() should return TRUE now case ccsevTimeout: { @@ -563,7 +563,7 @@ BOOL CControlConnectionSocket::SendFTPCommand(HWND parent, const char* ftpCmd, c switch (event) { // case ccsevESC: // (the user cannot press ESC during a 0 ms timeout) - case ccsevTimeout: // no message is waiting -> display the error from Write directly + case ccsevTimeout: // no message is pending -> display the error from Write directly { opFatalErrorTextID = !aborting ? IDS_SENDCOMMANDERROR : IDS_ABORTCOMMANDERROR; opFatalError = error; @@ -622,7 +622,7 @@ BOOL CControlConnectionSocket::SendFTPCommand(HWND parent, const char* ftpCmd, c if (event == ccsevClosed) { - if (state == sendState) // close without a cause + if (state == sendState) // unexpected close { fatalErrorTextID = IDS_CONNECTIONLOSTERROR; state = sfcsFatalError; @@ -653,7 +653,7 @@ BOOL CControlConnectionSocket::SendFTPCommand(HWND parent, const char* ftpCmd, c Logs.LogMessage(logUID, buf, -1, TRUE); // add the last error text to the log } fatalErrLogMsg = TRUE; - if (canRetry == NULL || donotRetry) // "retry" is not possible or does not make sense + if (canRetry == NULL || donotRetry) // "retry" is not possible or useful { *s = 0; SalamanderGeneral->SalMessageBox(parent, buf, LoadStr(IDS_FTPERRORTITLE), @@ -707,7 +707,7 @@ BOOL CControlConnectionSocket::SendFTPCommand(HWND parent, const char* ftpCmd, c } } - if (parentIsEnabled) // if we disabled the parent, enable it again + if (parentIsEnabled) // if the parent was disabled, enable it again { // remove the wait cursor over the parent if (winParent != NULL) @@ -744,7 +744,7 @@ BOOL CControlConnectionSocket::SendFTPCommand(HWND parent, const char* ftpCmd, c SetupKeepAliveTimer(); } } - else // connection interrupted or timeout (the socket cannot be used anymore) + else // connection interrupted or timed out (the socket is no longer usable) { CloseSocket(NULL); // close the socket (if it is open); the system will attempt a "graceful" shutdown (we will not learn the result) Logs.SetIsConnected(logUID, IsConnected()); @@ -795,7 +795,7 @@ BOOL CControlConnectionSocket::GetCurrentWorkingPath(HWND parent, char* path, in HANDLES(EnterCriticalSection(&SocketCritSect)); if (FTP_DIGIT_1(ftpReplyCode) == FTP_D1_SUCCESS && // success is returned (should be 257) FTPGetDirectoryFromReply(replyBuf, (int)strlen(replyBuf), WorkingPath, FTP_MAX_PATH) || - FTP_DIGIT_1(ftpReplyCode) != FTP_D1_SUCCESS) // failure returned (e.g. "not defined; use CWD to set the working directory") -> temporarily use an empty path + FTP_DIGIT_1(ftpReplyCode) != FTP_D1_SUCCESS) // failed (e.g. "not defined; use CWD to set the working directory") -> temporarily use an empty path { if (FTP_DIGIT_1(ftpReplyCode) != FTP_D1_SUCCESS) WorkingPath[0] = 0; // temporarily use an empty path @@ -896,8 +896,8 @@ BOOL CControlConnectionSocket::SendChangeWorkingPath(BOOL notInPanel, BOOL leftP const char* p; BOOL needChangeDir = i == 0 && reconnected && startPath != NULL; // after reconnect try to set 'startPath' again - if (i == 0 && !reconnected && startPath != NULL) // we have been connected for a while, check - { // whether the working directory matches 'startPath' + if (i == 0 && !reconnected && startPath != NULL) // we have been connected for a while; check whether the working directory matches 'startPath' + { // use the cache; under normal circumstances the path should be there if (GetCurrentWorkingPath(parent, newPath, FTP_MAX_PATH, FALSE, &canRetry, retryMsgBuf, 300)) { @@ -1041,8 +1041,8 @@ BOOL CControlConnectionSocket::ChangeWorkingPath(BOOL notInPanel, BOOL leftPanel if (path[0] == 0) // only right after connecting - otherwise the path change (Shift+F7) to { // a relative path (e.g. "ftp://localhost") is ignored // + when optimizing ChangePath() called right after obtaining the working directory - // forceRefresh should be only FALSE + it is always preceded by a GetCurrentWorkingPath() call -> it should always - // take the path from the cache (does not touch the connection) + // forceRefresh should only be FALSE, and this is always preceded by a GetCurrentWorkingPath() call, so it should always + // use the cached path (without touching the connection) ret = GetCurrentWorkingPath(parent, path, pathBufSize, forceRefresh, NULL, NULL, 0); if (ret) { @@ -1052,7 +1052,7 @@ BOOL CControlConnectionSocket::ChangeWorkingPath(BOOL notInPanel, BOOL leftPanel } else { - if (parsedPath && // except for connecting from the "Connect to FTP Server" dialog it is always TRUE + if (parsedPath && // parsedPath is always TRUE except when connecting from the "Connect to FTP Server" dialog (*path == '/' || *path == '\\')) // 'path' always starts with '/' or '\\' ("always true") { pathType = GetFTPServerPathType(path + 1); @@ -1060,7 +1060,7 @@ BOOL CControlConnectionSocket::ChangeWorkingPath(BOOL notInPanel, BOOL leftPanel pathType == ftpsptOS2 && GetFTPServerPathType("") == ftpsptOS2) // OS/2 paths get confused with the Unix path "/C:/path", so distinguish OS/2 paths even just by the SYST reply { // VMS + MVS + IBM_z/VM + OS/2 do not have '/' or '\\' at the start of the path memmove(path, path + 1, strlen(path) + 1); // remove the '/' or '\\' character from the start of the path - if (path[0] == 0) // generic root -> supplement it according to the system type + if (path[0] == 0) // generic root -> fill it in according to the system type { if (pathType == ftpsptOpenVMS) lstrcpyn(path, "[000000]", pathBufSize); @@ -1074,7 +1074,7 @@ BOOL CControlConnectionSocket::ChangeWorkingPath(BOOL notInPanel, BOOL leftPanel { if (rescuePath[0] == 0 || !FTPGetIBMz_VMRootPath(path, pathBufSize, rescuePath)) { - lstrcpyn(path, "/", pathBufSize); // the tested server supported the Unix root "/"; maybe someone will report it, then we will handle it further... + lstrcpyn(path, "/", pathBufSize); // the tested server supported the Unix root "/"; maybe someone will report this, then we will handle it further... } } else @@ -1083,7 +1083,7 @@ BOOL CControlConnectionSocket::ChangeWorkingPath(BOOL notInPanel, BOOL leftPanel { if (rescuePath[0] == 0 || !FTPGetOS2RootPath(path, pathBufSize, rescuePath)) { - lstrcpyn(path, "/", pathBufSize); // try at least the Unix root "/", we know nothing else; maybe someone will report it, then we will handle it further... + lstrcpyn(path, "/", pathBufSize); // try at least the Unix root "/"; we do not know anything else; maybe someone will report this, then we will handle it further... } } } @@ -1141,8 +1141,8 @@ BOOL CControlConnectionSocket::ChangeWorkingPath(BOOL notInPanel, BOOL leftPanel pathType = GetFTPServerPathType(path); rescuePath[0] = 0; // do not try it next time (avoid loops) } - else // no need to report any error (listing already reported an error); we quietly tried - { // to find an accessible path (which did not work) + else // no need to report any error (listing already reported an error); we tried silently + { // to find an accessible path, but it did not work ret = FALSE; } } @@ -1168,7 +1168,7 @@ BOOL CControlConnectionSocket::ChangeWorkingPath(BOOL notInPanel, BOOL leftPanel strcat(listCmd, "\r\n"); BOOL isFTPS = EncryptControlConnection == 1; int useListingsCacheAux = UseListingsCache; - BOOL resuscitateKeepAlive = (IsConnected() && KeepAliveEnabled && KeepAliveMode == kamNone); // if keep-alive has already turned off (revival time expired), we must restart it + BOOL resuscitateKeepAlive = (IsConnected() && KeepAliveEnabled && KeepAliveMode == kamNone); // if keep-alive has already turned off (the resuscitation interval expired), we must restart it KeepAliveStart = GetTickCount(); // beware, it is not enough to do it simply; 'resuscitateKeepAlive' must be used HANDLES(LeaveCriticalSection(&SocketCritSect)); @@ -1259,7 +1259,7 @@ BOOL CControlConnectionSocket::ChangeWorkingPath(BOOL notInPanel, BOOL leftPanel errBuf[0] = 0; // any possible message is unnecessary; the printed error would only be confusing } } - break; // fatal error or success (path changed) + possibly: the path is cached, take the listing from the cache + break; // fatal error or success (path changed); possibly: the path is cached and the listing is taken from the cache } } else @@ -1293,7 +1293,7 @@ BOOL CControlConnectionSocket::ChangeWorkingPath(BOOL notInPanel, BOOL leftPanel lstrcpyn(path, rescuePath, pathBufSize); fileNameAlreadyCut = TRUE; pathType = GetFTPServerPathType(path); - rescuePath[0] = 0; // do not try it next time (avoid loops) + rescuePath[0] = 0; // do not try it again next time (avoid loops) } else { @@ -1307,7 +1307,7 @@ BOOL CControlConnectionSocket::ChangeWorkingPath(BOOL notInPanel, BOOL leftPanel *pathWasCut = TRUE; // we are on a path other than the requested one if (pathBufSize > 0) path[0] = 0; // there is no current path on the server - break; // go try listing... + break; // try listing now... } } else @@ -1406,7 +1406,7 @@ void CControlConnectionSocket::GiveConnectionToWorker(CFTPWorker* newWorker, HWN if (IsConnected()) // only if the connection is open { // first stop keep-alive: - // store the focus from 'parent' (if the focus is not from 'parent', store NULL) + // save the focus from 'parent' (if the focus is not in 'parent', store NULL) HWND focusedWnd = GetFocus(); HWND hwnd = focusedWnd; while (hwnd != NULL && hwnd != parent) @@ -1588,7 +1588,7 @@ void CControlConnectionSocket::GetConnectionFromWorker(CFTPWorker* workerWithCon // restart keep-alive ReleaseKeepAlive(); WaitForEndOfKeepAlive(SalamanderGeneral->GetMsgBoxParent(), 0); // cannot open the wait window (it is in state 'kamNone') - SetupKeepAliveTimer(TRUE); // set up the keep-alive timer; trigger the keep-alive command right away (we do not know how long the connection was inactive, so let us avoid losing it) + SetupKeepAliveTimer(TRUE); // set up the keep-alive timer; run the keep-alive command immediately (the connection may have been inactive for an unknown length of time, so avoid losing it unnecessarily) } } } diff --git a/src/plugins/ftp/ctrlcon4.cpp b/src/plugins/ftp/ctrlcon4.cpp index 4e121e148..f3bf582bb 100644 --- a/src/plugins/ftp/ctrlcon4.cpp +++ b/src/plugins/ftp/ctrlcon4.cpp @@ -47,7 +47,7 @@ BOOL CControlConnectionSocket::SetCurrentTransferMode(HWND parent, BOOL asciiMod &ftpReplyCode, ftpReplyBuf, ftpReplyBufSize, FALSE, FALSE, TRUE, canRetry, retryMsg, retryMsgBufSize, NULL)) { - if (FTP_DIGIT_1(ftpReplyCode) == FTP_D1_SUCCESS) // success is returned (should be 200) + if (FTP_DIGIT_1(ftpReplyCode) == FTP_D1_SUCCESS) // a success reply was received (it should be 200) { HANDLES(EnterCriticalSection(&SocketCritSect)); leaveSect = TRUE; @@ -60,7 +60,7 @@ BOOL CControlConnectionSocket::SetCurrentTransferMode(HWND parent, BOOL asciiMod ret = FALSE; // error -> connection closed } - if (leaveSect) // the requested transfer mode is already set successfully + if (leaveSect) // the requested transfer mode has already been set successfully { if (success != NULL) *success = TRUE; @@ -234,7 +234,7 @@ BOOL CSendCmdUserIfaceForListAndDownload::CanFinishSending(int replyCode, BOOL* void CSendCmdUserIfaceForListAndDownload::BeforeWaitingForFinish(int replyCode, BOOL* useTimeout) { - if (FTP_DIGIT_1(replyCode) != FTP_D1_SUCCESS) // LIST does not return success - it may not close + if (FTP_DIGIT_1(replyCode) != FTP_D1_SUCCESS) // LIST did not return success, so the data connection may not close at all { // the data connection (e.g., WarFTPD) - wait for the remaining data, but preferably with a timeout *useTimeout = TRUE; // DataConnection->CloseSocketEx(NULL); // to have something to show in the Show Raw Listing panel we must fetch the remaining data @@ -269,8 +269,8 @@ void CSendCmdUserIfaceForListAndDownload::HandleESCWhenWaitingForFinish(HWND par if (esc) { // WaitWnd.SetText(LoadStr(IDS_LISTWNDABORTINGCOMMAND)); // unnecessary, the window will not be shown again - // while the user decides how to respond to the abort, the data connection may finish (that is why - // the dialog says "listing may be incomplete") - then it makes sense to ignore the abort + // while the user decides whether to abort, the data connection may finish (hence the + // "listing may be incomplete" message); then it makes sense to ignore the abort if (DataConnection->IsTransfering(NULL) || DataConnection->IsFlushingDataToDisk()) { DataConnection->CancelConnectionAndFlushing(); // close the "data connection"; the system attempts a "graceful" shutdown (we will not learn the result) @@ -392,7 +392,7 @@ BOOL CControlConnectionSocket::ListWorkingPath(HWND parent, const char* path, ch DWORD ip; unsigned short port; if (FTP_DIGIT_1(ftpReplyCode) == FTP_D1_SUCCESS && // success (should be 227) - FTPGetIPAndPortFromReply(replyBuf, -1, &ip, &port)) // managed to obtain IP and port + FTPGetIPAndPortFromReply(replyBuf, -1, &ip, &port)) // successfully obtained the IP address and port { dataConnection->SetPassive(ip, port, logUID); dataConnection->PassiveConnect(NULL); // the first attempt; the result does not matter (it is checked later) @@ -410,7 +410,7 @@ BOOL CControlConnectionSocket::ListWorkingPath(HWND parent, const char* path, ch { ok = FALSE; if (canRetry) - retryMsgAux = retryMsgBuf; // "retry" is allowed; go to the next reconnect + retryMsgAux = retryMsgBuf; // "retry" is allowed; move on to the next reconnect attempt else { *fatalError = TRUE; // fatal error @@ -438,7 +438,7 @@ BOOL CControlConnectionSocket::ListWorkingPath(HWND parent, const char* path, ch { // error -> connection closed ok = FALSE; if (canRetry) - retryMsgAux = retryMsgBuf; // "retry" is allowed; go to the next reconnect + retryMsgAux = retryMsgBuf; // "retry" is allowed; proceed to the next reconnect attempt else { *fatalError = TRUE; // fatal error @@ -446,11 +446,11 @@ BOOL CControlConnectionSocket::ListWorkingPath(HWND parent, const char* path, ch } } } - else // failed to open the "listen" socket for receiving the data connection from the server -> + else // failed to open the "listen" socket for receiving the data connection from the server, so treat it as a closed connection { // connection closed (so that the standard Retry can be used) ok = FALSE; if (canRetry) - retryMsgAux = retryMsgBuf; // "retry" is allowed; go to the next reconnect + retryMsgAux = retryMsgBuf; // "retry" is allowed; move on to the next reconnect attempt else { *fatalError = TRUE; // fatal error @@ -459,14 +459,14 @@ BOOL CControlConnectionSocket::ListWorkingPath(HWND parent, const char* path, ch } } - if (ok) // if we are still connected, switch the transfer mode to ASCII (ignore success) + if (ok) // if we are still connected, switch the transfer mode to ASCII (ignore the result) { ok = SetCurrentTransferMode(parent, TRUE, NULL, NULL, 0, forceRefresh, &canRetry, retryMsgBuf, 300); if (!ok) // error -> connection closed { if (canRetry) - retryMsgAux = retryMsgBuf; // "retry" is allowed; go to the next reconnect + retryMsgAux = retryMsgBuf; // "retry" is allowed; proceed to the next reconnect attempt else { *fatalError = TRUE; // fatal error @@ -513,8 +513,8 @@ BOOL CControlConnectionSocket::ListWorkingPath(HWND parent, const char* path, ch *pathListingIsBroken = TRUE; // to make it clear that the returned listing is not OK (VxWorks: while listing it can report "error reading entry: 16" and return "550 no files found or ...") } - // VMS returns 550 for an empty directory: we cannot leave the path and the listing can easily - // be considered OK (it can even be cached - it was not interrupted and the server + // VMS returns 550 for an empty directory: we cannot leave this path, and the listing can safely + // be treated as OK (it can even be cached - it was not interrupted, and the server // will most likely not return a different listing) // ret = FALSE; // stop - the path cannot be listed -> a path change is required @@ -562,7 +562,7 @@ BOOL CControlConnectionSocket::ListWorkingPath(HWND parent, const char* path, ch if (FTP_DIGIT_1(ftpReplyCode) == FTP_D1_SUCCESS || FTP_DIGIT_2(ftpReplyCode) != FTP_D2_CONNECTION || noDataTrTimeout || sslErrorOccured != SSLCONERR_NOERROR) - { // if we do not have a description of the network error from the server, we settle for the system description + { // if we do not have a network error description from the server, use the system description systErr = TRUE; if (!trModeHint) trModeHint = err == WSAETIMEDOUT || sslErrorOccured != SSLCONERR_NOERROR; @@ -610,7 +610,7 @@ BOOL CControlConnectionSocket::ListWorkingPath(HWND parent, const char* path, ch if (userIface.WasAborted()) // the user aborted the listing, which terminated the connection (for example on sunsolve.sun.com (Sun Unix) or ftp.chg.ru) - finish with an error (an incomplete listing) { ok = FALSE; // do not display the "list can be incomplete" message; the user was warned during abort - if (canRetry) // take over the message for the message box that announces the connection interruption + if (canRetry) // take over the message for the message box that reports the connection interruption { HANDLES(EnterCriticalSection(&SocketCritSect)); if (ConnectionLostMsg != NULL) @@ -665,7 +665,7 @@ BOOL CControlConnectionSocket::ListWorkingPath(HWND parent, const char* path, ch retryMsgBuf, 300)) { if (strcmp(cmdBuf, path) == 0) // we have the desired working directory on the server - // (assumption: the server returns the same working-path string) +// (assumption: the server always returns the same working-directory string) { pathError = FALSE; ok = TRUE; // successful reconnect; list again @@ -709,7 +709,7 @@ BOOL CControlConnectionSocket::ListWorkingPath(HWND parent, const char* path, ch } } } - else // reconnect failed - finish with an error (an incomplete listing) + else // reconnect failed; end with an error (incomplete listing) { SalamanderGeneral->SalMessageBox(parent, LoadStr(IDS_UNABLETOREADLIST), LoadStr(IDS_FTPERRORTITLE), @@ -745,7 +745,7 @@ BOOL CControlConnectionSocket::ListWorkingPath(HWND parent, const char* path, ch MB_OK | MB_ICONEXCLAMATION); } - *pathListingIsIncomplete = !ok; // TRUE in case of a failure/interruption/connection error + *pathListingIsIncomplete = !ok; // TRUE on connection failure, interruption, or error *pathListingMayBeOutdated = FALSE; // store the date when the listing was created @@ -787,7 +787,7 @@ BOOL CControlConnectionSocket::ListWorkingPath(HWND parent, const char* path, ch *pathListingStartTime); } } - else // failure/interruption/connection error = return at least what we have (the user already knows that "list can be incomplete") + else // on failure, interruption, or a connection error, return at least what we have (the user already knows that "list can be incomplete") { if (*allocatedListing != NULL) { // the buffer does not contain a complete listing -> trim it at the last line ending (CRLF or LF) to make it easier to work with @@ -795,7 +795,7 @@ BOOL CControlConnectionSocket::ListWorkingPath(HWND parent, const char* path, ch char* s = start + *allocatedListingLen; while (s > start && *(s - 1) != '\n') s--; - if (s < start + *allocatedListingLen) // there is a place to write the null terminator (just for easier debugging) + if (s < start + *allocatedListingLen) // there is room to write the null terminator (just for easier debugging) *s = 0; // either at the start of the buffer or after the last LF *allocatedListingLen = (int)(s - start); } @@ -803,7 +803,7 @@ BOOL CControlConnectionSocket::ListWorkingPath(HWND parent, const char* path, ch } if (dataConnection != NULL) // release and possibly close the "data connection" { - if (dataConnection->IsConnected()) // close the "data connection"; the system attempts a "graceful" + if (dataConnection->IsConnected()) // close the "data connection"; the system will attempt a graceful shutdown dataConnection->CloseSocketEx(NULL); // shutdown (we will not learn the result) DeleteSocket(dataConnection); } @@ -1056,8 +1056,8 @@ void CControlConnectionSocket::SetupNextKeepAliveTimer() #endif if (!KeepAliveCmdAllBytesWritten) - { // this should never happen because the server's reply arrives only after the complete command is written - // of the command (the command is always written at once; it is just a few bytes) + { // this should never happen because the server's reply arrives only after the complete + // command has been written (the command is always written at once; it is only a few bytes) TRACE_E("Unexpected situation in CControlConnectionSocket::SetupNextKeepAliveTimer(): KeepAliveCmdAllBytesWritten==FALSE!"); KeepAliveCmdAllBytesWritten = TRUE; } @@ -1081,7 +1081,7 @@ void CControlConnectionSocket::SetupNextKeepAliveTimer() } else { - KeepAliveMode = kamNone; // we should no longer perform keep-alive (there is no point in protecting the connection anymore) + KeepAliveMode = kamNone; // do not perform keep-alive anymore (protecting the connection is no longer useful) Logs.LogMessage(LogUID, LoadStr(IDS_LOGMSGKASTOPPED), -1, TRUE); // notify the user that the keep-alive mode has stopped } } @@ -1133,7 +1133,7 @@ void CControlConnectionSocket::ReleaseKeepAlive() // if the "data connection" is open, close it; it certainly will not be needed now if (closeDataCon != NULL) { - if (closeDataCon->IsConnected()) // close the "data connection"; the system attempts a "graceful" + if (closeDataCon->IsConnected()) // close the "data connection"; the system will attempt a graceful shutdown closeDataCon->CloseSocketEx(NULL); // shutdown (we will not learn the result) DeleteSocket(closeDataCon); // release the "data connection" through a SocketsThread method call } @@ -1236,7 +1236,7 @@ void CControlConnectionSocket::ReceiveTimer(DWORD id, void* param) BOOL listenError; if (!keepAliveDataConAux->OpenForListeningWithProxy(localIP, localPort, &listenError, &error)) { // failed to open the "listen" socket for receiving the data connection from - // the server (a local operation, this should almost never happen) and it can also be + // the server (a local operation, so this should almost never happen); it can also be // an error when connecting to the proxy server Logs.LogMessage(logUID, LoadStr(listenError ? IDS_LOGMSGOPENACTDATACONERROR : IDS_LOGMSGOPENACTDATACONERROR2), -1, TRUE); } @@ -1380,7 +1380,7 @@ CListingCacheItem::CListingCacheItem(const char* host, unsigned short port, cons if (CachedListing != NULL && cachedListing != NULL) { memcpy(CachedListing, cachedListing, cachedListingLen); - CachedListing[cachedListingLen] = 0; // once it is allocated there, make it null-terminated for debugging purposes + CachedListing[cachedListingLen] = 0; // If it is already allocated, make it null-terminated for debugging purposes } else err = TRUE; @@ -1496,7 +1496,7 @@ BOOL CListingCache::GetPathListing(const char* host, unsigned short port, const if (*cachedListing != NULL) { memcpy(*cachedListing, item->CachedListing, item->CachedListingLen); - (*cachedListing)[item->CachedListingLen] = 0; // once it is allocated there, make it null-terminated for debugging purposes + (*cachedListing)[item->CachedListingLen] = 0; // since it is already allocated, make it null-terminated for debugging purposes *cachedListingLen = item->CachedListingLen; } else @@ -1620,7 +1620,7 @@ void CListingCache::AcceptChangeOnPathNotification(const char* userPart, BOOL in HANDLES(EnterCriticalSection(&CacheCritSect)); - int delIndex = 0; // variables for deleting in blocks (shifting the array is O(N*N), so we optimize) + int delIndex = 0; // variables for block deletion (shifting the array is O(N*N), so we optimize) int delCount = 0; int i; for (i = 0; i < Cache.Count; i++) diff --git a/src/plugins/ftp/ctrlcon5.cpp b/src/plugins/ftp/ctrlcon5.cpp index d1524a60a..0423fae18 100644 --- a/src/plugins/ftp/ctrlcon5.cpp +++ b/src/plugins/ftp/ctrlcon5.cpp @@ -70,7 +70,7 @@ void CControlConnectionSocket::DownloadOneFile(HWND parent, const char* fileName char replyBuf[700]; BOOL setStartTimeIfConnected = TRUE; BOOL sslErrReconnect = FALSE; // TRUE = reconnect because of SSL errors - BOOL fastSSLErrReconnect = FALSE; // TRUE = server certificate changed, an immediate reconnect is desirable (without 20 seconds of waiting) + BOOL fastSSLErrReconnect = FALSE; // TRUE = the server certificate changed; an immediate reconnect is desirable (without waiting 20 seconds) while (ReconnectIfNeeded(notInPanel, panel == PANEL_LEFT, parent, userBuf, userBufSize, &reconnected, setStartTimeIfConnected, totalAttemptNum, @@ -109,7 +109,7 @@ void CControlConnectionSocket::DownloadOneFile(HWND parent, const char* fileName userBuf, userBufSize, &success, replyBuf, 700, NULL, totalAttemptNum, NULL, TRUE, NULL); - if (ok && !success && workPath[0] != 0) // send succeeded but the server reports an error (+ignore errors with an empty path) -> file cannot be + if (ok && !success && workPath[0] != 0) // send succeeded but the server reports an error (+ignore errors with an empty path) -> file cannot be downloaded { // downloaded (it is on the current path in the panel) _snprintf_s(errBuf, _TRUNCATE, LoadStr(IDS_CHANGEWORKPATHERROR), workPath, replyBuf); SalamanderGeneral->SalMessageBox(parent, errBuf, LoadStr(IDS_FTPERRORTITLE), @@ -184,7 +184,7 @@ void CControlConnectionSocket::DownloadOneFile(HWND parent, const char* fileName else // failed to open the "listen" socket for accepting the data connection from the server -> { // connection closed (so the standard Retry can be used) ok = FALSE; - if (canRetry) // "retry" is allowed, proceed to the next reconnect + if (canRetry) // "retry" is allowed, proceed to the next reconnect attempt { run = TRUE; retryMsgAux = retryMsgBuf; @@ -192,7 +192,7 @@ void CControlConnectionSocket::DownloadOneFile(HWND parent, const char* fileName } } - if (ok) // if we are still connected, change the transfer mode according to 'asciiMode' (ignore success) + if (ok) // if we are still connected, change the transfer mode according to 'asciiMode' (ignore the result) { if (!SetCurrentTransferMode(parent, asciiMode, NULL, NULL, 0, FALSE, &canRetry, retryMsgBuf, 300)) @@ -234,7 +234,7 @@ void CControlConnectionSocket::DownloadOneFile(HWND parent, const char* fileName int asciiTrForBinFileHowToSolve = 0; if (dataConnection->IsAsciiTrForBinFileProblem(&asciiTrForBinFileHowToSolve)) { // the "ascii transfer mode for binary file" problem was detected - if (asciiTrForBinFileHowToSolve == 0) // we should ask the user + if (asciiTrForBinFileHowToSolve == 0) // ask the user { INT_PTR res = CViewErrAsciiTrForBinFileDlg(parent).Execute(); if (res == IDOK) @@ -405,7 +405,7 @@ void CControlConnectionSocket::DownloadOneFile(HWND parent, const char* fileName dataConnection->WaitForFileClose(5000); // max. 5 seconds if (run) // go for another attempt; clean the target file just in case (it may have been created before the error/interruption) - { // we are not in any critical section, so even if the disk operation stalls for a while, nothing happens + { // we are not in any critical section, so it does not matter if the disk operation stalls for a while SetFileAttributes(tgtFileName, FILE_ATTRIBUTE_NORMAL); DeleteFile(tgtFileName); } @@ -420,7 +420,7 @@ void CControlConnectionSocket::DownloadOneFile(HWND parent, const char* fileName if (*newFileSize != CQuadWord(0, 0)) TRACE_E("CControlConnectionSocket::DownloadOneFile(): unexpected situation: file was not created, but its size is not null!"); - // we are not in any critical section, so even if the disk operation stalls for a while, nothing happens + // we are not in any critical section, so it does not matter if the disk operation stalls for a while SetFileAttributes(tgtFileName, FILE_ATTRIBUTE_NORMAL); // so a read-only file can be overwritten HANDLE file = HANDLES_Q(CreateFile(tgtFileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, @@ -453,8 +453,8 @@ void CControlConnectionSocket::DownloadOneFile(HWND parent, const char* fileName } } - if (dataConnection->IsConnected()) // close the "data connection" if needed; the system attempts a "graceful" - dataConnection->CloseSocketEx(NULL); // shutdown (we do not learn the result) + if (dataConnection->IsConnected()) // close the "data connection" if needed; the system attempts a "graceful" shutdown + dataConnection->CloseSocketEx(NULL); // shutdown (the result is not available) if (!run) break; @@ -530,7 +530,7 @@ BOOL CControlConnectionSocket::CreateDir(char* changedPath, HWND parent, char* n userBuf, userBufSize, &success, replyBuf, 700, NULL, totalAttemptNum, NULL, TRUE, NULL); - if (ok && !success && workPath[0] != 0) // send succeeded but the server reports an error (+ignore errors with an empty path) -> file cannot be + if (ok && !success && workPath[0] != 0) // send succeeded, but the server reports an error (+ignore errors with an empty path) -> file cannot be downloaded { // downloaded (it is on the current path in the panel) _snprintf_s(errBuf, _TRUNCATE, LoadStr(IDS_CHANGEWORKPATHERROR), workPath, replyBuf); SalamanderGeneral->SalMessageBox(parent, errBuf, LoadStr(IDS_FTPERRORTITLE), @@ -561,7 +561,7 @@ BOOL CControlConnectionSocket::CreateDir(char* changedPath, HWND parent, char* n UploadListingCache.ReportCreateDirs(hostBuf, userBuffer, portBuf, workPath, GetFTPServerPathType(workPath), newName, FALSE); } - if (FTP_DIGIT_1(ftpReplyCode) == FTP_D1_SUCCESS && // success is returned (should be 257) + if (FTP_DIGIT_1(ftpReplyCode) == FTP_D1_SUCCESS && // a success reply is returned (should be 257) FTPGetDirectoryFromReply(replyBuf, (int)strlen(replyBuf), newPath, FTP_MAX_PATH)) { // directory 'newPath' has just been created newName[0] = 0; // no focus after refresh yet @@ -578,12 +578,12 @@ BOOL CControlConnectionSocket::CreateDir(char* changedPath, HWND parent, char* n if (FTPIsTheSameServerPath(pathType, newPath, workPath)) lstrcpyn(newName, cutDir, 2 * MAX_PATH); // directory name for focus after the refresh } - else // probably the server returns a relative directory name in reply "257" (e.g. warftpd) + else // the server probably returns a relative directory name in reply "257" (e.g. warftpd) { lstrcpyn(newName, newPath, 2 * MAX_PATH); // directory name for focus after the refresh } } - else // error (including unexpected format of reply "257") + else // error (including an unexpected format of reply "257") { if (!retSuccess) // do not display an error message for a successful reply { @@ -706,7 +706,7 @@ BOOL CControlConnectionSocket::QuickRename(char* changedPath, HWND parent, const userBuf, userBufSize, &success, replyBuf, 700, NULL, totalAttemptNum, NULL, TRUE, NULL); - if (ok && !success && workPath[0] != 0) // send succeeded but the server reports an error (+ignore errors with an empty path) -> file cannot be + if (ok && !success && workPath[0] != 0) // send succeeded, but the server reports an error (+ignore errors for an empty path) -> file cannot be downloaded { // downloaded (it is on the current path in the panel) _snprintf_s(errBuf, _TRUNCATE, LoadStr(IDS_CHANGEWORKPATHERROR), workPath, replyBuf); SalamanderGeneral->SalMessageBox(parent, errBuf, LoadStr(IDS_FTPERRORTITLE), @@ -733,7 +733,7 @@ BOOL CControlConnectionSocket::QuickRename(char* changedPath, HWND parent, const &ftpReplyCode, replyBuf, 700, FALSE, FALSE, FALSE, &canRetry, retryMsgBuf, 300, NULL)) { - if (FTP_DIGIT_1(ftpReplyCode) == FTP_D1_SUCCESS) // success is returned (should be 250) + if (FTP_DIGIT_1(ftpReplyCode) == FTP_D1_SUCCESS) // success returned (should be 250) { // quick rename completed successfully - leave the new name in 'newName' so it can be focused after the refresh retSuccess = TRUE; if (workPath[0] != 0) @@ -840,7 +840,7 @@ BOOL CControlConnectionSocket::OpenForListeningAndWaitForRes(HWND parent, CDataC CSetWaitCursorWindow* winParent = NULL; if (parentIsEnabled) // we cannot leave the parent enabled (the wait window is not modal) { - // store the focus from 'parent' (if the focus is not from 'parent', save NULL) + // save the focused window from 'parent' (if the focus is not in 'parent', save NULL) focusedWnd = GetFocus(); HWND hwnd = focusedWnd; while (hwnd != NULL && hwnd != parent) @@ -864,7 +864,7 @@ BOOL CControlConnectionSocket::OpenForListeningAndWaitForRes(HWND parent, CDataC HANDLES(EnterCriticalSection(&SocketCritSect)); int logUID = LogUID; // log UID of this connection - BOOL handleKeepAlive = KeepAliveMode != kamForbidden; // TRUE if keep-alive is not handled one level above (it must be handled here) + BOOL handleKeepAlive = KeepAliveMode != kamForbidden; // TRUE if keep-alive is not handled at a higher level (it must be handled here) DWORD auxServerIP = ServerIP; int proxyPort = ProxyServer != NULL ? ProxyServer->ProxyPort : 0; HANDLES(LeaveCriticalSection(&SocketCritSect)); @@ -999,7 +999,7 @@ BOOL CControlConnectionSocket::OpenForListeningAndWaitForRes(HWND parent, CDataC } doNotCloseCon = TRUE; } - else // connection error on the proxy server; log the error, close the control connection, and perform "retry" + else // connection error when connecting to the proxy server; log the error, close the control connection, and retry { in_addr srvAddr; srvAddr.s_addr = auxServerIP; diff --git a/src/plugins/ftp/datacon.h b/src/plugins/ftp/datacon.h index 583dc6605..98c3201aa 100644 --- a/src/plugins/ftp/datacon.h +++ b/src/plugins/ftp/datacon.h @@ -188,7 +188,7 @@ class CDataConnectionSocket : public CDataConnectionBaseSocket // shared among all threads - set to "signaled" after the "data connection" closes (after receiving all bytes) and also after the flush to disk is completed (see TgtDiskFileName) HANDLE TransferFinished; - HWND WindowWithStatus; // handle of the window that should receive notifications about changes in the "data connection" state (NULL = do not send anything) + HWND WindowWithStatus; // handle of the window that should receive messages about changes in the "data connection" state (NULL = do not send anything) UINT StatusMessage; // message sent when the "data connection" state changes BOOL StatusMessageSent; // TRUE = the previous message has not been delivered yet, so there is no point sending another one @@ -245,7 +245,7 @@ class CDataConnectionSocket : public CDataConnectionBaseSocket // returns NetEventLastError, ReadBytesLowMemory, TgtFileLastError, NoDataTransTimeout, // SSLErrorOccured, DecomprErrorOccured - // (these use a critical section) + // (protected by a critical section) void GetError(DWORD* netErr, BOOL* lowMem, DWORD* tgtFileErr, BOOL* noDataTransTimeout, int* sslErrorOccured, BOOL* decomprErrorOccured); @@ -287,8 +287,8 @@ class CDataConnectionSocket : public CDataConnectionBaseSocket void SetDirectFlushParams(const char* tgtFileName, CCurrentTransferMode currentTransferMode); // returns the state of the target file when flushing data directly to the TgtDiskFileName file; - // in 'fileCreated' it returns TRUE if the file was created; in 'fileSize' it returns the size - // of the file + // returns TRUE in 'fileCreated' if the file was created; returns the size + // of the file in 'fileSize' void GetTgtFileState(BOOL* fileCreated, CQuadWord* fileSize); // called after the data transfer finishes (successful or not); meaningful only when flushing @@ -296,14 +296,14 @@ class CDataConnectionSocket : public CDataConnectionBaseSocket void CloseTgtFile(); // called by the worker after data flushing finishes; 'flushBuffer' is the buffer that was just flushed - // (it is therefore returned to this object - retrieve it via GiveFlushData(); - // WARNING: it can also be a buffer from 'DecomprDataBuffer'); if there is more data to flush, - // the buffers are swapped and WorkerMsgFlushData is posted to the worker; if necessary it will also post - // FD_READ or FD_CLOSE to this socket (see NeedFlushReadBuf); + // (it is thus returned to this object - see GiveFlushData() to retrieve it; + // WARNING: it can also be a buffer from 'DecomprDataBuffer'); if more data need to be flushed, + // the buffers are swapped and WorkerMsgFlushData is posted to the worker; if needed, + // FD_READ or FD_CLOSE is also posted to this socket (see NeedFlushReadBuf); // 'enterSocketCritSect' is TRUE except for the exception described below // WARNING: this method must not be called from the SocketCritSect critical section (the method uses - // SocketsThread), exception: if we are in CSocketsThread::CritSect and - // SocketCritSect, the call is possible if we set 'enterSocketCritSect' to FALSE + // SocketsThread); exception: if the caller is in both CSocketsThread::CritSect and + // SocketCritSect, the call is allowed if 'enterSocketCritSect' is set to FALSE void FlushDataFinished(char* flushBuffer, BOOL enterSocketCritSect); // if new data are present in FlushBuffer it returns TRUE and the data in 'flushBuffer' @@ -320,10 +320,10 @@ class CDataConnectionSocket : public CDataConnectionBaseSocket // were flushed) void FreeFlushData(); - // called after this data connection closes; returns TRUE if all data are - // flushed (meaning the data connection no longer contains any data); if 'onlyTest' + // called after this data connection is closed; returns TRUE if all data are + // flushed (that is, the data connection no longer contains any data); if 'onlyTest' // is FALSE and necessary, it swaps buffers and posts WorkerMsgFlushData - // to the worker (flush the data); it returns TRUE only after FlushDataFinished is called for + // to the worker to flush the data; returns TRUE only after FlushDataFinished is called for // the last flushed data // WARNING: this method must not be called from the SocketCritSect critical section (the method uses // SocketsThread) @@ -338,10 +338,10 @@ class CDataConnectionSocket : public CDataConnectionBaseSocket // if data are being flushed; otherwise returns FALSE BOOL IsFlushingDataToDisk(); - // returns TRUE if the "ASCII transfer mode for binary file" problem needs to be handled, then - // in 'howToSolve' it returns how to handle the problem: 0 = ask the user, 1 = download - // again in binary mode, 2 = interrupt the file download (cancel); returns FALSE if - // the problem did not occur or the user chose: ignore (finish the download in ASCII + // returns TRUE if the "ASCII transfer mode for binary file" problem needs to be handled; in + // 'howToSolve' it stores how to handle it: 0 = ask the user, 1 = download + // again in binary mode, 2 = cancel the file download; returns FALSE if + // the problem did not occur or the user chose to ignore it (finish the download in ASCII // mode) BOOL IsAsciiTrForBinFileProblem(int* howToSolve); @@ -400,7 +400,7 @@ class CDataConnectionSocket : public CDataConnectionBaseSocket // a Windows error code (came with FD_CLOSE or occurred while handling FD_CLOSE) virtual void SocketWasClosed(DWORD error); - // receiving a timer with ID 'id' and parameter 'param' + // receives a timer with ID 'id' and parameter 'param' virtual void ReceiveTimer(DWORD id, void* param); // receiving a posted message with ID 'id' and parameter 'param' @@ -473,7 +473,7 @@ class CUploadDataConnectionSocket : public CDataConnectionBaseSocket BOOL IsGood() { return BytesToWrite != NULL && FlushBuffer != NULL; } - // returns NetEventLastError, NoDataTransTimeout, and SSLErrorOccured (use a critical section) + // returns NetEventLastError, NoDataTransTimeout, and SSLErrorOccured (protected by a critical section) void GetError(DWORD* netErr, BOOL* noDataTransTimeout, int* sslErrorOccured); // just calls CloseSocket() + sets SocketCloseTime @@ -515,10 +515,10 @@ class CUploadDataConnectionSocket : public CDataConnectionBaseSocket // called by the worker after finishing reading data from disk; 'flushBuffer' is the buffer that was just filled; // if the second data buffer is free and we have not reached the end of the file yet, - // the buffers are swapped and WorkerMsgPrepareData is posted to the worker; if necessary it will also post - // FD_WRITE to this socket (see WaitingForWriteEvent); with compression it ensures - // gradually fills the FlushBuffer with compressed data (until it is full and we are not - // at the end of the file, posts WorkerMsgPrepareData to the worker) + // the buffers are swapped and WorkerMsgPrepareData is posted to the worker; if needed, it also posts + // FD_WRITE to this socket (see WaitingForWriteEvent); with compression, it ensures that + // FlushBuffer is gradually filled with compressed data (while it is not full and we are not yet at + // the end of the file, it posts WorkerMsgPrepareData to the worker) void DataBufferPrepared(char* flushBuffer, int validBytesInFlushBuffer, BOOL enterCS); // called by the worker after receiving the response to the STOR/APPE command from the server (upload is finished on the server side) @@ -567,7 +567,7 @@ class CUploadDataConnectionSocket : public CDataConnectionBaseSocket // a Windows error code (came with FD_CLOSE or occurred while handling FD_CLOSE) virtual void SocketWasClosed(DWORD error); - // receiving a timer with ID 'id' and parameter 'param' + // receives a timer with ID 'id' and parameter 'param' virtual void ReceiveTimer(DWORD id, void* param); // called after FD_ACCEPT is received and processed (assuming CSocket::ReceiveNetEvent is used for FD_ACCEPT) @@ -603,7 +603,7 @@ class CKeepAliveDataConSocket : public CSocket DWORD NetEventLastError; // code of the last error reported to ReceiveNetEvent() or that occurred in PassiveConnect() int SSLErrorOccured; // see constants SSLCONERR_XXX BOOL ReceivedConnected; // TRUE = the "data connection" opened (connect or accept); does not describe the current state - DWORD LastActivityTime; // GetTickCount() from when we last worked with the "data connection" (tracks initialization (SetPassive() and SetActive()), successful connect, and read) + DWORD LastActivityTime; // GetTickCount() value from the last activity on the "data connection" (tracks initialization (SetPassive() and SetActive()), a successful connect, and a read) DWORD SocketCloseTime; // GetTickCount() from the moment the "data connection" socket closed // used when closing the "data connection" (evaluates whether the keep-alive command has finished) @@ -621,11 +621,11 @@ class CKeepAliveDataConSocket : public CSocket CKeepAliveDataConSocket(CControlConnectionSocket* parentControlSocket, CFTPProxyForDataCon* proxyServer, int encryptConnection, CCertificate* certificate); virtual ~CKeepAliveDataConSocket(); - // called when the "control connection" receives the server's response ('replyCode') - // announcing the end of the data transfer; returns TRUE if the transfer really finished (the + // called when the "control connection" receives the server response ('replyCode') + // indicating the end of the data transfer; returns TRUE if the transfer has actually finished (the // "data connection" can be released); returns FALSE if the transfer has not finished yet (the "data connection" // cannot be released); once the transfer actually ends, it indirectly calls SetupNextKeepAliveTimer() - // of the ParentControlSocket object + // on the ParentControlSocket object BOOL FinishDataTransfer(int replyCode); // returns TRUE if the "data connection" is open for data transfer (the connection to the server has already been established) @@ -708,7 +708,7 @@ class CKeepAliveDataConSocket : public CSocket // a Windows error code (came with FD_CLOSE or occurred while handling FD_CLOSE) virtual void SocketWasClosed(DWORD error); - // timer reception with ID 'id' and parameter 'param' + // receives a timer with ID 'id' and parameter 'param' virtual void ReceiveTimer(DWORD id, void* param); // called after FD_ACCEPT is received and processed (assuming CSocket::ReceiveNetEvent is used for FD_ACCEPT) diff --git a/src/plugins/ftp/datacon1.cpp b/src/plugins/ftp/datacon1.cpp index ecdb3d359..3330c5dd8 100644 --- a/src/plugins/ftp/datacon1.cpp +++ b/src/plugins/ftp/datacon1.cpp @@ -131,7 +131,7 @@ BOOL CDataConnectionBaseSocket::PassiveConnect(DWORD* error) conRes = Connect(auxServerIP, auxServerPort, &err); } BOOL ret = TRUE; - if (!conRes) // there is no hope for success + if (!conRes) // no chance of success { HANDLES(EnterCriticalSection(&SocketCritSect)); NetEventLastError = err; // record the error (except fatal errors such as insufficient memory, etc.) @@ -824,7 +824,7 @@ void CDataConnectionSocket::ReceivePostMessage(DWORD id, void* param) } TgtFileLastError = DiskWork.WinError; // store the error when creating/writing to the target file - CloseSocketEx(NULL); // shut down (we will not learn about the result) + CloseSocketEx(NULL); // shutdown (we will not learn the result) FreeFlushData(); // since we are already in the CSocketsThread::CritSect section, this call // can also be made from the CSocket::SocketCritSect section (no deadlock risk) @@ -844,8 +844,8 @@ void CDataConnectionSocket::JustConnected() { ReceivedConnected = TRUE; // if FD_READ arrives before FD_CONNECT (either way it must be connected) TransferSpeedMeter.JustConnected(); - // since we are already in the CSocketsThread::CritSect section, this call - // can also be made from the CSocket::SocketCritSect section (no deadlock risk) + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) DoPostMessageToWorker(WorkerMsgConnectedToServer); // since we are already in the CSocketsThread::CritSect section, this call // can also be made from the CSocket::SocketCritSect section (no deadlock risk) @@ -907,21 +907,21 @@ void CDataConnectionSocket::MoveReadBytesToFlushBuffer() void CDataConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) { SLOW_CALL_STACK_MESSAGE3("CDataConnectionSocket::ReceiveNetEvent(0x%IX, %d)", lParam, index); - DWORD eventError = WSAGETSELECTERROR(lParam); // extract error code of event + DWORD eventError = WSAGETSELECTERROR(lParam); // extract the event error code BOOL logLastErr = FALSE; switch (WSAGETSELECTEVENT(lParam)) // extract event { case FD_CLOSE: // sometimes arrives before the last FD_READ, so we first try FD_READ and if it succeeds, post FD_CLOSE again (FD_READ may succeed again before it) case FD_READ: { - BOOL sendFDCloseAgain = FALSE; // TRUE = FD_CLOSE arrived and there was data to read (handled as FD_READ) => post FD_CLOSE again (the current FD_CLOSE was a false alarm) + BOOL sendFDCloseAgain = FALSE; // TRUE = FD_CLOSE arrived and there was data to read (handled as FD_READ), so post FD_CLOSE again (the current FD_CLOSE was spurious) BOOL skipSendingOfFDClose = FALSE; // TRUE = FD_CLOSE arrived and we are waiting for the data flush, so delay it (do not process it now) HANDLES(EnterCriticalSection(&SocketCritSect)); if (ReceivedConnected || UsePassiveMode) // ignore closing of the "listen" socket { if (eventError == NO_ERROR) // only if no error occurred (according to the help only WSAENETDOWN can happen) { - if (UsePassiveMode) // for an active connection we have to wait for FD_ACCEPT (this socket is the "listen" one, and only then comes the "data connection") + if (UsePassiveMode) // for a passive connection we have to wait for FD_ACCEPT (this socket is the "listen" socket, and only then comes the "data connection") { if (!ReceivedConnected) JustConnected(); @@ -1044,12 +1044,12 @@ void CDataConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) sendFDCloseAgain = TRUE; // if no timer for flushing data with the DATACON_FLUSHTIMEOUT timeout has been created yet, - // and at the same time the need to flush the buffer is not recorded (NeedFlushReadBuf == 0), - // then create a timer for flushing the data + // and the need to flush the buffer has not yet been recorded (NeedFlushReadBuf == 0), + // create a timer for flushing the data if (!FlushTimerAdded && NeedFlushReadBuf == 0) { - // since we are already in the CSocketsThread::CritSect section, this call - // can also be made from the CSocket::SocketCritSect section (no deadlock risk) + // since we are already in CSocketsThread::CritSect, this call + // can also be made from CSocket::SocketCritSect (no deadlock risk) FlushTimerAdded = SocketsThread->AddTimer(Msg, UID, GetTickCount() + DATACON_FLUSHTIMEOUT, DATACON_FLUSHTIMERID, NULL); } @@ -1110,7 +1110,7 @@ void CDataConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) else // all data are stored in the ReadBytes buffer { if (!lowMem && - ReadBytesAllocatedSize - ValidBytesInReadBytesBuf < DATACON_BYTESTOREADONSOCKET) // maly buffer 'ReadBytes' + ReadBytesAllocatedSize - ValidBytesInReadBytesBuf < DATACON_BYTESTOREADONSOCKET) // 'ReadBytes' buffer too small { int newSize = ValidBytesInReadBytesBuf + DATACON_BYTESTOREADONSOCKET + DATACON_BYTESTOREADONSOCKETPREALLOC; @@ -1142,12 +1142,12 @@ void CDataConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) len = SSLLib.SSL_read(SSLConn, ReadBytes + ValidBytesInReadBytesBuf, ReadBytesAllocatedSize - ValidBytesInReadBytesBuf); } - if (len >= 0) // we may have read something (0 = the connection is already closed) + if (len >= 0) // data may have been read (0 = the connection is already closed) { if (len > 0) { - ValidBytesInReadBytesBuf += len; // adjust the number of bytes already read by the newly read ones - TotalReadBytesCount += CQuadWord(len, 0); // adjust the total number of bytes already read by the newly read ones + ValidBytesInReadBytesBuf += len; // adjust the number of bytes already read by the newly read bytes + TotalReadBytesCount += CQuadWord(len, 0); // add the newly read bytes to the total number of bytes already read LastActivityTime = GetTickCount(); // successfully read bytes from the socket if (GlobalLastActivityTime != NULL) GlobalLastActivityTime->Set(LastActivityTime); @@ -1223,7 +1223,7 @@ void CDataConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) // now process FD_CLOSE if (WSAGETSELECTEVENT(lParam) == FD_CLOSE && !skipSendingOfFDClose) { - if (sendFDCloseAgain) // FD_CLOSE came instead of FD_READ => post FD_CLOSE again + if (sendFDCloseAgain) // FD_CLOSE arrived instead of FD_READ => post FD_CLOSE again { PostMessage(SocketsThread->GetHiddenWindow(), WM_APP_SOCKET_MIN + index, (WPARAM)GetSocket(), lParam); @@ -1286,12 +1286,12 @@ void CDataConnectionSocket::SocketWasClosed(DWORD error) if (error != NO_ERROR) NetEventLastError = error; - // since we are already in the CSocketsThread::CritSect section, this call - // can also be made from the CSocket::SocketCritSect section (no deadlock risk) + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) DoPostMessageToWorker(WorkerMsgConnectionClosed); - // since we are already in the CSocketsThread::CritSect section, this call - // can also be made from the CSocket::SocketCritSect section (no deadlock risk) + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) SocketsThread->DeleteTimer(UID, DATACON_TESTNODATATRTIMERID); HANDLES(LeaveCriticalSection(&SocketCritSect)); @@ -1376,13 +1376,13 @@ void CDataConnectionSocket::CloseTgtFile() HANDLES(EnterCriticalSection(&SocketCritSect)); if (TgtDiskFileName[0] != 0) { - if (DiskWorkIsUsed) // if some disk flush is in progress, cancel it + if (DiskWorkIsUsed) // if any disk flush is in progress, cancel it { BOOL workIsInProgress; if (FTPDiskThread->CancelWork(&DiskWork, &workIsInProgress)) { if (workIsInProgress) - DiskWork.FlushDataBuffer = NULL; // the work is in progress; we cannot free the buffer with the data being written/tested, leave it to the disk-work thread (see the cancellation part) - we can write to DiskWork because after Cancel the disk thread must no longer access it (it may no longer exist) + DiskWork.FlushDataBuffer = NULL; // the work is already underway, so we cannot free the buffer with the data being written/tested; leave it to the disk-work thread (see the cancellation part) - we can still write to DiskWork because after Cancel the disk thread must no longer access it (it may not even exist anymore) else { // the work was cancelled before the disk thread started processing it - deallocate the flush buffer if (DiskWork.FlushDataBuffer != NULL) @@ -1392,7 +1392,7 @@ void CDataConnectionSocket::CloseTgtFile() } } } - else // the work is already finished, DATACON_DISKWORKWRITEFINISHED is supposedly on its way (has not arrived yet) + else // the work is already finished, DATACON_DISKWORKWRITEFINISHED should already be on its way (has not arrived yet) { if (DiskWork.FlushDataBuffer != NULL) // the flush buffer is now useless { @@ -1443,7 +1443,7 @@ BOOL CDataConnectionSocket::WaitForFileClose(DWORD timeout) if (tgtDiskFileCloseIndex != -1) return FTPDiskThread->WaitForFileClose(tgtDiskFileCloseIndex, timeout); - return FALSE; // the file probably was not opened at all (or the closing+delete is handled on the disk-work thread - cancellation during the first create+flush disk job) + return FALSE; // the file was probably never opened at all (or the close+delete operation is handled on the disk worker thread - cancellation during the first create+flush disk task) } void CDataConnectionSocket::SetDataTotalSize(CQuadWord const& size) @@ -1551,7 +1551,7 @@ BOOL CDataConnectionSocket::GiveFlushData(char** flushBuffer, int* validBytesInF { int newBytes = (DecomprDataAllocatedSize - DecomprDataDelayedBytes - ZLIBInfo.avail_out) - (ValidBytesInFlushBuffer - AlreadyDecomprPartOfFlushBuffer - ZLIBInfo.avail_in); - if (newBytes != 0) // balance the difference caused by decompression (WARNING: it can also be negative) + if (newBytes != 0) // adjust for the difference caused by decompression (WARNING: it can also be negative) { if (newBytes > 0) { @@ -1580,7 +1580,7 @@ BOOL CDataConnectionSocket::GiveFlushData(char** flushBuffer, int* validBytesInF { *flushBuffer = DecomprDataBuffer; if (err != SAL_Z_STREAM_END && !isFirstDecompFromFlushBuffer && *validBytesInFlushBuffer < DecomprDataAllocatedSize) - { // when continuing to decompress data from FlushBuffer, if it is not the end of the file and the DecomprDataBuffer was not filled (fill level depends on compression ratio, in extreme cases it may be just a single byte), wait with writing to the file until the next cycle (to avoid unnecessary fragmentation) + { // when continuing to decompress data from FlushBuffer, if this is not the end of the file and DecomprDataBuffer is not full (the fill level depends on the compression ratio and in extreme cases may be just one byte), postpone writing to the file until the next cycle (to avoid unnecessary fragmentation) // TRACE_I("flushing: buffer is not full (only " << *validBytesInFlushBuffer << " bytes), waiting..."); DecomprDataDelayedBytes = *validBytesInFlushBuffer; *validBytesInFlushBuffer = 0; // do not write an empty buffer @@ -1658,8 +1658,8 @@ void CDataConnectionSocket::FlushDataFinished(char* flushBuffer, BOOL enterSocke if (CompressData && AlreadyDecomprPartOfFlushBuffer < ValidBytesInFlushBuffer) { // if it is necessary to continue decompressing data from 'FlushBuffer' - // since we are already in the CSocketsThread::CritSect section, this call - // can also be made from the CSocket::SocketCritSect section (no deadlock risk) + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) DoPostMessageToWorker(WorkerMsgFlushData); // if this is direct flushing of data to a file from the data connection, perform it here diff --git a/src/plugins/ftp/datacon2.cpp b/src/plugins/ftp/datacon2.cpp index 52b136eec..e89e02a9b 100644 --- a/src/plugins/ftp/datacon2.cpp +++ b/src/plugins/ftp/datacon2.cpp @@ -456,7 +456,7 @@ void CKeepAliveDataConSocket::ConnectionAccepted(BOOL success, DWORD winError, B JustConnected(); LastActivityTime = GetTickCount(); // a successful accept occurred } - else // an error occurred - log it at least + else // error: log it at least { NetEventLastError = winError; if (proxyError && NetEventLastError == NO_ERROR) @@ -468,20 +468,20 @@ void CKeepAliveDataConSocket::ConnectionAccepted(BOOL success, DWORD winError, B void CKeepAliveDataConSocket::ReceiveNetEvent(LPARAM lParam, int index) { CALL_STACK_MESSAGE3("CKeepAliveDataConSocket::ReceiveNetEvent(0x%IX, %d)", lParam, index); - DWORD eventError = WSAGETSELECTERROR(lParam); // extract error code of event + DWORD eventError = WSAGETSELECTERROR(lParam); // extract the event error code BOOL logLastErr = FALSE; switch (WSAGETSELECTEVENT(lParam)) // extract event { case FD_CLOSE: // sometimes arrives before the final FD_READ, so try FD_READ first and if it succeeds post FD_CLOSE again (another FD_READ may still succeed before it) case FD_READ: { - BOOL sendFDCloseAgain = FALSE; // TRUE = FD_CLOSE arrived and there was data to read (handled as FD_READ) => post FD_CLOSE again (the current FD_CLOSE was a false alarm) + BOOL sendFDCloseAgain = FALSE; // TRUE = FD_CLOSE arrived and there was data to read (handled as FD_READ) => post FD_CLOSE again (the current FD_CLOSE was premature) HANDLES(EnterCriticalSection(&SocketCritSect)); if (ReceivedConnected || UsePassiveMode) // ignore closing of the listen socket { if (eventError == NO_ERROR) // only if no error occurred (documentation says only WSAENETDOWN can happen) { - if (UsePassiveMode) // for an active connection we must wait for FD_ACCEPT (this socket is the listener, then the data connection) + if (UsePassiveMode) // for a passive connection we must wait for FD_ACCEPT (this socket is the listener, then the data connection) { if (!ReceivedConnected) JustConnected(); @@ -928,7 +928,7 @@ void CUploadDataConnectionSocket::UploadFinished() HANDLES(EnterCriticalSection(&SocketCritSect)); if (ConnectionClosedOnEOF && SkippedWriteAfterConnect > 0) - { // account bytes from local buffers in the upload speed (we are not sure the local buffers will be sent, but without them the speed on small files that fit almost entirely into local buffers would be completely wrong—absurdly low) + { // include bytes from local buffers in the upload speed (we are not sure the local buffers will be sent, but without them the speed for small files that fit almost entirely into local buffers would be completely wrong: absurdly low) DWORD ti = GetTickCount(); TransferSpeedMeter.BytesReceived(SkippedWriteAfterConnect, ti); if (GlobalTransferSpeedMeter != NULL) @@ -1017,7 +1017,7 @@ void CUploadDataConnectionSocket::ConnectionAccepted(BOOL success, DWORD winErro SSLErrorOccured = SSLCONERR_NOERROR; JustConnected(); } - else // an error occurred - log it at least + else // error: log it at least { NetEventLastError = winError; if (proxyError && NetEventLastError == NO_ERROR) @@ -1031,7 +1031,7 @@ DWORD GetPacketSizeEstimation(DWORD speed, DWORD tooBigPacketSize) if (tooBigPacketSize == -1) tooBigPacketSize = 1000000; // disable tooBigPacketSize if (speed < 4096 || tooBigPacketSize <= 1024) - return 512; // select this even if tooBigPacketSize forbids it (something must be chosen) + return 512; // choose this even if tooBigPacketSize forbids it (something must be chosen) else { if (speed < 8192 || tooBigPacketSize <= 4096) @@ -1108,7 +1108,7 @@ void CUploadDataConnectionSocket::MoveFlushBufferToBytesToWrite() void CUploadDataConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) { CALL_STACK_MESSAGE3("CUploadDataConnectionSocket::ReceiveNetEvent(0x%IX, %d)", lParam, index); - DWORD eventError = WSAGETSELECTERROR(lParam); // extract error code of event + DWORD eventError = WSAGETSELECTERROR(lParam); // extract the event error code BOOL logLastErr = FALSE; switch (WSAGETSELECTEVENT(lParam)) // extract event { @@ -1121,7 +1121,7 @@ void CUploadDataConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) WaitingForWriteEvent = FALSE; // assumption: starting the write will require posting FD_WRITE (if send returns a "would-block" error we switch the value to TRUE) if (eventError == NO_ERROR) { - if (UsePassiveMode) // for an active connection we must wait for FD_ACCEPT (this socket is the listener, then the data connection) + if (UsePassiveMode) // for a passive connection we must wait for FD_ACCEPT (this socket is the listener, then the data connection) { if (!ReceivedConnected) JustConnected(); // if FD_WRITE arrives before FD_CONNECT (it still must be connected) @@ -1206,7 +1206,7 @@ void CUploadDataConnectionSocket::ReceiveNetEvent(LPARAM lParam, int index) if (GlobalLastActivityTime != NULL) GlobalLastActivityTime->Set(LastActivityTime); if (LastActivityTime - FirstWriteAfterConnectTime > 100) - { // during upload the local buffer fills first (e.g. 8KB in 1ms or 45KB in 8ms when connected to localhost, apparently both send and receive buffers fill up), we do not measure the rate of this filling because it would artificially and unfairly boost the upload speed + { // during upload, the local buffer fills first (e.g. 8KB in 1ms or 45KB in 8ms when connected to localhost, apparently both send and receive buffers fill up); we do not measure this fill rate because it would artificially and meaninglessly increase the upload speed TransferSpeedMeter.BytesReceived(decomprSentLen, LastActivityTime); if (CompressData) ComprTransferSpeedMeter.BytesReceived(sentLen, LastActivityTime); @@ -1533,7 +1533,7 @@ void CUploadDataConnectionSocket::DataBufferPrepared(char* flushBuffer, int vali AlreadyComprPartOfFlushBuffer = (int)(ZLIBInfo.next_out - (BYTE*)FlushBuffer); DecomprBytesInFlushBuffer += validBytesInFlushBuffer - ZLIBInfo.avail_in; if (err == SAL_Z_STREAM_END) - EndOfFileReached = TRUE; // managed to compress all data and finish the stream == we are at the end of the file + EndOfFileReached = TRUE; // all data was compressed and the stream was finished == we are at the end of the file if (err < 0) TRACE_E("SalZLIB->Deflate returns unexpected error: " << err); else // successful compression diff --git a/src/plugins/ftp/dialogs.h b/src/plugins/ftp/dialogs.h index f8dcc9119..f58b10a09 100644 --- a/src/plugins/ftp/dialogs.h +++ b/src/plugins/ftp/dialogs.h @@ -40,27 +40,27 @@ void HandleOperationsCombo(int* value, CTransferInfo& ti, int resID, int arrValu void ProxyComboBox(HWND hWindow, CTransferInfo& ti, int ctrlID, int& proxyUID, BOOL addDefault, CFTPProxyServerList* proxyServerList); -// 'lastCheck' (in/out) stores the last state of the checkbox, 'lastCheck' initializes to -1; -// 'valueBuf' is a buffer for the value in the "checked" state with size of at least 31 characters, -// 'valueBuf' initializes to an empty string; +// 'lastCheck' (in/out) stores the last checkbox state; 'lastCheck' is initialized to -1; +// 'valueBuf' is a buffer for the value in the "checked" state, at least 31 characters long; +// 'valueBuf' is initialized to an empty string; // 'checkedVal' is the initial value in the "checked" state; -// 'globValUsed'+'globVal' - value for the third state of the checkbox (is it used? + value) +// 'globValUsed'+'globVal' specify the third checkbox state (whether it is used and its value) void CheckboxEditLineInteger(HWND dlg, int checkboxID, int editID, int* lastCheck, char* valueBuf, int checkedVal, BOOL globValUsed, int globVal); -// 'lastCheck' (in/out) stores the last state of the checkbox, 'lastCheck' initializes to -1; -// 'valueBuf' is a buffer for the value in the "checked" state with size of at least 31 characters, -// 'valueBuf' initializes to an empty string; +// 'lastCheck' (in/out) stores the last checkbox state value; initialize 'lastCheck' to -1. +// 'valueBuf' is a buffer for the value in the "checked" state, with a size of at least 31 characters; +// initialize 'valueBuf' to an empty string. // 'checkedVal' is the initial value in the "checked" state; -// 'globValUsed'+'globVal' - value for the third state of the checkbox (is it used? + value) +// 'globValUsed'+'globVal' - value for the third state of the checkbox (used? + value) void CheckboxEditLineDouble(HWND dlg, int checkboxID, int editID, int* lastCheck, char* valueBuf, double checkedVal, BOOL globValUsed, double globVal); -// 'lastCheck' (in/out) stores the last state of the checkbox, 'lastCheck' initializes to -1; -// 'valueBuf' is a buffer for the value in the "checked" state (index in the combo box), -// 'valueBuf' initializes to -1; -// 'checkedVal' is the initial value in the "checked" state (index in the combo box); -// 'globValUsed'+'globVal' - value for the third state of the checkbox (is it used? + value) +// 'lastCheck' (in/out) stores the last checkbox state; 'lastCheck' is initialized to -1; +// 'valueBuf' stores the value in the "checked" state (combo box index); +// 'valueBuf' is initialized to -1; +// 'checkedVal' is the initial value in the "checked" state (combo box index); +// 'globValUsed'+'globVal' specify the third checkbox state (whether it is used and its value) void CheckboxCombo(HWND dlg, int checkboxID, int comboID, int* lastCheck, int* valueBuf, int checkedVal, BOOL globValUsed, int globVal); @@ -193,7 +193,7 @@ class CConfigPageLogs : public CCommonPropSheetPage { protected: int LastLogMaxSize; // last value of the "log max size" checkbox - char LogMaxSizeBuf[31]; // buffer to keep the contents of the "log max size" line + char LogMaxSizeBuf[31]; // buffer holding the contents of the "log max size" field int LastMaxClosedConLogs; // last value of the "max disconnected connection logs" checkbox char MaxClosedConLogsBuf[31]; // buffer to keep the contents of the "max disconnected connection logs" line @@ -416,8 +416,8 @@ class CRenameDlg : public CCenteredDialog protected: char* Name; // listbox item name (for edit line + checkbox) - BOOL NewServer; // TRUE/FALSE: dialog New/Rename - BOOL AddBookmark; // TRUE/FALSE: Connect:Add Bookmark dialog / applies to NewServer + BOOL NewServer; // TRUE/FALSE: New/Rename dialog + BOOL AddBookmark; // TRUE/FALSE: Connect:Add Bookmark dialog / only when NewServer is TRUE BOOL ServerTypes; // FALSE/TRUE: Connect/Configuration:Servers dialog char* CopyFromName; // only if ServerTypes==TRUE: name for the checkbox (differs from the name for the edit line) @@ -478,8 +478,8 @@ class CWaitWindow : public CWindow CWaitWindow(HWND hParent, BOOL showCloseButton); ~CWaitWindow(); - // returns TRUE if the user clicked the wait-window close button with the mouse; it returns TRUE - // only once and the next TRUE comes only after another click of the close button + // returns TRUE if the user clicked the wait-window close button with the mouse; + // it returns TRUE only once per click of the close button BOOL GetWindowClosePressed() { BOOL ret = WindowClosePressed; @@ -785,7 +785,7 @@ class CEditServerTypeDlg : public CCenteredDialog { protected: HWND HListView; // listview with columns - BOOL CanReadListViewChanges; // TRUE = record checkbox changes in the list-view, FALSE = undesirable while filling the list-view + BOOL CanReadListViewChanges; // TRUE = record checkbox changes in the list-view; FALSE = do not record them while filling the list-view CServerType* ServerType; // edited server type (changes may occur only after pressing the OK button) TIndirectArray ColumnsData; // columns shown in the dialog (data for the listview with columns) @@ -821,10 +821,10 @@ class CEditSrvTypeColumnDlg : public CCenteredDialog BOOL Edit; // TRUE = editing, FALSE = adding a new column int* EditedColumn; // IN: index (in 'ColumnsData') of the edited column, OUT: focus index - int LastUsedIndexForName; // -1==invalid, otherwise index in the combo of the last Name selection - int LastUsedIndexForDescr; // -1==invalid, otherwise index in the combo of the last Description selection + int LastUsedIndexForName; // -1==invalid, otherwise the index of the last Name selection in the combo box + int LastUsedIndexForDescr; // -1==invalid, otherwise the index of the last Description selection in the combo box - BOOL FirstSelNotifyAfterTransfer; // TRUE = data were just set into the dialog, the posted CBN_SELCHANGE for combo Type must not change Alignment + BOOL FirstSelNotifyAfterTransfer; // TRUE = data were just set into the dialog; the posted CBN_SELCHANGE for combo Type must not change the Alignment value public: CEditSrvTypeColumnDlg(HWND parent, TIndirectArray* columnsData, @@ -990,7 +990,7 @@ class CChangeAttrsDlg : public CCenteredDialog #define OPERDLG_STATUSMINIDLETIME 950 // minimum time gap for the next update (periodic or from a worker) after the last worker update - WARNING: tied to WORKER_STATUSUPDATETIMEOUT #define OPERDLG_GETDISKSPACEPERIOD 3000 // time after which free space on the target disk is fetched again #define OPERDLG_SHOWERRMINIDLETIME 10000 // minimum idle time in the dialog before an error is shown automatically (see Config.OpenSolveErrIfIdle) -#define OPERDLG_AUTOSHOWERRTIMER 4 // timer ID for a periodic test whether a Show Error dialog should appear +#define OPERDLG_AUTOSHOWERRTIMER 4 // timer ID for periodically checking whether a Show Error dialog should be displayed #define OPERDLG_AUTOSHOWERRPERIOD 1000 // timer period for testing whether a Show Error dialog should appear #define OPERDLG_AUTOSHOWERRTIMER2 5 // helper timer: ensures "immediate" delivery of OPERDLG_AUTOSHOWERRTIMER #define OPERDLG_CORRECTBTNSTIMER 6 // timer ID for checking button states shortly after the dialog is activated (focus is unfortunately unknown at activation) @@ -998,7 +998,7 @@ class CChangeAttrsDlg : public CCenteredDialog #define WM_APP_DISABLEDETAILED WM_APP + 1 // [0, 0] - disable the Detailed button after maximizing #define WM_APP_ACTIVATEWORKERS WM_APP + 2 // [0, 0] - activate workers after opening the dialog #define WM_APP_WORKERCHANGEREP WM_APP + 3 // [0, 0] - a worker change was reported, we must read from the operation where the change happened (see CFTPOperation::GetChangedWorker()) -#define WM_APP_ITEMCHANGEREP WM_APP + 4 // [0, 0] - an item change was reported, we must read from the operation where the changes happened (see CFTPOperation::GetChangedItems()) +#define WM_APP_ITEMCHANGEREP WM_APP + 4 // [0, 0] - an item change was reported; query the operation for where the changes happened (see CFTPOperation::GetChangedItems()) #define WM_APP_OPERSTATECHANGE WM_APP + 5 // [0, 0] - the operation state changed (done/in progress/completed with errors), we must read the state from the operation (see CFTPOperation::GetOperationState()) #define WM_APP_HAVEDISKFREESPACE WM_APP + 6 // [0, 0] - the thread checking disk free space reports that it has a result #define WM_APP_CLOSEDLG WM_APP + 7 // [0, 0] - the progress dialog should close (uses auto-close) @@ -1048,7 +1048,7 @@ class COperDlgListView : public CWindow public: HWND HToolTip; COperationDlg* OperDlg; // dialog in which the listview exists - BOOL ConsOrItems; // TRUE/FALSE = take data from the Connections/Operations listview + BOOL ConsOrItems; // TRUE/FALSE = take data from the Connections/Operations listview, respectively int LastItem; int LastSubItem; @@ -1102,12 +1102,12 @@ class COperationDlg : public CDialog char ItemsTextBuf[3][OPERDLG_ITEMSTEXTBUFSIZE]; // buffers for LVN_GETDISPINFO text in the Operations listview int ItemsActTextBuf; // which of the three buffers is currently free for LVN_GETDISPINFO in the Operations listview - BOOL SimpleLook; // TRUE/FALSE = simple (after the split bar) / detailed (complete) dialog look + BOOL SimpleLook; // TRUE/FALSE = simple / detailed (complete) dialog appearance char* TitleText; // text for the dialog title (without the initial "(XX%) ") BOOL IsDirtyStatus; // TRUE = status/progress of the operation needs update (the dialog must redraw status/progress) - BOOL IsDirtyProgress; // TRUE = a worker changed; maybe (if the worker changed due to progress) status/progress needs update (the dialog must redraw status/progress) + BOOL IsDirtyProgress; // TRUE = a worker changed; status/progress of the operation may need an update (the dialog must redraw status/progress if the worker changed due to progress) DWORD LastUpdateOfProgressByWorker; // GetTickCount at the last update of progress triggered by a worker (used to skip unnecessarily frequent updates with multiple workers + skip periodic updates) BOOL IsDirtyConsListView; // TRUE = the Connections listview content changed (needs repaint in the dialog) BOOL IsDirtyItemsListView; // TRUE = the Operations listview content changed (needs repaint in the dialog) @@ -1124,8 +1124,8 @@ class COperationDlg : public CDialog BOOL EnableChangeFocusedItemUID; // TRUE = change FocusedItemUID when focus changes (FALSE is used during listview refresh to prevent unwanted changes to FocusedItemUID) BOOL UserWasActive; // TRUE = prevent the window from closing automatically after the operation finishes successfully (the user was doing something and the dialog would vanish) - BOOL DelayAfterCancel; // TRUE = do not open another Solve Error dialog immediately after Cancel in the previous Solve Error dialog - BOOL CloseDlgWhenOperFin; // FALSE = do not close the window after operation completion = the window may close only if Config.CloseOperationDlgIfSuccessfullyFinished==TRUE + BOOL DelayAfterCancel; // TRUE = do not open another Solve Error dialog immediately after pressing Cancel in the previous Solve Error dialog + BOOL CloseDlgWhenOperFin; // FALSE = do not close the window after the operation finishes = the window may close if Config.CloseOperationDlgIfSuccessfullyFinished==TRUE DWORD ClearChkboxTime; HWND LastFocusedControl; // last focused control in the dialog DWORD LastActivityTime; // GetTickCount() from the time of the user's last activity @@ -1198,7 +1198,7 @@ class COperationDlg : public CDialog int ConnectionsActHeight; // current height of the Connections listview int ConsAddActYOffset; // current y-offset of the Add button below the Connections listview int ConnectionsActHeightLimit; // current height limit for the Connections listview - BOOL InListViewSplit; // TRUE = the mouse is in the area where dragging changes the Connections listview height against the Operations listview + BOOL InListViewSplit; // TRUE = the mouse is in the area where dragging changes the Connections listview height relative to the Operations listview height BOOL Captured; // TRUE = the mouse is captured by us int DragOriginY; // Y coordinate of the left-button press (start of the drag) double ListviewSplitRatio; // ratio between the Connections listview height and the total height for the listviews @@ -1251,9 +1251,9 @@ class COperationDlg : public CDialog // updates is OPERDLG_UPDATEPERIOD milliseconds void ScheduleDelayedUpdate(); - // draws (shows) new values of all changed data displayed in the dialog + // updates displayed values of all changed data in the dialog // (used for delayed data refresh); returns TRUE if - // something needed updating + // anything needed updating BOOL UpdateDataInDialog(); // ensures setting the close button (Close/Cancel); 'flashTitle' is TRUE @@ -1529,7 +1529,7 @@ class CViewErrAsciiTrForBinFileDlg : public CCenteredDialog // // helper object for the Script edit control (custom context menu + does not -// select-all when the control gets focus) +// select all when the control gets focus) class CProxyScriptControlWindow : public CWindow { public: diff --git a/src/plugins/ftp/dialogs1.cpp b/src/plugins/ftp/dialogs1.cpp index 2a7d1774e..dd7625792 100644 --- a/src/plugins/ftp/dialogs1.cpp +++ b/src/plugins/ftp/dialogs1.cpp @@ -27,7 +27,7 @@ CCenteredDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) // horizontal and vertical centering of the dialog relative to the parent if (Parent != NULL) SalamanderGeneral->MultiMonCenterWindow(HWindow, Parent, TRUE); - break; // I want the focus from DefDlgProc + break; // Let DefDlgProc set the focus } } return CDialog::DialogProc(uMsg, wParam, lParam); @@ -538,7 +538,7 @@ CConfigPageDefaults::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) HWND combo = GetDlgItem(HWindow, IDC_PROXYSERVER); int sel = (int)SendMessage(combo, CB_GETCURSEL, 0, 0); int count = (int)SendMessage(combo, CB_GETCOUNT, 0, 0); - int fixedItems = 1; // this will be 2 for "not used" + "default" + int fixedItems = 1; // this will be 2 for "not used" and "default" EnableMenuItem(subMenu, CM_EDITPROXYSRV, MF_BYCOMMAND | ((sel != CB_ERR && count != CB_ERR ? sel >= fixedItems : FALSE) ? MF_ENABLED : MF_DISABLED | MF_GRAYED)); EnableMenuItem(subMenu, CM_DELETEPROXYSRV, MF_BYCOMMAND | ((sel != CB_ERR && count != CB_ERR ? sel >= fixedItems : FALSE) ? MF_ENABLED : MF_DISABLED | MF_GRAYED)); EnableMenuItem(subMenu, CM_MOVEUPPROXYSRV, MF_BYCOMMAND | ((sel != CB_ERR && count != CB_ERR ? sel > fixedItems : FALSE) ? MF_ENABLED : MF_DISABLED | MF_GRAYED)); @@ -647,7 +647,7 @@ class CCenteredPropertyWindow : public CWindow case WM_APP + 1000: // we should detach from the dialog (already centered) { DetachWindow(); - delete this; // a bit hacky, but nothing touches 'this' anymore, so it's fine + delete this; // a bit of a hack, but 'this' will no longer be accessed afterward return 0; } } @@ -821,7 +821,7 @@ CBookmarksListbox::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) break; } } - break; // let the keys propagate, the listbox should not handle them, no problem + break; // pass the keys on; the listbox should not process them } case WM_LBUTTONDBLCLK: @@ -1210,7 +1210,7 @@ void CConnectDlg::RefreshList(BOOL focusLast) void CConnectDlg::MoveItem(HWND list, int fromIndex, int toIndex, int topIndex) { - if (fromIndex > 0 && toIndex > 0 && fromIndex != toIndex && // nobody is allowed to move the quick-connect entry + if (fromIndex > 0 && toIndex > 0 && fromIndex != toIndex && // the quick-connect entry must not be moved fromIndex <= TmpFTPServerList.Count && toIndex <= TmpFTPServerList.Count) // movement stays within the array { fromIndex--; @@ -1411,7 +1411,7 @@ CConnectDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) SendMessage(HWindow, WM_NEXTDLGCTL, (WPARAM)button, TRUE); PostMessage(HWindow, uMsg, wParam, lParam); // postpone this command CanChangeFocus = FALSE; // prevents an infinite loop - return TRUE; // do nothing; wait for the kill focus in the edit boxes + return TRUE; // do nothing; wait for the edit boxes to lose focus } CanChangeFocus = TRUE; @@ -1442,7 +1442,7 @@ CConnectDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) HWND wnd = GetFocus(); while (wnd != NULL && wnd != ctrl) wnd = GetParent(wnd); - if (wnd == NULL) // set focus only if the control is not an ancestor of GetFocus + if (wnd == NULL) // set focus only if the control is not an ancestor of the window returned by GetFocus { // for example, the edit line in the combo box SendMessage(HWindow, WM_NEXTDLGCTL, (WPARAM)ctrl, TRUE); } @@ -1466,7 +1466,7 @@ CConnectDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) // if the connection needs passwords, we must be able to decrypt them // test the bookmark if (!s->EnsurePasswordCanBeDecrypted(HWindow)) - return TRUE; // failed to enter the master password or it probably failed to decrypt the password + return TRUE; // the master password was not entered, or the password probably could not be decrypted with it // WARNING: s->EnsurePasswordCanBeDecrypted() might have cleared the password in 's' and its stored copy, which means // returning to the dialog (return TRUE) requires performing a "refresh" @@ -1481,7 +1481,7 @@ CConnectDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) SelChanged(); EnableControls(); - return TRUE; // failed to enter the master password or they could not decrypt the password + return TRUE; // master password entry failed or the password could not be decrypted } } break; diff --git a/src/plugins/ftp/dialogs2.cpp b/src/plugins/ftp/dialogs2.cpp index d0d42e052..c7cebeb66 100644 --- a/src/plugins/ftp/dialogs2.cpp +++ b/src/plugins/ftp/dialogs2.cpp @@ -411,7 +411,7 @@ void CLogsDlg::LoadLog(int updateUID) if (updateUID != -1) // the log with UID 'updateUID' should be updated { - BOOL found = (actLogUID == updateUID); // TRUE = the combo has the updated log with UID 'actLogUID' selected + BOOL found = (actLogUID == updateUID); // TRUE = the combo has the log with UID 'actLogUID' selected for update MSG msg; // remove other messages requesting a log update (update the current log) while (PeekMessage(&msg, NULL, WM_APP_UPDATELOG, WM_APP_UPDATELOG, PM_REMOVE)) { @@ -582,7 +582,7 @@ CLogsDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) for (i = 0; i < count; i++) { if (SendMessage(combo, CB_GETITEMDATA, i, 0) == (int)wParam) // find the UID // FIXME_X64 suspicious cast - { // (unfortunately we cannot search directly in Logs - a changed log count would misalign the index) + { // (unfortunately we cannot search directly in Logs - if the number of logs changes, the index would no longer match) if (SendMessage(combo, CB_GETCURSEL, 0, 0) != i) { SendMessage(combo, CB_SETCURSEL, i, 0); @@ -1111,8 +1111,8 @@ CWaitWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) // the application was deactivated and the wait window should be shown (no longer hidden because of a dialog) if (!Visible && wParam == FALSE && HasTimer) Show(TRUE); // the window must be shown so Salamander can be reached via Alt+Tab - break; // WM_ACTIVATEAPP arrives even when neither the wait window nor its parent is active (any - } // modeless dialog without a parent - previously the Logs dialog) - the wait window cannot be activated + break; // WM_ACTIVATEAPP arrives even when neither the wait window nor its parent is active + } // for example, for a modeless dialog without a parent; the wait window cannot be activated case WM_ACTIVATE: { @@ -1161,8 +1161,8 @@ CWaitWindow::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) case WM_NCHITTEST: { - // prevent moving the window by dragging its title bar - // also block the tooltip above the Close button + // prevent moving the window by dragging the title bar + // also block the tooltip over the Close button return HTCLIENT; } @@ -1448,7 +1448,7 @@ void CListWaitWindow::RefreshTimeAndStatusAndProgress(BOOL fromTimer) int asciiTrForBinFileHowToSolve = 0; if (Visible && DataConnection->IsAsciiTrForBinFileProblem(&asciiTrForBinFileHowToSolve)) { // detected the "ascii transfer mode for binary file" problem, ask how to solve it - if (asciiTrForBinFileHowToSolve == 0) // we should ask the user + if (asciiTrForBinFileHowToSolve == 0) // ask the user { Show(FALSE); INT_PTR res = CViewErrAsciiTrForBinFileDlg(HParent).Execute(); diff --git a/src/plugins/ftp/dialogs3.cpp b/src/plugins/ftp/dialogs3.cpp index 21cd64327..309db12a2 100644 --- a/src/plugins/ftp/dialogs3.cpp +++ b/src/plugins/ftp/dialogs3.cpp @@ -599,7 +599,7 @@ CEditServerTypeDlg::CEditServerTypeDlg(HWND parent, CServerType* serverType) } } if (!ok) - ColumnsData.DestroyMembers(); // safeguard against a potential overlooked error + ColumnsData.DestroyMembers(); // safeguard in case an error was overlooked RawListing = NULL; RawListIncomplete = FALSE; @@ -663,7 +663,7 @@ void CEditServerTypeDlg::Validate(CTransferInfo& ti) delete parser; // the parser is OK, delete it again else // display the error and mark the error in the "rules for parsing" edit box { - if (errorResID != -1) // some "reasonable" error was found, comment on it + if (errorResID != -1) // some "reasonable" error was found, report it { char buf[300]; sprintf(buf, LoadStr(IDS_STPAR_UNABLECOMPPARSER), LoadStr(errorResID)); @@ -767,7 +767,7 @@ void CEditServerTypeDlg::Transfer(CTransferInfo& ti) } } if (!ok) - ServerType->Columns.DestroyMembers(); // safeguard against a potential overlooked error + ServerType->Columns.DestroyMembers(); // safeguard against a possible missed error } // if the data changed, we must change the server type to "user defined" @@ -829,7 +829,7 @@ void CEditServerTypeDlg::RefreshListView(BOOL onlySet, int selIndex) CanReadListViewChanges = FALSE; // LockWindowUpdate(HListView); // do not use - it makes the entire Windows flicker SendMessage(HListView, WM_SETREDRAW, FALSE, 0); - // I see no reason to dim the window here; there are few columns and calling SetColumnWidths() + // I see no reason to hide the window here; there are few columns and calling SetColumnWidths() // does not cause the list view to flicker // SetWindowPos(HListView, NULL, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_HIDEWINDOW | SWP_NOREDRAW | SWP_NOSENDCHANGING | SWP_NOZORDER); @@ -920,7 +920,7 @@ void CEditServerTypeDlg::RefreshListView(BOOL onlySet, int selIndex) ListView_SetItemState(HListView, selIndex, state, state); ListView_EnsureVisible(HListView, selIndex, FALSE); } - // LockWindowUpdate(NULL); // do not use - it makes the entire Windows flicker + // LockWindowUpdate(NULL); // do not use - the entire Windows UI flickers // SetWindowPos(HListView, NULL, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW | SWP_NOREDRAW | SWP_NOSENDCHANGING | SWP_NOZORDER); SendMessage(HListView, WM_SETREDRAW, TRUE, 0); @@ -1589,7 +1589,7 @@ MENU_TEMPLATE_ITEM EditServerTypeADCondMenu[] = } else // display the error and mark the error in the "rules for parsing" edit box { - if (errorResID != -1) // some "reasonable" error was found, comment on it + if (errorResID != -1) // a "reasonable" error was found; report it { char buf[300]; sprintf(buf, LoadStr(IDS_STPAR_UNABLECOMPPARSER), LoadStr(errorResID)); diff --git a/src/plugins/ftp/dialogs4.cpp b/src/plugins/ftp/dialogs4.cpp index 470f4d8cf..1c0753516 100644 --- a/src/plugins/ftp/dialogs4.cpp +++ b/src/plugins/ftp/dialogs4.cpp @@ -179,8 +179,8 @@ void CEditSrvTypeColumnDlg::Transfer(CTransferInfo& ti) } else { - // if the user has custom text, pull it out, otherwise use indexes from the last selection - // in the combo (finding the index by looking up the string in the list is impossible, duplicate strings may occur) + // if the user has custom text, retrieve it; otherwise use the indexes from the last selection + // in the combo box (finding the index by looking up the string in the list is impossible because duplicate strings may occur) if (LastUsedIndexForName == -1) GetWindowText(comboName, bufName, STC_NAME_MAX_SIZE); if (LastUsedIndexForDescr == -1) @@ -957,7 +957,7 @@ void CSrvTypeTestParserDlg::LoadTextFromFile() HANDLES(CloseHandle(file)); SetCursor(oldCur); - if (err != NO_ERROR) // print the error + if (err != NO_ERROR) // display the error { sprintf(buf, LoadStr(IDS_SRVTYPE_READRAWLISTERR), SalamanderGeneral->GetErrorText(err)); SalamanderGeneral->SalMessageBox(HWindow, buf, LoadStr(IDS_FTPERRORTITLE), diff --git a/src/plugins/ftp/dialogs5.cpp b/src/plugins/ftp/dialogs5.cpp index 453af42d9..2f8724e61 100644 --- a/src/plugins/ftp/dialogs5.cpp +++ b/src/plugins/ftp/dialogs5.cpp @@ -452,7 +452,7 @@ BOOL COperationDlg::UpdateDataInDialog() if (totalCount > 0 && transferIdleTime <= 30) { DWORD secs = (SMPLCMD_APPROXBYTESIZE * waitingCount) / speed; // estimate remaining seconds - secs++; // add one second so we end with "time left: 1 sec" instead of 0 sec + secs++; // add one more second so we finish the operation with "time left: 1 sec" (instead of 0 sec) if (LastTimeEstimation != -1) secs = (2 * secs + LastTimeEstimation) / 3; // rounding calculation (roughly 10% error + round to nice numbers 1,2,5,10,20,40) @@ -720,7 +720,7 @@ BOOL COperationDlg::UpdateDataInDialog() // determine what actually changed int itemUID1, itemUID2; Oper->GetChangedItems(&itemUID1, &itemUID2); - if (!ShowOnlyErrors && itemUID1 != -1) // change of a single item (ShowOnlyErrors disallows this; must refresh all items because the item may hide/show) + if (!ShowOnlyErrors && itemUID1 != -1) // change of a single item (not allowed with ShowOnlyErrors; all items must be refreshed because the item may be hidden or shown) { // redraw the changed item int index1 = Queue->GetItemIndex(itemUID1); @@ -831,7 +831,7 @@ void COperationDlg::RefreshConnections(BOOL init, int newFocusIndex, int refresh if (!ConsListViewObj.Scrolling) ListView_EnsureVisible(ConsListView, 0, FALSE); } - else // refresh the list view as gently as possible (preserves top index and focus by UID or the last focus) + else // refresh the list view with minimal disruption (preserves the top index and restores focus by UID or the last focused item) { if (newFocusIndex != -1) lastFocus = newFocusIndex; @@ -931,7 +931,7 @@ void COperationDlg::RefreshItems(BOOL init, int refreshOnlyIndex1, int refreshOn focusIndex = ErrorsIndexes[0]; FocusedItemUID = Queue->GetItemUID(focusIndex); } - else // refresh the list view as gently as possible (preserves top index and focus by UID or the last focus) + else // refresh the list view with minimal disruption (preserves the top index and restores focus by UID or the last focused item) { int index = lastFocus >= 0 ? lastFocus : 0; if (ShowOnlyErrors) diff --git a/src/plugins/ftp/dialogs6.cpp b/src/plugins/ftp/dialogs6.cpp index e33648c34..dd84cf6a2 100644 --- a/src/plugins/ftp/dialogs6.cpp +++ b/src/plugins/ftp/dialogs6.cpp @@ -481,7 +481,7 @@ COperationDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) LastActivityTime = GetTickCount(); Config.OperDlgPlacement.length = sizeof(WINDOWPLACEMENT); // store the window position GetWindowPlacement(HWindow, &Config.OperDlgPlacement); - if (SimpleLook) // simple-look is unsuitable; store the size of the opened dialog + if (SimpleLook) // simple-look is not suitable; store the open dialog size Config.OperDlgPlacement.rcNormalPosition.bottom = Config.OperDlgPlacement.rcNormalPosition.top + LastDlgHeight1; else { @@ -579,7 +579,7 @@ COperationDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) DlgWillCloseIfOpFinWithSkips = (IsDlgButtonChecked(HWindow, IDC_OPCLOSEWINWHENDONE) == BST_CHECKED); CorrectLookOfPrevFocusedDisabledButton(focus); if (res != IDYES) - return TRUE; // no Cancel/Close will happen + return TRUE; // no Cancel/Close will occur break; } @@ -983,7 +983,7 @@ COperationDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) ToggleSimpleLook(); // the dialog must be shown in the detailed form if (workerIndex != -1) { - // focus the worker whose error we are going to solve + // focus the worker whose error we are going to handle BOOL oldEnableChangeFocusedCon = EnableChangeFocusedCon; EnableChangeFocusedCon = FALSE; ListView_SetItemState(ConsListView, workerIndex, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); @@ -1029,7 +1029,7 @@ COperationDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) else TRACE_E("Unexpected situation in COperationDlg::DialogProc::OPERDLG_AUTOSHOWERRTIMER!"); } - SetTimer(HWindow, OPERDLG_AUTOSHOWERRTIMER2, 100, 0); // to have an "immediate" reaction to the next error (PostMessage cannot be used here because another window beeps for some reason; I did not investigate why, WorkersList->PostNewWorkAvailable causes it) + SetTimer(HWindow, OPERDLG_AUTOSHOWERRTIMER2, 100, 0); // for an "immediate" response to the next error (PostMessage cannot be used here because another window beeps for some reason; the cause was not investigated, but WorkersList->PostNewWorkAvailable triggers it) SetTimer(HWindow, OPERDLG_AUTOSHOWERRTIMER, OPERDLG_AUTOSHOWERRPERIOD, NULL); // resume regular error checks } } @@ -1224,7 +1224,7 @@ COperationDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) // from the message loop of that modal dialog) SalamanderGeneral->CloseAllOwnedEnabledDialogs(HWindow); *SendWMClose = TRUE; // request WM_CLOSE again - return TRUE; // do not process further (closing was denied) + return TRUE; // do not process further (close was blocked) } DestroyWindow(HWindow); // destroy the window (the standard variant tries IDCANCEL, which we do not want) return TRUE; // do not process further diff --git a/src/plugins/ftp/dialogs7.cpp b/src/plugins/ftp/dialogs7.cpp index 9a72e33c3..c7d8bb6f5 100644 --- a/src/plugins/ftp/dialogs7.cpp +++ b/src/plugins/ftp/dialogs7.cpp @@ -134,10 +134,10 @@ void CSolveItemErrorDlg::Validate(CTransferInfo& ti) } } -// meaning of the button in connection with "do the same action for all operations with the same error": +// button meaning in connection with "do the same action for all operations with the same error": // buttons (order of values in one row of the array): // use-alternate-name, resume, resume or overwrite, overwrite, skip, use-existing-dir, ignore, in-binary-mode -// special value: -1 = does not make sense +// special value: -1 = not applicable int ButtonActionsTbl[][8] = { // row 0 = file exists: download+upload {FILEALREADYEXISTS_AUTORENAME, FILEALREADYEXISTS_RESUME, FILEALREADYEXISTS_RES_OVRWR, FILEALREADYEXISTS_OVERWRITE, FILEALREADYEXISTS_SKIP, -1, -1, -1}, @@ -316,7 +316,7 @@ void CSolveItemErrorDlg::Transfer(CTransferInfo& ti) case CM_SIED_OVERWRITE: value = ButtonActionsTbl[typeIndex][3]; break; - // case CM_SIED_OVERWRITEALL: // is changed to CM_SIED_OVERWRITE + *ApplyToAll==TRUE + // case CM_SIED_OVERWRITEALL: // changes to CM_SIED_OVERWRITE + *ApplyToAll==TRUE case IDB_SCRD_SKIP: value = ButtonActionsTbl[typeIndex][4]; break; @@ -1047,7 +1047,7 @@ COperDlgListView::~COperDlgListView() DestroyWindow(HToolTip); } -#define TTS_NOANIMATE 0x10 // it is not in the headers, so I define the constant here +#define TTS_NOANIMATE 0x10 // not in the headers, so define the constant here void COperDlgListView::Attach(HWND hListView, COperationDlg* operDlg, BOOL consOrItems) { @@ -1063,9 +1063,9 @@ void COperDlgListView::Attach(HWND hListView, COperationDlg* operDlg, BOOL consO if (dlgFont != NULL || SystemFont != NULL) SendMessage(HToolTip, WM_SETFONT, (WPARAM)(dlgFont != NULL ? dlgFont : SystemFont), TRUE); - // I commented out SetWindowPos(HWND_TOPMOST) because otherwise message boxes above the operation dialog do not work - // completely correctly - when Alt+TAB to the message box it does not activate automatically (it is not brought to the front) - // operation dialog + // SetWindowPos(HWND_TOPMOST) is commented out because otherwise message boxes above the operation dialog do not work + // completely correctly: when Alt+TAB switches to a message box, the operation dialog is not activated automatically + // (not brought to the front). // SetWindowPos(HToolTip, HWND_TOPMOST, 0, 0, 0, 0, // SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOREDRAW | SWP_NOSIZE); @@ -1235,9 +1235,9 @@ COperDlgListView::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) if (pt.x + width > monRect.right) pt.x = monRect.right - width; - // I commented out SetWindowPos(HWND_TOPMOST) because otherwise message boxes above the operation dialog do not work - // completely correctly - when Alt+TAB to the message box it does not activate automatically (it is not brought to the front) - // operation dialog + // SetWindowPos(HWND_TOPMOST) is commented out because otherwise message boxes above the operation dialog do not work + // completely correctly: when Alt+TAB switches to a message box, the operation dialog is not activated automatically + // (not brought to the front). /* SetWindowPos(HToolTip, HWND_TOPMOST, pt.x, @@ -1409,7 +1409,7 @@ void CSolveItemErrorSimpleDlg::Transfer(CTransferInfo& ti) int value = -1; switch (UsedButtonID) { - // case CM_SISE_RETRY: // it makes no sense for Retry + // case CM_SISE_RETRY: // does not make sense for Retry case IDOK: { diff --git a/src/plugins/ftp/dialogs8.cpp b/src/plugins/ftp/dialogs8.cpp index e07fe3ecd..8348fadcc 100644 --- a/src/plugins/ftp/dialogs8.cpp +++ b/src/plugins/ftp/dialogs8.cpp @@ -297,7 +297,7 @@ CServersListbox::WindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) break; } } - break; // let the keys pass through, the listbox should not handle them, no problem + break; // let the keys pass through; the listbox should not handle them } case WM_LBUTTONDBLCLK: @@ -977,7 +977,7 @@ CRenameDlg::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam) checkboxName[0] != 0 ? checkboxName : LoadStr(IDS_QUICKCONNECT)); SetDlgItemText(HWindow, IDC_COPYFOCUSEDSRV, buf); } - else // new server type + empty list = necessary to hide/disable the "copy from" checkbox + else // new server type + empty list = need to hide/disable the "copy from" checkbox { ShowWindow(GetDlgItem(HWindow, IDC_COPYFOCUSEDSRV), SW_HIDE); } @@ -1193,7 +1193,7 @@ void CConfigPageAdvanced::Validate(CTransferInfo& ti) int num; int arr[] = {IDE_SRVREPLIESTIMEOUT, IDE_DELAYBETWCONRETR, IDE_CONNECTRETRIES, IDE_NODATATRTIMEOUT, IDE_RESUMEMINFILESIZE, IDE_RESUMEOVERLAP, -1}; - BOOL gzthzero[] = {TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, -1}; // testing > 0 (TRUE) or >= 0 (FALSE) + BOOL gzthzero[] = {TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, -1}; // test > 0 (TRUE) or >= 0 (FALSE) int i; for (i = 0; arr[i] != -1; i++) { diff --git a/src/plugins/ftp/fs1.cpp b/src/plugins/ftp/fs1.cpp index d2dd78969..72eb1e49e 100644 --- a/src/plugins/ftp/fs1.cpp +++ b/src/plugins/ftp/fs1.cpp @@ -4,7 +4,7 @@ #include "precomp.h" -// FS-name assigned by Salamander after loading the plug-in +// FS-name assigned by Salamander after loading the plugin char AssignedFSName[MAX_PATH] = ""; int AssignedFSNameLen = 0; @@ -305,7 +305,7 @@ void CPluginInterfaceForFS::CloseFS(CPluginFSInterfaceAbstract* fs) break; } } - if (!found) // "i == FTPConnections.Count" is not enough (there is Delete(i)) + if (!found) // "i == FTPConnections.Count" is not enough because Delete(i) is called TRACE_E("Unexpected situation in CPluginInterfaceForFS::CloseFS(): FS not found in FTPConnections."); delete ((CPluginFSInterface*)fs); // to call the correct destructor @@ -691,7 +691,7 @@ void CPluginInterfaceForFS::ExecuteOnFS(int panel, CPluginFSInterfaceAbstract* p fs->MakeUserPart(newUserPart, FTP_USERPART_SIZE, newPath); if (SalamanderGeneral->ChangePanelPathToPluginFS(panel, pluginFSName, newUserPart)) { - fs->TopIndexMem.Push(type, backupPath, topIndex); // remember the top-index for the return + fs->TopIndexMem.Push(type, backupPath, topIndex); // remember the top index for returning } } } @@ -756,7 +756,7 @@ void CTopIndexMem::Push(CFTPServerPathType type, const char* path, int topIndex) ok = FTPIsTheSameServerPath(type, testPath, Path); } - if (ok) // it follows -> remember the next top-index + if (ok) // continues from the current path -> remember the next top-index { if (TopIndexesCount == TOP_INDEX_MEM_SIZE) // we need to discard the first top-index from memory { @@ -788,13 +788,13 @@ BOOL CTopIndexMem::FindAndPop(CFTPServerPathType type, const char* path, int& to topIndex = TopIndexes[--TopIndexesCount]; return TRUE; } - else // we no longer have this value (it was not stored or low memory removed it) + else // we no longer have this value (it was not stored, or it was discarded due to low memory) { Clear(); return FALSE; } } - else // query for another path -> clear the memory, a long jump occurred + else // query for a different path -> clear memory, a long jump occurred { Clear(); return FALSE; diff --git a/src/plugins/ftp/fs2.cpp b/src/plugins/ftp/fs2.cpp index 0a95bd6a5..d5f93b707 100644 --- a/src/plugins/ftp/fs2.cpp +++ b/src/plugins/ftp/fs2.cpp @@ -7,7 +7,7 @@ int CSimpleListPluginDataInterface::ListingColumnWidth = 0; // LO/HI-WORD: left/right panel: width of the Raw Listing column int CSimpleListPluginDataInterface::ListingColumnFixedWidth = 0; // LO/HI-WORD: left/right panel: does the Raw Listing column have a fixed width? -// Global variables where I store pointers to Salamander's global variables +// Global variables that store pointers to Salamander's global variables const CFileData** TransferFileData = NULL; int* TransferIsDir = NULL; char* TransferBuffer = NULL; @@ -385,7 +385,7 @@ BOOL CPluginFSInterface::ChangePath(int currentFSNameIndex, char* fsName, int fs if (lastErrorState == fesFatal) { TargetPanelPath[0] = 0; // the connection failed, no path change in the target panel - return FALSE; // fatal error, stop + return FALSE; // fatal error, abort } // Treat a hard refresh as distrust of the path; drop from the disk cache all files @@ -411,7 +411,7 @@ BOOL CPluginFSInterface::ChangePath(int currentFSNameIndex, char* fsName, int fs TotalConnectAttemptNum = 1; // opening the connection = first attempt to open it InformAboutUnknownSrvType = TRUE; - BOOL parsedPath = TRUE; // TRUE = path obtained from the user part; need to decide whether to trim '/' or '\\' at the start + BOOL parsedPath = TRUE; // TRUE = path obtained from the user-part; need to determine whether to trim a leading '/' or '\\' ControlConnection = new CControlConnectionSocket; if (ControlConnection == NULL || !ControlConnection->IsGood()) { @@ -1168,7 +1168,7 @@ BOOL CPluginFSInterface::ListCurrentPath(CSalamanderDirectoryAbstract* dir, { serverType->CompiledAutodetCond = CompileAutodetectCond(HandleNULLStr(serverType->AutodetectCond), NULL, NULL, NULL, NULL, 0); - if (serverType->CompiledAutodetCond == NULL) // can only fail due to lack of memory + if (serverType->CompiledAutodetCond == NULL) // this can only be a low-memory error { err = TRUE; break; @@ -1205,8 +1205,8 @@ BOOL CPluginFSInterface::ListCurrentPath(CSalamanderDirectoryAbstract* dir, serverType = serverTypeList->At(i); if (!serverType->ParserAlreadyTested) // only if we have not tried it yet { - // serverType is selected, try its parser on the listing - // serverType->ParserAlreadyTested = TRUE; // unnecessary, not used afterwards + // serverType has been selected; try its parser on the listing + // serverType->ParserAlreadyTested = TRUE; // unnecessary, not used later if (ParseListing(dir, &pluginData, serverType, &err, isVMS, NULL, FALSE, NULL, NULL) || err) { if (!err) @@ -1260,7 +1260,7 @@ BOOL CPluginFSInterface::ListCurrentPath(CSalamanderDirectoryAbstract* dir, pluginData = &SimpleListPluginDataInterface; // ATTENTION: the change may also affect obtaining the data interface in CPluginFSInterface::ChangeAttributes! dir->SetValidData(VALID_DATA_NONE); dir->SetFlags(SALDIRFLAG_CASESENSITIVE | SALDIRFLAG_IGNOREDUPDIRS); // probably unnecessary, but everything is treated as case-sensitive so this should be safe - if (!PathListingIsBroken && // if the listing is not OK, rather use an empty listing + if (!PathListingIsBroken && // if the listing is not OK, use an empty listing instead PathListingLen > 0) { char* beg = PathListing; diff --git a/src/plugins/ftp/fs3.cpp b/src/plugins/ftp/fs3.cpp index b3c58b596..2b7fa14b0 100644 --- a/src/plugins/ftp/fs3.cpp +++ b/src/plugins/ftp/fs3.cpp @@ -23,7 +23,7 @@ BOOL CPluginFSInterface::TryCloseOrDetach(BOOL forceClose, BOOL canDetach, BOOL& { if (reason == FSTRYCLOSE_CHANGEPATH) { - if (canDetach && !Config.DisconnectCommandUsed) // "close or detach" and it is not the "Disconnect" command + if (canDetach && !Config.DisconnectCommandUsed) // "close or detach", not the "Disconnect" command { int res; if (!Config.AlwaysNotCloseCon) @@ -88,7 +88,7 @@ MENU_TEMPLATE_ITEM MsgBoxButtons[] = { close = ret = TRUE; // this prompt proved to be very confusing and incomprehensible, so we simply prefer Disconnect /* - // "no path on the FTP is accessible, disconnect?" + // "no path on the FTP server is accessible, disconnect?" close = ret = (SalamanderGeneral->SalMessageBox(SalamanderGeneral->GetMsgBoxParent(), LoadStr(IDS_NOPATHACCESSINPANEL), LoadStr(IDS_FTPPLUGINTITLE), @@ -168,12 +168,12 @@ void CPluginFSInterface::Event(int event, DWORD param) case FSE_TIMER: // delayed panel refresh (to give the connection time to return from the operation dialog to the panel) { - DWORD paramLimit = 4; // maximum one second waiting for the connection (we wait to see whether the worker will try to hand over the connection) + DWORD paramLimit = 4; // wait up to one second for the connection (we wait to see whether the worker will try to hand over the connection) DWORD ti; if (ControlConnection != NULL && ControlConnection->GetIsSocketConnectedLastCallTime(&ti) && GetTickCount() - ti < 5000) { - paramLimit = 24; // maximum five seconds waiting for the connection (we know the worker is trying to hand it over) + paramLimit = 24; // wait up to five seconds for the connection (we know the worker is trying to hand it over) } if (param >= paramLimit || // param < paramLimit: start the refresh only if we have the connection, param >= paramLimit always allows the refresh ControlConnection != NULL && ControlConnection->IsConnected()) @@ -222,8 +222,8 @@ void CPluginFSInterface::ReleaseObject(HWND parent) } else { - // if we have not yet written what led to closing the connection, do it now - // at least into the log (there is no point in showing a window, the user is probably no longer interested) + // if we have not yet logged what caused the connection to close, do it now + // at least to the log (there is no point in showing a window; the user is probably no longer interested) ControlConnection->CheckCtrlConClose(TRUE, FALSE, parent, TRUE); } @@ -319,7 +319,7 @@ BOOL CPluginFSInterface::GetNextDirectoryLineHotPath(const char* text, int pathL if (*root == '/' || *root == '\\') root++; // skip '/' or '\\' from the disk root path } - if (DirLineHotPathType == ftpsptTandem) // for Tandem paths skip the "system" ("\\SYSTEM"), a shorter path makes no sense + if (DirLineHotPathType == ftpsptTandem) // for Tandem paths, skip "system" ("\\SYSTEM"); a shorter path makes no sense while (root < end && *root != '.') root++; } @@ -777,7 +777,7 @@ void CPluginFSInterface::SendUserFTPCommand(HWND parent) BOOL ok = TRUE; char newPath[FTP_MAX_PATH]; BOOL needChangeDir = reconnected; // after reconnect try to set the working directory again - if (!reconnected) // already connected for a longer time, verify that the working directory matches 'Path' + if (!reconnected) // already connected for some time, verify that the working directory matches 'Path' { // use the cache, under normal circumstances the path should be there ok = ControlConnection->GetCurrentWorkingPath(parent, newPath, FTP_MAX_PATH, FALSE, @@ -787,7 +787,7 @@ void CPluginFSInterface::SendUserFTPCommand(HWND parent) run = TRUE; retryMsgAux = retryMsgBuf; } - if (ok && strcmp(newPath, Path) != 0) // working directory on the server differs - change required + if (ok && strcmp(newPath, Path) != 0) // the working directory on the server differs - change required needChangeDir = TRUE; // (assumption: the server returns the same working path string) } if (ok && needChangeDir) // working directory needs to be changed @@ -795,14 +795,14 @@ void CPluginFSInterface::SendUserFTPCommand(HWND parent) int panel; BOOL notInPanel = !SalamanderGeneral->GetPanelWithPluginFS(this, panel); BOOL success; - // SendChangeWorkingPath() calls ReconnectIfNeeded() on connection failure, luckily that + // SendChangeWorkingPath() calls ReconnectIfNeeded() on connection failure; this // does not matter because the code preceding this call runs only when reconnect did not // occur - "if (!reconnected)" - if reconnect happens, both code paths are the same ok = ControlConnection->SendChangeWorkingPath(notInPanel, panel == PANEL_LEFT, parent, Path, User, USER_MAX_SIZE, &success, ftpReplyBuf, 700, NULL, &TotalConnectAttemptNum, NULL, TRUE, NULL); - if (ok && !success && Path[0] != 0) // send succeeded, but the server reports an error (+ignore the error for an empty path) -> user command cannot + if (ok && !success && Path[0] != 0) // send succeeded, but the server reports an error (+ignore the error for an empty path) -> the user command cannot be sent { // be sent (it may be tied to the current path in the panel) char errBuf[900 + FTP_MAX_PATH]; _snprintf_s(errBuf, _TRUNCATE, LoadStr(IDS_CHANGEWORKPATHERROR), Path, ftpReplyBuf); @@ -844,7 +844,7 @@ void CPluginFSInterface::SendUserFTPCommand(HWND parent) } } - if (ok) // everything went well, report the command result to the user + if (ok) // command succeeded, report the command result to the user { char* s = logBuf + strlen(logBuf); while (s > logBuf && (*(s - 1) == '\n' || *(s - 1) == '\r')) @@ -856,7 +856,7 @@ void CPluginFSInterface::SendUserFTPCommand(HWND parent) } else { - if (dlg.RefreshWorkingPath) // the Path may have changed, invalidate the Path listing cache + if (dlg.RefreshWorkingPath) // Path may have changed, invalidate the listing for Path in the cache UploadListingCache.ReportUnknownChange(User, Host, Port, Path, GetFTPServerPathType(Path)); if (canRetry) // "retry" is allowed @@ -927,7 +927,7 @@ void CPluginFSInterface::ContextMenu(const char* fsName, HWND parent, int menuX, int type2, lastType = sctyUnknown; while (SalamanderGeneral->EnumSalamanderCommands(&index, &salCmd, nameBuf, 200, &enabled, &type2)) { - if (!enabled || salCmd == SALCMD_OPEN || // we cannot "open" files yet, so do not add it (we can do it only for directories and there it is uninteresting) + if (!enabled || salCmd == SALCMD_OPEN || // we cannot "open" files yet, so do not add it (we only support it for directories, where it is not useful) type2 == sctyForFocusedFile && isfocusedDir || (type2 != sctyForFocusedFile && type2 != sctyForFocusedFileOrDirectory && type2 != sctyForSelectedFilesAndDirectories)) @@ -1344,7 +1344,7 @@ CFTPListingPluginDataInterface::CFTPListingPluginDataInterface(TIndirectArrayRelease(); oper->SetCompressData(ControlConnection->GetCompressData()); - if (ControlConnection->InitOperation(oper)) // initialize the server connection according to the "control connection" + if (ControlConnection->InitOperation(oper)) // initialize the server connection using the "control connection" { oper->SetBasicData(dlgSubjectSrc, (AutodetectSrvType ? NULL : LastServerType)); char path[2 * MAX_PATH]; @@ -713,7 +713,7 @@ BOOL CPluginFSInterface::Delete(const char* fsName, int mode, HWND parent, int p { if (dataIface != NULL && (void*)dataIface == (void*)&SimpleListPluginDataInterface) dataIface = NULL; // we care only about a data interface of type CFTPListingPluginDataInterface - int rightsCol = -1; // column index with permissions (used to detect links) + int rightsCol = -1; // permissions column index (used to detect links) if (dataIface != NULL) rightsCol = dataIface->FindRightsColumn(); const CFileData* f = NULL; // pointer to the file/directory/link in the panel to process @@ -791,7 +791,7 @@ BOOL CPluginFSInterface::Delete(const char* fsName, int mode, HWND parent, int p } if (!ok) FTPOperationsList.DeleteOperation(operUID, TRUE); - oper = NULL; // the operation is already added to the array, do not release it via 'delete' (see below) + oper = NULL; // the operation has already been added to the array, so do not release it via 'delete' (see below) } } if (oper != NULL) @@ -928,7 +928,7 @@ BOOL CPluginFSInterface::CopyOrMoveFromFS(BOOL copy, int mode, const char* fsNam char subject[MAX_PATH + 200]; sprintf(subject, LoadStr(copy ? IDS_COPYFROMFTP : IDS_MOVEFROMFTP), subjectSrc); - if (mode == 1 && targetPath[0] != 0) // only when opening the dialog for the first time and the target path is selected + if (mode == 1 && targetPath[0] != 0) // only when opening the dialog for the first time and a target path is selected { SalamanderGeneral->SalPathAppend(targetPath, "*.*", 2 * MAX_PATH); SalamanderGeneral->SetUserWorkedOnPanelPath(PANEL_TARGET); // default action = work with the path in the target panel @@ -1035,7 +1035,7 @@ BOOL CPluginFSInterface::CopyOrMoveFromFS(BOOL copy, int mode, const char* fsNam if (cert) cert->Release(); oper->SetCompressData(ControlConnection->GetCompressData()); - if (ControlConnection->InitOperation(oper)) // initialize the server connection according to the "control connection" + if (ControlConnection->InitOperation(oper)) // initialize the connection to the server based on the "control connection" { oper->SetBasicData(dlgSubjectSrc, (AutodetectSrvType ? NULL : LastServerType)); char path[2 * MAX_PATH]; @@ -1069,8 +1069,8 @@ BOOL CPluginFSInterface::CopyOrMoveFromFS(BOOL copy, int mode, const char* fsNam if (queue != NULL) { if (dataIface != NULL && (void*)dataIface == (void*)&SimpleListPluginDataInterface) - dataIface = NULL; // we care only about a data interface of type CFTPListingPluginDataInterface - int rightsCol = -1; // column index with permissions (used to detect links) + dataIface = NULL; // we are only interested in a data interface of type CFTPListingPluginDataInterface + int rightsCol = -1; // index of the permissions column (used to detect links) if (dataIface != NULL) rightsCol = dataIface->FindRightsColumn(); CQuadWord totalSize(0, 0); // total size (in bytes or blocks) @@ -1097,7 +1097,7 @@ BOOL CPluginFSInterface::CopyOrMoveFromFS(BOOL copy, int mode, const char* fsNam if (!is_AS_400_QSYS_LIB_Path) { if (donotUseOpMask) - lstrcpyn(targetName, f->Name, 2 * MAX_PATH); // masks trim '.' from name ends, which is not always OK (e.g. directories "a.b" and "a.b." would merge) - probably rare, so for now we solve it only provisionally like this + lstrcpyn(targetName, f->Name, 2 * MAX_PATH); // masks trim trailing '.' characters from names, which is not always OK (e.g. directories "a.b" and "a.b." would merge) - this is probably rare, so for now we handle it only provisionally like this else SalamanderGeneral->MaskName(targetName, 2 * MAX_PATH, f->Name, opMask); } @@ -1106,7 +1106,7 @@ BOOL CPluginFSInterface::CopyOrMoveFromFS(BOOL copy, int mode, const char* fsNam char mbrName[MAX_PATH]; FTPAS400CutFileNamePart(mbrName, f->Name); if (donotUseOpMask) - lstrcpyn(targetName, mbrName, 2 * MAX_PATH); // masks trim '.' from name ends, which is not always OK (e.g. directories "a.b" and "a.b." would merge) - probably rare, so for now we solve it only provisionally like this + lstrcpyn(targetName, mbrName, 2 * MAX_PATH); // masks trim '.' from the ends of names, which is not always OK (e.g. directories "a.b" and "a.b." would merge) - this is probably rare, so for now we handle it provisionally like this else SalamanderGeneral->MaskName(targetName, 2 * MAX_PATH, mbrName, opMask); } @@ -1211,7 +1211,7 @@ CFTPQueueItem* CreateItemForChangeAttrsOperation(const CFileData* f, BOOL isDir, char* rights = NULL; if (rightsCol != -1 && IsUNIXLink((rights = dataIface->GetStringFromColumn(*f, rightsCol)))) { // link - if (includeSubdirs) // try whether it is a link to a directory (otherwise there is nothing to do) + if (includeSubdirs) // try to determine whether this is a link to a directory (otherwise there is nothing to do) { *type = fqitChAttrsResolveLink; item = new CFTPQueueItem; diff --git a/src/plugins/ftp/fs5.cpp b/src/plugins/ftp/fs5.cpp index 064cbd35c..b469f253f 100644 --- a/src/plugins/ftp/fs5.cpp +++ b/src/plugins/ftp/fs5.cpp @@ -47,7 +47,7 @@ BOOL CPluginFSInterface::ChangeAttributes(const char* fsName, HWND parent, int p { // we only care about data iface objects of type CFTPListingPluginDataInterface CFTPListingPluginDataInterface* dataIface = (CFTPListingPluginDataInterface*)pluginDataIface; int rightsCol = dataIface->FindRightsColumn(); - if (rightsCol != -1) // if the Rights column exists (it does not have to be Unix, that is handled later) + if (rightsCol != -1) // if the Rights column exists (it does not have to be a Unix column; that is handled later) { displayWarning = FALSE; const CFileData* f = NULL; // pointer to the file/directory in the panel that should be processed @@ -93,7 +93,7 @@ BOOL CPluginFSInterface::ChangeAttributes(const char* fsName, HWND parent, int p } } - if (!displayWarning || // optionally display a warning that this is not a UNIX server with the traditional rights model (e.g. we do not support ACL) + if (!displayWarning || // optionally display a warning that this is not a UNIX server with the traditional permissions model (e.g. ACLs are not supported) SalamanderGeneral->SalMessageBox(parent, LoadStr(IDS_CHATTRNOTUNIXSRV), LoadStr(IDS_FTPPLUGINTITLE), MB_YESNO | MSGBOXEX_ESCAPEENABLED | @@ -105,7 +105,7 @@ BOOL CPluginFSInterface::ChangeAttributes(const char* fsName, HWND parent, int p CChangeAttrsDlg dlg(parent, subject, attr, attrDiff, selDirs); if (dlg.Execute() == IDOK) { - BOOL failed = TRUE; // pre-initialize the operation error + BOOL failed = TRUE; // initialize the operation as failed // create the operation object CFTPOperation* oper = new CFTPOperation; if (oper != NULL) @@ -141,7 +141,7 @@ BOOL CPluginFSInterface::ChangeAttributes(const char* fsName, HWND parent, int p CFTPListingPluginDataInterface* dataIface = (CFTPListingPluginDataInterface*)pluginDataIface; if (dataIface != NULL && (void*)dataIface == (void*)&SimpleListPluginDataInterface) dataIface = NULL; // we only care about data iface objects of type CFTPListingPluginDataInterface - int rightsCol = -1; // index of the column with rights (used to detect links) + int rightsCol = -1; // index of the permissions column (used to detect links) if (dataIface != NULL) rightsCol = dataIface->FindRightsColumn(); const CFileData* f = NULL; // pointer to the file/directory/link in the panel that should be processed @@ -238,7 +238,7 @@ BOOL CPluginFSInterface::ChangeAttributes(const char* fsName, HWND parent, int p } if (!ok) FTPOperationsList.DeleteOperation(operUID, TRUE); - oper = NULL; // the operation is already added in the array, do not free it with 'delete' (see below) + oper = NULL; // the operation is already added to the array, do not free it with 'delete' (see below) } } if (oper != NULL) @@ -246,7 +246,7 @@ BOOL CPluginFSInterface::ChangeAttributes(const char* fsName, HWND parent, int p } else TRACE_E(LOW_MEMORY); - return !failed; // return the operation success (TRUE = clear the selection in the panel) + return !failed; // return whether the operation succeeded (TRUE = clear the selection in the panel) } } return FALSE; // cancellation @@ -258,7 +258,7 @@ BOOL CPluginFSInterface::RunOperation(HWND parent, int operUID, CFTPOperation* o BOOL ok = TRUE; - CFTPWorker* workerWithCon = NULL; // if we passed the connection, this points to who received it + CFTPWorker* workerWithCon = NULL; // if we passed the connection, this points to the recipient int i; for (i = 0; i < 1; i++) // FIXME: eventually we may place the initial number of operation workers into the configuration: just replace "1" with the appropriate count... { @@ -456,14 +456,14 @@ void CPluginFSInterface::ViewFile(const char* fsName, HWND parent, // open the viewer HANDLE fileLock; BOOL fileLockOwner; - if (!fileExists && !newFileCreated || // open the viewer only if the copy of the file is fine + if (!fileExists && !newFileCreated || // open the viewer only if the file copy is valid !salamander->OpenViewer(parent, tmpFileName, &fileLock, &fileLockOwner)) { // on error reset the "lock" fileLock = NULL; fileLockOwner = FALSE; } - // we still have to call FreeFileNameInCache as a pair to AllocFileNameInCache (link + // we still have to call FreeFileNameInCache to match AllocFileNameInCache (link // the viewer and the disk cache) salamander->FreeFileNameInCache(uniqueFileName, fileExists, newFileCreated, newFileSize, fileLock, fileLockOwner, @@ -714,7 +714,7 @@ BOOL CPluginFSInterface::CopyOrMoveFromDiskToFS(BOOL copy, int mode, const char* if (mode == 2 || mode == 3) { // 'targetPath' contains the raw path entered by the user (the only thing we know about it - // is that it points to the FTP, otherwise Salamander would not call this method) + // is that it is on FTP, otherwise Salamander would not call this method) int isFTPS = SalamanderGeneral->StrNICmp(targetPath, AssignedFSNameFTPS, AssignedFSNameLenFTPS) == 0 && targetPath[AssignedFSNameLenFTPS] == ':'; @@ -744,7 +744,7 @@ BOOL CPluginFSInterface::CopyOrMoveFromDiskToFS(BOOL copy, int mode, const char* if (p != NULL && *p != 0) port = atoi(p); - if (ControlConnection == NULL) // open the connection (open the path on the FTP server) + if (ControlConnection == NULL) // opening the connection (opening the path on the FTP server) { TotalConnectAttemptNum = 1; // opening the connection = first attempt to open the connection @@ -886,7 +886,7 @@ BOOL CPluginFSInterface::CopyOrMoveFromDiskToFS(BOOL copy, int mode, const char* } // if this is a root (only specific cases, other types of root paths continue further), no more adjustments - // nor path analysis make sense - use the path as is plus the "*" mask + // or path analysis makes sense - use the path as is plus the "*" mask if (!isSpecRootPath) { // if the path ends with a separator, treat it as a path without a mask (e.g. "/pub/dir/" or @@ -1034,7 +1034,7 @@ BOOL CPluginFSInterface::CopyOrMoveFromDiskToFS(BOOL copy, int mode, const char* // the path is analyzed, start the operation: // 'tgtPath' is the target path, 'mask' is the operation mask - BOOL success = FALSE; // pre-initialize cancel/error state of the operation + BOOL success = FALSE; // preset the cancel/error state of the operation char dlgSubjectSrc[MAX_PATH + 100]; if (sourceFiles + sourceDirs <= 1) // one selected item @@ -1070,7 +1070,7 @@ BOOL CPluginFSInterface::CopyOrMoveFromDiskToFS(BOOL copy, int mode, const char* if (cert) cert->Release(); oper->SetCompressData(ControlConnection->GetCompressData()); - if (ControlConnection->InitOperation(oper)) // initialize the connection to the server according to the "control connection" + if (ControlConnection->InitOperation(oper)) // initialize the connection to the server based on the "control connection" { oper->SetBasicData(dlgSubjectSrc, (AutodetectSrvType ? NULL : LastServerType)); char targetPath2[2 * MAX_PATH]; @@ -1207,7 +1207,7 @@ BOOL CPluginFSInterface::CopyOrMoveFromDiskToFS(BOOL copy, int mode, const char* oper->SetQueue(queue); // set the queue of its items for the operation queue = NULL; - // FIXME: there is probably no place for an "only add to queue" checkbox: if (Config.UploadAddToQueue) success = TRUE; // perform the operation later -> for now the operation is successful + // FIXME: there is probably nowhere to put an "only add to queue" checkbox: if (Config.UploadAddToQueue) success = TRUE; // perform the operation later -> for now, this counts as a successful operation // else // perform the operation in the active "control connection" // { // open the operation progress window and start the operation @@ -1219,7 +1219,7 @@ BOOL CPluginFSInterface::CopyOrMoveFromDiskToFS(BOOL copy, int mode, const char* } if (!ok) FTPOperationsList.DeleteOperation(operUID, TRUE); - oper = NULL; // the operation is already added in the array, do not free it with 'delete' (see below) + oper = NULL; // the operation is already added to the array, do not free it with 'delete' (see below) } } } @@ -1248,7 +1248,7 @@ void CPluginFSInterface::ShowSecurityInfo(HWND hParent) char errBuf[300]; int panel; if (SalamanderGeneral->GetPanelWithPluginFS(this, panel)) - { // the user might have imported the certificate or deleted it from the MS store, verify the state and show it in the panel + { // the user might have imported the certificate or deleted it from the MS store; recheck its status and show it in the panel bool verified = cert->CheckCertificate(errBuf, 300); cert->SetVerified(verified); SalamanderGeneral->ShowSecurityIcon(panel, TRUE, verified, diff --git a/src/plugins/ftp/ftp.cpp b/src/plugins/ftp/ftp.cpp index dee08be27..02ab50456 100644 --- a/src/plugins/ftp/ftp.cpp +++ b/src/plugins/ftp/ftp.cpp @@ -10,45 +10,45 @@ CPluginInterface PluginInterface; CPluginInterfaceForFS InterfaceForFS; CPluginInterfaceForMenuExt InterfaceForMenuExt; -// ConfigVersion: 0 - default (without load), -// 1 - work version before listing parsing support (from this version on there are sensible lists of server-types and ftp-servers) -// 2 - work version before the first MVS adjustments according to tester Michael Knigge (server-type list adjustment) -// 3 - work version before the second MVS adjustments according to tester Michael Knigge (server-type list adjustment) -// 4 - work version before the third MVS adjustments according to tester Michael Knigge (server-type list adjustment) -// 5 - work version before the first VMS adjustments (server-type list adjustment) -// 6 - work version before the fourth MVS adjustments according to tester Michael Knigge (server-type list adjustment) -// 7 - work version before modifying values in the configuration on the Operations page -// 8 - work version before Servant Salamander 2.1 beta 1 -// 9 - Servant Salamander 2.5 beta 6 (+adjustments to server-type autodetect conditions) -// 10 - added parser for Unix systems with two spaces before the file/directory name in the listing (Filezilla + AIX) -// 11 - fixed parser for Unix systems with two spaces before the file/directory name in the listing (Filezilla + AIX) -// 12 - priority change: the parser for Unix systems with two spaces after the year before names comes before the parser with one space after the year before names (the variant without spaces at the beginning of names is more likely) + enriched MVS1 and MVS2 parsers -// 13 - fixed column descriptions in the MVS PO parser (all four): used "Number of Records" instead of "Size" -// 14 - fixed the MVS PO 4 parser: the value can be missing both in column "AC" and in column "Alias" - now reading them directly by offsets + trimming trailing spaces, there is no other way + fixed the MVS1 and MVS2 parsers (volume OK + followed by "Error determining attributes") -// + fixed the column names in the MVS PO parser (all four): used "Records" instead of "Size" - the size is not in bytes, nonsensical progress was shown during download -// 15 - added parser for OS/2 FTP server -// 16 - added parser for VxWorks FTP server +// ConfigVersion: 0 - default (not loaded), +// 1 - working version before listing parsing support (from this version on, sensible server-type and ftp-server lists already exist) +// 2 - working version before the first MVS changes based on tester Michael Knigge's feedback (server-type list update) +// 3 - working version before the second MVS changes based on tester Michael Knigge's feedback (server-type list update) +// 4 - working version before the third MVS changes based on tester Michael Knigge's feedback (server-type list update) +// 5 - working version before the first VMS changes (server-type list update) +// 6 - working version before the fourth MVS changes based on tester Michael Knigge's feedback (server-type list update) +// 7 - working version before changing values in the configuration on the Operations page +// 8 - working version before Servant Salamander 2.1 beta 1 +// 9 - Servant Salamander 2.5 beta 6 (+ changes to server-type autodetection conditions) +// 10 - added a parser for Unix systems with two spaces before the file/directory name in the listing (FileZilla + AIX) +// 11 - fixed the parser for Unix systems with two spaces before the file/directory name in the listing (FileZilla + AIX) +// 12 - priority change: the parser for Unix systems with two spaces after the year before names now takes precedence over the parser with one space after the year before names (the variant without leading spaces in names is more likely) + enhanced MVS1 and MVS2 parsers +// 13 - fixed column descriptions in the MVS PO parser (all four): "Number of Records" is now used instead of "Size" +// 14 - fixed the MVS PO 4 parser: a value may be missing in both the "AC" and "Alias" columns - they are now read strictly by offsets + trailing spaces are trimmed, otherwise it simply does not work + fixed the MVS1 and MVS2 parsers (volume OK + followed by "Error determining attributes") +// + fixed column names in the MVS PO parser (all four): "Records" is now used instead of "Size" - the size is not in bytes, so download progress was nonsensical +// 15 - added a parser for the OS/2 FTP server +// 16 - added a parser for the VxWorks FTP server // 17 - fixed the MVS parser (another type of error message in the listing + another combination of skipped data in the listing) + fixed the VxWorks parser -// 18 - added alignment to parser columns - we usually align dates+times+numbers to the right +// 18 - added alignment to parser columns - dates, times, and numbers are usually right-aligned // 19 - adjusted the z/VM parser: Date is of type GeneralDate so that item ".." shows an empty string instead of "1.1.1602" // 20 - added the "is_link" identifier (TRUE = the panel icon has a link overlay) -// 21 - added the UNIX4 parser (German dates - months longer than 3 letters), added functions "month_txt" -// 22 - modified values in the configuration on the Operations 2 (Upload) page -// 23 - adjusted parser autodetection conditions that skip the first or last rows of the listing (if Microsoft IIS or Netprezenz returned a listing with one or two rows, the VMS parser simply ignored it and an empty listing was used) -// 24 - adjusted skipping listing headers in parsers, now an invalid row is not skipped when a header is missing -// 25 - adjusted the Microsoft IIS parser: directories containing spaces instead of names are ignored (I do not understand why they are even shown when they have no name, but they are) -// 26 - added UNIX5 (IBM AIX - German version) parser (the month and day columns are swapped) -// 27 - adjusted the VMS1-4 parsers, novelty on cs.felk.cvut.cz: an empty directory returns a listing containing "Total of 0 files, 0/0 blocks" (the listing previously returned the error "no files found") -// 28 - added parser for Tandem -// 29 - default change: "Resume or Overwrite" instead of "Overwrite" for Config.UploadRetryOnCreatedFile; Config.DisableLoggingOfWorkers changed to FALSE (I am tired of writing to everyone to enable logging, the logging overhead is minimal) -// 30 - added parser for IBM AS/400 -// 31 - adjusted parser for IBM AS/400 -// 32 - renamed parser for IBM AS/400 to "IBM iSeries/i5, AS/400" -// 33 - adjusted parser for IBM AS/400: names must not contain spaces (otherwise it nonsensically parses, for example, unparsable Unix listings) -// 34 - adjusted all five UNIX parsers: user+group can contain more spaces (in that case they are ignored because we do not know how to separate user from group) -// 35 - added UNIX parser for MOXA FTP server (missing times + dates); change in all UNIX parsers: reading the column is no longer done by fixed 10 characters but by a word (reason: ACL on Unix introduced '+' after those ten characters, e.g. "drwxrwxr-x+") +// 21 - added the UNIX4 parser (German dates - month names longer than 3 letters), added the "month_txt" functions +// 22 - changed values in the configuration on the Operations 2 (Upload) page +// 23 - adjusted parser autodetection conditions that skip the first or last rows of the listing (if Microsoft IIS or NetPresenz returned a listing with one or two rows, the VMS parser simply ignored it and an empty listing was used) +// 24 - adjusted skipping of listing headers in parsers; an invalid row is no longer skipped when a header is missing +// 25 - adjusted the Microsoft IIS parser: directories with spaces instead of names are ignored +// 26 - added the UNIX5 (IBM AIX - German version) parser (the month and day columns are swapped) +// 27 - adjusted the VMS1-4 parsers; new behavior on cs.felk.cvut.cz: an empty directory returns a listing containing "Total of 0 files, 0/0 blocks" (previously the listing returned the error "no files found") +// 28 - added a parser for Tandem +// 29 - default change: "Resume or Overwrite" instead of "Overwrite" for Config.UploadRetryOnCreatedFile; Config.DisableLoggingOfWorkers changed to FALSE (logging overhead is minimal) +// 30 - added a parser for IBM AS/400 +// 31 - adjusted the parser for IBM AS/400 +// 32 - renamed the parser for IBM AS/400 to "IBM iSeries/i5, AS/400" +// 33 - adjusted the parser for IBM AS/400: names must not contain spaces (otherwise it produces nonsensical parsing, for example for Unix listings that cannot be parsed) +// 34 - adjusted all five UNIX parsers: user+group may contain multiple spaces (in that case they are ignored because user and group cannot be separated) +// 35 - added a UNIX parser for the MOXA FTP server (missing times + dates); change in all UNIX parsers: the column is no longer read as a fixed 10 characters, but as a word (reason: ACLs on Unix introduced '+' after those ten characters, e.g. "drwxrwxr-x+") // 36 - change in the CZ+EN parser for IBM AS/400: ignore the first row with an empty file name -// 37 - added parser for Xbox 360 +// 37 - added a parser for Xbox 360 int ConfigVersion = 0; #define CURRENT_CONFIG_VERSION 37 @@ -200,7 +200,7 @@ int InactiveBeepWhenDone = TRUE; // current value of the Salamander configurati HINSTANCE DLLInstance = NULL; // handle to SPL - language-independent resources HINSTANCE HLanguage = NULL; // handle to SLG - language-dependent resources -// general interface of Salamander - valid from startup until the plug-in is closed +// general interface of Salamander - valid from startup until the plugin is closed CSalamanderGeneralAbstract* SalamanderGeneral = NULL; // ZLIB compression/decompression interface; @@ -244,7 +244,7 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) if (!InitCommonControlsEx(&initCtrls)) { MessageBox(NULL, "InitCommonControlsEx failed!", "Error", MB_OK | MB_ICONERROR); - return FALSE; // DLL won't start + return FALSE; // DLL cannot be loaded } WindowsVistaAndLater = SalIsWindowsVersionOrGreater(6, 0, 0); @@ -287,16 +287,16 @@ CPluginInterfaceAbstract* WINAPI SalamanderPluginEntry(CSalamanderPluginEntryAbs HANDLES_CAN_USE_TRACE(); CALL_STACK_MESSAGE1("SalamanderPluginEntry()"); - // this plug-in is made for the current version of Salamander and higher - perform a check + // this plugin is made for the current version of Salamander and higher - perform a check if (SalamanderVersion < LAST_VERSION_OF_SALAMANDER) { // reject older versions MessageBox(salamander->GetParentWindow(), REQUIRE_LAST_VERSION_OF_SALAMANDER, - "FTP Client" /* neprekladat! */, MB_OK | MB_ICONERROR); + "FTP Client" /* do not translate */, MB_OK | MB_ICONERROR); return NULL; } // let the language module (.slg) load - HLanguage = salamander->LoadLanguageModule(salamander->GetParentWindow(), "FTP Client" /* neprekladat! */); + HLanguage = salamander->LoadLanguageModule(salamander->GetParentWindow(), "FTP Client" /* do not translate */); if (HLanguage == NULL) return NULL; @@ -332,7 +332,7 @@ CPluginInterfaceAbstract* WINAPI SalamanderPluginEntry(CSalamanderPluginEntryAbs return NULL; // error } - // set the basic information about the plug-in + // set the basic information about the plugin salamander->SetBasicPluginData(LoadStr(IDS_PLUGINNAME), FUNCTION_CONFIGURATION | FUNCTION_LOADSAVECONFIGURATION | FUNCTION_FILESYSTEM, @@ -585,9 +585,9 @@ void CPluginInterface::LoadConfiguration(HWND parent, HKEY regKey, CSalamanderRe registry->GetValue(regKey, CONFIG_UPLOADDIRALREADYEXISTS, REG_DWORD, &Config.UploadDirAlreadyExists, sizeof(DWORD)); registry->GetValue(regKey, CONFIG_UPLOADRETRYONCREATFILE, REG_DWORD, &Config.UploadRetryOnCreatedFile, sizeof(DWORD)); - // adjustment of a poorly chosen default - based on user feedback I changed "Overwrite" to "Resume or Overwrite" - // (they were annoyed that after an hour of upload and a broken connection the file was overwritten instead of resumed, the risk of - // Resume is hopefully small enough, so I changed it to "Resume or Overwrite") + // adjustment of a poorly chosen default - based on user feedback, "Overwrite" was changed to "Resume or Overwrite" + // (users were annoyed that after an hour of uploading and a broken connection, the file was overwritten instead of resumed; the risk of + // Resume errors is hopefully small enough, so it was changed to "Resume or Overwrite") if (ConfigVersion < 29 && Config.UploadRetryOnCreatedFile == RETRYONCREATFILE_OVERWRITE) Config.UploadRetryOnCreatedFile = RETRYONCREATFILE_RES_OVRWR; @@ -642,7 +642,7 @@ void CPluginInterface::LoadConfiguration(HWND parent, HKEY regKey, CSalamanderRe registry->GetValue(regKey, CONFIG_ALWAYSSHOWLOGFORACTPAN, REG_DWORD, &Config.AlwaysShowLogForActPan, sizeof(DWORD)); registry->GetValue(regKey, CONFIG_DISABLELOGWORKERS, REG_DWORD, &Config.DisableLoggingOfWorkers, sizeof(DWORD)); - // adjustment of a poorly chosen default - logging will be enabled in workers by default (I am tired of constantly pointing people to how to enable logging + the logging overhead is minimal) + // adjust a poorly chosen default - logging will now be enabled in workers by default (the logging overhead is minimal) if (ConfigVersion < 29 && Config.DisableLoggingOfWorkers) Config.DisableLoggingOfWorkers = FALSE; @@ -698,8 +698,8 @@ void CPluginInterface::LoadConfiguration(HWND parent, HKEY regKey, CSalamanderRe registry->GetValue(regKey, CONFIG_OPERDLGCLOSEIFSUCCESS, REG_DWORD, &Config.CloseOperationDlgIfSuccessfullyFinished, sizeof(DWORD)); - // commented out because remembering this checkbox feels odd to me - I now see the meaning of the checkbox - // in having the option to let the dialog close after the operation completes (which does not depend on the previous operation) + // commented out because remembering this checkbox seems odd - the checkbox now appears to mean + // having the option to close the dialog after the operation completes (which does not depend on the previous operation) // registry->GetValue(regKey, CONFIG_OPERDLGCLOSEWHENFINISHES, REG_DWORD, // &Config.CloseOperationDlgWhenOperFinishes, sizeof(DWORD)); @@ -874,8 +874,8 @@ void CPluginInterface::SaveConfiguration(HWND parent, HKEY regKey, CSalamanderRe registry->SetValue(regKey, CONFIG_OPERDLGCLOSEIFSUCCESS, REG_DWORD, &Config.CloseOperationDlgIfSuccessfullyFinished, sizeof(DWORD)); - // commented out because remembering this checkbox feels odd to me - I now see the meaning of the checkbox - // in having the option to let the dialog close after the operation completes (which does not depend on the previous operation) + // commented out because remembering this checkbox seems odd - the checkbox now appears to mean + // having the option to close the dialog after the operation completes (which does not depend on the previous operation) // registry->SetValue(regKey, CONFIG_OPERDLGCLOSEWHENFINISHES, REG_DWORD, // &Config.CloseOperationDlgWhenOperFinishes, sizeof(DWORD)); @@ -1068,7 +1068,7 @@ void CPluginInterface::AcceptChangeOnPathNotification(const char* path, BOOL inc void CPluginInterface::ReleasePluginDataInterface(CPluginDataInterfaceAbstract* pluginData) { - if (pluginData != &SimpleListPluginDataInterface) // it is global, no need to release it + if (pluginData != &SimpleListPluginDataInterface) // the global one does not need to be released { delete ((CFTPListingPluginDataInterface*)pluginData); } diff --git a/src/plugins/ftp/ftp.h b/src/plugins/ftp/ftp.h index e38247f89..a18083ed0 100644 --- a/src/plugins/ftp/ftp.h +++ b/src/plugins/ftp/ftp.h @@ -93,10 +93,10 @@ extern HICON FTPOperIcon; // (16x16) icon of the operation dialog extern HICON FTPOperIconBig; // large (32x32) icon of the operation dialog extern HCURSOR DragCursor; // cursor for the drag&drop list box in the Connect dialog extern HFONT FixedFont; // font for the Welcome Message dialog (fixed so text layout works better) -extern HFONT SystemFont; // environment font (dialogs, wait window, etc.) +extern HFONT SystemFont; // system font (dialogs, wait window, etc.) extern HICON WarningIcon; // small (16x16) "warning" icon for the operation dialog -// generic Salamander interface - valid from startup until the plug-in is closed +// generic Salamander interface - valid from startup until the plugin is closed extern CSalamanderGeneralAbstract* SalamanderGeneral; // ZLIB compression/decompression interface; @@ -105,11 +105,11 @@ extern CSalamanderZLIBAbstract* SalZLIB; // interface providing customized Windows controls used in Salamander extern CSalamanderGUIAbstract* SalamanderGUI; -// FS name assigned by Salamander after the plug-in is loaded +// FS name assigned by Salamander after the plugin is loaded extern char AssignedFSName[MAX_PATH]; extern int AssignedFSNameLen; // length of AssignedFSName -// FS name for FTP over SSL (FTPS) assigned by Salamander after the plug-in loads +// FS name for FTP over SSL (FTPS) assigned by Salamander after the plugin loads extern char AssignedFSNameFTPS[MAX_PATH]; extern int AssignedFSNameIndexFTPS; // index of AssignedFSNameFTPS extern int AssignedFSNameLenFTPS; // length of AssignedFSNameFTPS @@ -121,7 +121,7 @@ extern unsigned char* UpperCase; // frequently used error message extern const char* LOW_MEMORY; -extern const char* SAVEBITS_CLASSNAME; // class for CWaitWindow +extern const char* SAVEBITS_CLASSNAME; // window class for CWaitWindow extern int GlobalShowLogUID; // UID of the log that FTPCMD_SHOWLOGS should show (-1 == none) extern int GlobalDisconnectPanel; // panel for which disconnect is called (-1 == active panel - source) @@ -191,7 +191,7 @@ void ConnectFTPServer(HWND parent, int panel); void OrganizeBookmarks(HWND parent); // copies the contents of 'newStr' into 'str', reallocates 'str' if needed; sets 'err' (if not NULL) to TRUE -// on low memory; if 'clearMem' is TRUE, wipes memory that stops being used (due to passwords) +// on out-of-memory; if 'clearMem' is TRUE, clears memory that is no longer used (for passwords) void UpdateStr(char*& str, const char* newStr, BOOL* err = NULL, BOOL clearMem = FALSE); // scrambling and the reverse process used for storing passwords in the registry @@ -221,12 +221,12 @@ void GetMyDocumentsPath(char* initDir); char* GetTypeNameForUser(char* typeName, char* buf, int bufSize); // loads from resources the standard column name identified by 'id' (columns for -// "server type" - solution for translating user-defined parsers); +// "server type" - support for translating user-defined parsers); // returns TRUE if 'id' is known BOOL LoadStdColumnStrName(char* buf, int bufSize, int id); // loads from resources the standard column description identified by 'id' (columns for -// "server type" - solution for translating user-defined parsers) +// "server type" - support for translating user-defined parsers) // returns TRUE if 'id' is known BOOL LoadStdColumnStrDescr(char* buf, int bufSize, int id); @@ -238,7 +238,7 @@ BOOL ConvertStringTxtToReg(char* buf, int bufSize, const char* txtStr); // RegEdit cannot import strings with EOLs from .reg files -> replace EOLs (CRLF with '|', // LF with '!' and CR with '$'); -// converts a registry string to a regular string; returns FALSE if the result +// converts a registry string to a normal string; returns FALSE if the result // did not fit into the buffer BOOL ConvertStringRegToTxt(char* buf, int bufSize, const char* regStr); @@ -274,7 +274,7 @@ enum CSrvTypeColumnTypes stctExt, // 2, extension appended to the name (without stctName it makes no sense) stctSize, // 3, size (UNSIGNED INT64) - default empty value in the column is "0" + directories always have value "0" and the panel shows "DIR" stctDate, // 4, date (NOTE: CFileData stores UTC time - requires a local->UTC conversion) - default empty value in the column is "1.1.1602" (adjusted according to regional settings) - stctTime, // 5, time (NOTE: CFileData stores UTC time - requires a local->UTC conversion) - default empty value in the column is "0:00:00" (adjusted according to regional settings) + stctTime, // 5, time (NOTE: CFileData stores UTC time - conversion from UTC to local time is required) - the default empty value in the column is "0:00:00" (adjusted according to regional settings) stctType, // 6, file type description (works only if 'stctExt' is present) // general columns stored outside CFileData (attached before CFileData::PluginData) // NOTE: numbering must match 'stctFirstGeneral' @@ -354,11 +354,11 @@ struct CSrvTypeColumn void LoadFromObj(CSrvTypeColumn* copyFrom); // loads column data from a string (the structure must be new); - // returns success of the operation + // returns whether the operation succeeded BOOL LoadFromStr(const char* str); - // stores the data to buffer 'buf' of size 'bufSize'; returns FALSE only if the data - // do not fit into the buffer + // stores the data in buffer 'buf' of size 'bufSize'; returns FALSE only if the data + // do not fit in the buffer BOOL SaveToStr(char* buf, int bufSize, BOOL ignoreColWidths = FALSE); // allocates a copy of the structure, returns NULL on error @@ -385,16 +385,16 @@ struct CSrvTypeColumn BOOL LoadStr(const char** str, char** result, int limit); }; -// verifies whether the column list is valid (contains a visible Name column at position one -// + the Ext column is visible and can be only at position two + variable names are -// unique and non-empty + column names and descriptions are non-empty + except for the "general/any" type -// the types in the column list are not repeated + the empty value has a permitted -// format according to the column type); returns TRUE if the list is valid, otherwise returns FALSE and -// in 'errResID' (if not NULL) the ID of the error description in resources +// verifies whether the column list is valid (contains a visible Name column +// in the first position + the Ext column is visible and can only be in the second +// position + variable names are unique and non-empty + column names and descriptions +// are non-empty + except for the "general/any" type, types in the column list are not +// repeated + the empty value has a format permitted by the column type); returns TRUE +// if the list is valid, otherwise returns FALSE and stores the resource ID of the error description in 'errResID' (if not NULL) BOOL ValidateSrvTypeColumns(TIndirectArray* columns, int* errResID); -// returns TRUE if the identifier is OK, otherwise returns FALSE and in 'errResID' (if not NULL) -// returns the ID of the error description in resources +// returns TRUE if the identifier is valid, otherwise returns FALSE and stores the resource ID +// of the error description in 'errResID' (if not NULL) BOOL IsValidIdentifier(const char* s, int* errResID); class CFTPAutodetCondNode; @@ -418,7 +418,7 @@ struct CServerType // !!! NOTE: when adding a new variable it is necessary to update all structure methods !!! // helper variable for listing parser autodetection - no need to initialize/copy, etc. - BOOL ParserAlreadyTested; // TRUE if this server type has already been tried on the listing (unsuccessfully) + BOOL ParserAlreadyTested; // TRUE if this server type has already been tried against the listing (unsuccessfully) CServerType() : Columns(5, 5) { Init(); } ~CServerType() { Release(); } @@ -426,11 +426,11 @@ struct CServerType void Init(); // initializes all object variables void Release(); // releases and initializes all object variables - // sets the structure, returns FALSE on error + // sets the structure, returns FALSE on failure BOOL Set(const char* typeName, const char* autodetectCond, int columnsCount, const char* columnsStr[], const char* rulesForParsing); - // sets the structure (except for 'typeName' it takes everything from 'copyFrom'), returns FALSE on error + // sets the structure (everything except 'typeName' is taken from 'copyFrom'); returns FALSE on failure BOOL Set(const char* typeName, CServerType* copyFrom); // loads the structure, returns TRUE if the item is valid (should be added to the list) @@ -463,8 +463,8 @@ class CServerTypeList : public TIndirectArray // adds a server type to the list BOOL AddServerType(const char* typeName, CServerType* copyFrom); - // adds names to the combo box + returns the index of type 'serverType' in 'index' (if - // not found, returns 'index'==-1); 'serverType' may also be NULL (returns 'index'==-1) + // adds names to the combo box and returns the index of server type 'serverType' in 'index' (if + // not found, 'index' is set to -1); 'serverType' may also be NULL ('index' is set to -1) void AddNamesToCombo(HWND combo, const char* serverType, int& index); // adds names to the list box @@ -480,9 +480,9 @@ class CServerTypeList : public TIndirectArray BOOL CopyItemsFrom(CServerTypeList* list); // returns TRUE if the list already contains the name 'typeName' (regardless of "user defined"); - // if 'exclude' is not NULL, it is an item to exclude from the search (used when renaming so - // the item being renamed is not found); in 'index' (if not NULL) - // returns the index of the found item (-1 if the item is not found) + // if 'exclude' is not NULL, it is the item to exclude from the search (used when renaming so + // the item being renamed is not found); the index of the found item is returned in 'index' + // (if not NULL), or -1 if the item is not found BOOL ContainsTypeName(const char* typeName, CServerType* exclude, int* index = NULL); }; @@ -503,7 +503,7 @@ struct CFTPServer int SavePassword; // TRUE = password should be stored on media (registry/config file) int ProxyServerUID; // proxy server: -2 = default, -1 = not used, otherwise the proxy server UID from Config.FTPProxyServerList char* TargetPanelPath; // if not NULL or "", the target path in the panel should be set (max. MAX_PATH-1 characters) - char* ServerType; // server type (for listing) - NULL == auto-detect, otherwise a textual name (format see CServerType::TypeName; the server list will gradually expand) (max. SERVERTYPE_MAX_SIZE-1 characters) + char* ServerType; // server type (for listing) - NULL == auto-detect, otherwise a textual name (format see CServerType::TypeName; the list of server types will gradually expand) (max. SERVERTYPE_MAX_SIZE-1 characters) char* ListCommand; // command for listing - NULL == LIST_CMD_TEXT, otherwise the command text int TransferMode; // 0 - default, 1 - binary, 2 - ascii, 3 - auto (uses Config.ASCIIFileMasks) int Port; // port of the server we connect to (standard FTP port is IPPORT_FTP) @@ -522,7 +522,7 @@ struct CFTPServer int EncryptDataConnection; // 0 - no, 1 - yes int CompressData; // 0 - no; 1-9 - zlib levels; -1 - default, based on configuration - // !!! NOTE: when adding a new variable it is necessary to update all structure methods !!! + // !!! NOTE: when adding a new variable, all methods of this structure must be updated !! CFTPServer() { Init(); } ~CFTPServer() { Release(); } @@ -532,8 +532,8 @@ struct CFTPServer // releases and zeroes the structure data void Release(); - // allocates a copy of the structure, returns NULL on error - // NOTE: clears user-name, password, and save-passwd when anonymous connection is enabled + // allocates a copy of the structure; returns NULL on failure + // WARNING: clears user-name, password, and save-passwd when anonymous connection is enabled CFTPServer* MakeCopy(); // sets the structure, returns FALSE on error @@ -566,7 +566,7 @@ struct CFTPServer int encryptDataConnection, int compressData); - // sets the structure based on source 'src', returns FALSE on error + // sets the structure based on source 'src', returns FALSE on failure BOOL Set(const CFTPServer& src) { return Set(src.ItemName, @@ -599,14 +599,14 @@ struct CFTPServer src.CompressData); } - // loads the structure, returns TRUE if the item is valid (should be added to the list) + // Loads the structure; returns TRUE if the item is valid (it should be added to the list). BOOL Load(HWND parent, HKEY regKey, CSalamanderRegistryAbstract* registry); // saves the structure void Save(HWND parent, HKEY regKey, CSalamanderRegistryAbstract* registry); - // returns TRUE if the (plain) password can be obtained; - // if a master password is used and not entered, asks the user for it (the window is shown via 'hParent); - // if the user did not enter the correct master password or it could not decrypt the password, returns FALSE + // returns TRUE if the plaintext password can be obtained; + // if a master password is used and has not been entered, asks the user for it (the dialog is shown with hParent as parent); + // if the user did not enter the correct master password or the password could not be decrypted with it, returns FALSE BOOL EnsurePasswordCanBeDecrypted(HWND hParent); }; @@ -617,8 +617,8 @@ class CFTPServerList : public TIndirectArray public: CFTPServerList() : TIndirectArray(10, 10) {} - // copies (allocates) all list items into list 'dstList' (first completely deletes it) - // NOTE: clears user-name, password, and save-passwd when anonymous connection is enabled + // copies (allocates) all list items into 'dstList' (clears it completely first) + // WARNING: clears user name, password, and save-passwd when anonymous connection is enabled BOOL CopyMembersToList(CFTPServerList& dstList); // adds a bookmark to the FTP server list @@ -731,32 +731,32 @@ struct CProxyScriptParams // helper structure for running proxy scripts CProxyScriptParams(); }; -// validates or gradually executes a proxy script; during validation '*execPoint', +// validates or executes a proxy script step by step; during validation, '*execPoint', // 'scriptParams', 'hostBuf', 'port', 'sendCmdBuf', and 'logCmdBuf' are NULL and 'lastCmdReply'==-1; -// the function returns TRUE if the script is OK (FALSE on error, with the error text in 'errDescrBuf'); +// the function returns TRUE if the script is valid (FALSE on error, with the error text in 'errDescrBuf'); // 'script' is the proxy script text; '*execPoint' ('execPoint' must not be NULL) is -// the current execution position (the script is executed step by step); if it is NULL, we start -// validation/execution from the beginning of the script; 'lastCmdReply' is the result of the command from the previous -// line (-1 = previous line was skipped or this is the first line); 'scriptParams' -// contains the input values of individual variables; possible results of the +// the current execution position; if it is NULL, validation/execution starts at the beginning +// of the script; 'lastCmdReply' is the result of the command from the previous +// line (-1 = the previous line was skipped or this is the first line); on input, 'scriptParams' +// contains the values of the individual variables; possible results of the // ProcessProxyScript function: -// - script error: the function returns FALSE + the error position is returned in '*execPoint' + the error +// - script error: the function returns FALSE, the error position is returned in '*execPoint', and the error // description is in 'errDescrBuf' // - missing variable value: the function returns TRUE and scriptParams->NeedUserInput() -// returns TRUE (the value of '*execPoint' does not change) -// - successfully determined host:port to connect to (only at the beginning of the script): returns TRUE -// and returns the connection target in 'hostBuf'+'port'; '*execPoint' points to the start +// returns TRUE ('*execPoint' is unchanged) +// - successfully determined host:port to connect to (only at the beginning of the script): returns TRUE, +// and 'hostBuf' and 'port' receive the destination; '*execPoint' points to the start // of the next script line -// - successfully determined which command to send to the server (not possible at the beginning of the script): returns -// TRUE and 'sendCmdBuf' contains the command (including CRLF at the end), 'logCmdBuf' contains the +// - successfully determined command to send to the server (not possible at the beginning of the script): returns +// TRUE, 'sendCmdBuf' contains the command (including CRLF at the end), and 'logCmdBuf' contains the // log text (the password is replaced with "(hidden)"); '*execPoint' points to the start // of the next script line -// - end of script (not possible at the beginning of the script): returns TRUE and 'sendCmdBuf' is an empty -// string; '*execPoint' points to the end of the script; +// - end of script (not possible at the beginning of the script): returns TRUE, 'sendCmdBuf' is an empty +// string, and '*execPoint' points to the end of the script; // 'hostBuf' (if not NULL) is a buffer of size HOST_MAX_SIZE characters; 'sendCmdBuf' // and 'logCmdBuf' (if not NULL) are buffers of size FTPCOMMAND_MAX_SIZE characters; // 'errDescrBuf' is a buffer of size 300 characters; 'proxyHostNeeded' (if not NULL) -// returns TRUE if ProxyHost must be specified (we connect to it) +// is set to TRUE if ProxyHost must be specified (the connection is made to it) BOOL ProcessProxyScript(const char* script, const char** execPoint, int lastCmdReply, CProxyScriptParams* scriptParams, char* hostBuf, unsigned short* port, char* sendCmdBuf, char* logCmdBuf, char* errDescrBuf, @@ -770,7 +770,7 @@ const char* GetProxyScriptText(CFTPProxyServerType type, BOOL textForDialog); // returns the default port for a proxy server of the given type unsigned short GetProxyDefaultPort(CFTPProxyServerType type); -// returns TRUE if the given proxy server type uses a password for the proxy server +// returns TRUE if the given proxy server type uses a proxy server password BOOL HavePassword(CFTPProxyServerType type); // returns TRUE if the given proxy server type uses the proxy server address and port @@ -819,7 +819,7 @@ struct CFTPProxyServer char* ProxyScript; // only for ProxyType==fpstOwnScript (otherwise NULL): script for connecting to the FTP server - // !!! NOTE: when adding a new variable it is necessary to update all structure methods !!! + // !!! NOTE: when adding a new variable, all methods of this structure must be updated ! CFTPProxyServer(int proxyUID) { Init(proxyUID); } ~CFTPProxyServer() { Release(); } @@ -829,10 +829,10 @@ struct CFTPProxyServer // releases and zeroes the structure data void Release(); - // allocates a copy of the structure, returns NULL on error + // allocates a copy of the structure, returns NULL on failure CFTPProxyServer* MakeCopy(); - // allocates a CFTPProxyForDataCon structure, returns NULL on error + // allocates a CFTPProxyForDataCon structure, returns NULL on failure CFTPProxyForDataCon* AllocProxyForDataCon(DWORD proxyHostIP, const char* host, DWORD hostIP, unsigned short hostPort); @@ -848,7 +848,7 @@ struct CFTPProxyServer // sets ProxyUser BOOL SetProxyUser(const char* proxyUser); - // sets the structure, returns FALSE on error + // sets the structure; returns FALSE on failure BOOL Set(int proxyUID, const char* proxyName, CFTPProxyServerType proxyType, @@ -860,7 +860,7 @@ struct CFTPProxyServer int saveProxyPassword, const char* proxyScript); - // sets the structure based on source 'src', returns FALSE on error + // sets the structure based on source 'src', returns FALSE on failure BOOL Set(const CFTPProxyServer& src) { return Set(src.ProxyUID, @@ -875,7 +875,7 @@ struct CFTPProxyServer src.ProxyScript); } - // loads the structure, returns TRUE if the item is valid (should be added to the list) + // Loads the structure; returns TRUE if the item is valid (it should be added to the list). BOOL Load(HWND parent, HKEY regKey, CSalamanderRegistryAbstract* registry); // saves the structure void Save(HWND parent, HKEY regKey, CSalamanderRegistryAbstract* registry); @@ -901,7 +901,7 @@ class CFTPProxyServerList : protected TIndirectArray // (non-empty and unique among the other proxy servers) BOOL IsProxyNameOK(CFTPProxyServer* proxyServer, const char* proxyName); - // copies (allocates) all elements of the list into the list 'dstList' (first deletes it completely) + // copies (allocates) all elements of the list into 'dstList' (first clears it completely) BOOL CopyMembersToList(CFTPProxyServerList& dstList); // fills the "Proxy Server" combo box; 'combo' is the combo box; 'focusProxyUID' is the UID of the server @@ -976,9 +976,9 @@ class CFTPProxyServerList : protected TIndirectArray // returns TRUE if the server list contains an item whose password is not encrypted with AES (only scrambled) BOOL ContainsUnsecuredPassword(); - // returns TRUE if the (plain) password for the proxy server with UID 'proxyServerUID' can be obtained; - // if a master password is used and not entered, asks the user for it (window is shown via 'hParent) - // if the user did not enter the correct master password or it could not decrypt the password, returns FALSE + // returns TRUE if the plain password for the proxy server with UID 'proxyServerUID' can be obtained; + // if a master password is used and has not been entered, asks the user for it (the window is shown with 'hParent' as the parent); + // if the user does not enter the correct master password or the password cannot be decrypted with it, returns FALSE BOOL EnsurePasswordCanBeDecrypted(HWND hParent, int proxyServerUID); }; @@ -1036,16 +1036,16 @@ class CConfiguration int UseMaxClosedConLogs; // TRUE = use MaxClosedConLogs int MaxClosedConLogs; // maximum number of logs of closed connections (older ones are discarded) int AlwaysShowLogForActPan; // TRUE = activate the log when the FTP connection becomes active in the panel - int DisableLoggingOfWorkers; // TRUE = disable logging of worker communication with the server + int DisableLoggingOfWorkers; // TRUE = disable logging of workers' communication with the server WINDOWPLACEMENT LogsDlgPlacement; // position of the Logs dialog WINDOWPLACEMENT OperDlgPlacement; // position of the Operations dialog (user's last setting) double OperDlgSplitPos; // position of the splitter between list views in the Operations dialog - int CloseOperationDlgIfSuccessfullyFinished; // TRUE = automatically close the operations dialog when an operation finishes without errors/questions in the untouched dialog + int CloseOperationDlgIfSuccessfullyFinished; // TRUE = automatically close the operations dialog when an operation finishes without errors or prompts, if the dialog was left untouched int CloseOperationDlgWhenOperFinishes; // TRUE = close the operations dialog after the operation completes (if no Solve Error dialog is open) int OpenSolveErrIfIdle; // TRUE = automatically open the Solve Error dialog when it is idle - char* CommandHistory[COMMAND_HISTORY_SIZE]; // history of FTP commands (from the "Send FTP Command" command) + char* CommandHistory[COMMAND_HISTORY_SIZE]; // history of FTP commands (from the "Send FTP Command" dialog) int SendSecretCommand; // last state of the "Secret command" checkbox in the "Send FTP Command" dialog char* HostAddressHistory[HOSTADDRESS_HISTORY_SIZE]; // history of server addresses in the Connect to FTP Server dialog @@ -1373,21 +1373,21 @@ class CFTPListingPluginDataInterface : public CPluginDataInterfaceAbstract // prepares data in file.PluginData for further use (deallocates and clears strings) void ClearPluginData(CFileData& file); - // stores the allocated string 'str' into the structure 'file' into column 'column'; + // stores the allocated string 'str' in column 'column' of the 'file' structure; // 'str' is deallocated when ReleasePluginData() is called for 'file'; when - // overwriting a string the overwritten string is deallocated + // overwriting a string, the overwritten string is deallocated void StoreStringToColumn(CFileData& file, int column, char* str); - // stores day 'day' into the structure 'file' into column 'column' into a CFTPDate structure + // stores day 'day' in column 'column' of the 'file' structure in a CFTPDate structure void StoreDayToColumn(CFileData& file, int column, BYTE day); - // stores month 'month' into the structure 'file' into column 'column' into a CFTPDate structure + // stores month 'month' in column 'column' of the 'file' structure in a CFTPDate structure void StoreMonthToColumn(CFileData& file, int column, BYTE month); - // stores year 'year' into the structure 'file' into column 'column' into a CFTPDate structure + // stores year 'year' in column 'column' of the 'file' structure in a CFTPDate structure void StoreYearToColumn(CFileData& file, int column, WORD year); - // stores date 'day'+'month'+'year' into the structure 'file' into column 'column' into a CFTPDate structure + // stores date 'day'+'month'+'year' in column 'column' of the 'file' structure in a CFTPDate structure void StoreDateToColumn(CFileData& file, int column, BYTE day, BYTE month, WORD year); // stores time 'hour'+'minute'+'second'+'millisecond' into the structure 'file' into column 'column' @@ -1395,22 +1395,22 @@ class CFTPListingPluginDataInterface : public CPluginDataInterfaceAbstract void StoreTimeToColumn(CFileData& file, int column, BYTE hour, BYTE minute, BYTE second, WORD millisecond); - // stores number 'number' into the structure 'file' into column 'column' + // stores the number 'number' in column 'column' of the 'file' structure void StoreNumberToColumn(CFileData& file, int column, __int64 number); // returns a string from the structure 'file' from column 'column' char* GetStringFromColumn(const CFileData& file, int column); - // returns (in the relevant part of the structure 'stVal') the date from the structure 'file' from column 'column' + // returns the date from column 'column' of the 'file' structure in the corresponding part of the 'stVal' structure void GetDateFromColumn(const CFileData& file, int column, SYSTEMTIME* stVal); - // returns in 'date' the date from the structure 'file' from column 'column' + // returns the date from column 'column' of the 'file' structure in 'date' void GetDateFromColumn(const CFileData& file, int column, CFTPDate* date); - // returns (in the relevant part of the structure 'stVal') the time from the structure 'file' from column 'column' + // returns the time from column 'column' of the 'file' structure in the corresponding part of the 'stVal' structure void GetTimeFromColumn(const CFileData& file, int column, SYSTEMTIME* stVal); - // returns in 'time' the time from the structure 'file' from column 'column' + // returns the time from column 'column' of the 'file' structure in 'time' void GetTimeFromColumn(const CFileData& file, int column, CFTPTime* time); // returns a number from the structure 'file' from column 'column'; @@ -1420,9 +1420,9 @@ class CFTPListingPluginDataInterface : public CPluginDataInterfaceAbstract // finds the "Rights" column with textual content; if it does not exist, returns -1 int FindRightsColumn(); - // if the size of the file 'file' is known, returns TRUE and the size in 'size' and - // in 'inBytes' returns TRUE/FALSE depending on whether the size is in bytes/blocks; - // if the file size is not known, returns FALSE and does not modify 'size' or 'inBytes' + // if the size of file 'file' is known, returns TRUE, stores the size in 'size', and + // sets 'inBytes' to TRUE/FALSE depending on whether the size is in bytes or blocks; + // if the file size is not known, returns FALSE and leaves 'size' and 'inBytes' unchanged BOOL GetSize(const CFileData& file, CQuadWord& size, BOOL& inBytes); // returns the base name - currently used only when trimming version numbers from @@ -1432,9 +1432,9 @@ class CFTPListingPluginDataInterface : public CPluginDataInterfaceAbstract // an auxiliary buffer (size at least MAX_PATH) into which the adjusted name is stored void GetBasicName(const CFileData& file, char** name, char** ext, char* buffer); - // returns the date and time of the last write to the file; in 'dateAndTimeValid' returns - // FALSE if this date+time is not known; also returns "empty values": - // for the date it sets date->Day == 0, for the time it sets time->Hour == 24 + // returns the date and time of the last write to the file; sets 'dateAndTimeValid' to + // FALSE if this date and time are not known; also returns "empty values": + // for the date, date->Day == 0; for the time, time->Hour == 24 void GetLastWriteDateAndTime(const CFileData& file, BOOL* dateAndTimeValid, CFTPDate* date, CFTPTime* time); @@ -1505,9 +1505,9 @@ class CPluginFSInterface : public CPluginFSInterfaceAbstract CTopIndexMem TopIndexMem; // top-index memory for ExecuteOnFS() CControlConnectionSocket* ControlConnection; // "control connection" socket to the FTP server (NULL == never connected) - char RescuePath[FTP_MAX_PATH]; // rescue path on FTP - try when ChangePath() can no longer shorten the path + char RescuePath[FTP_MAX_PATH]; // fallback path on FTP - try it when ChangePath() can no longer shorten the path char HomeDir[FTP_MAX_PATH]; // default path on FTP - set after logging into the server - BOOL OverwritePathListing; // if TRUE, PathListing should be overwritten with a new listing (once/if we obtain it) - handles the situation when ChangePath is called and ListCurrentPath is no longer invoked because the path did not change + BOOL OverwritePathListing; // if TRUE, PathListing should be overwritten with a new listing if one is obtained - handles the situation when ChangePath is called and ListCurrentPath is no longer invoked because the path did not change char* PathListing; // if not NULL, contains at least part (can also be "") of the listing of the current path int PathListingLen; // length of the string in PathListing CFTPDate PathListingDate; // date when the listing was obtained (needed for "year_or_time") @@ -1530,7 +1530,7 @@ class CPluginFSInterface : public CPluginFSInterfaceAbstract BOOL InformAboutUnknownSrvType; // TRUE until the user is informed that we cannot find a listing parser (unsupported server type) BOOL NextRefreshCanUseOldListing; // TRUE only if only the configuration changed (parsers, columns) and therefore it is not necessary to read the listing from the server again - BOOL NextRefreshWontClearCache; // TRUE only if the refresh happened based on a "change on path" notification and it is therefore not necessary to clear the current path from the cache (done elsewhere) + BOOL NextRefreshWontClearCache; // TRUE only if the refresh was triggered by a "change on path" notification, so the current path does not need to be cleared from the cache (done elsewhere) int TransferMode; // file transfer mode (binary/ascii/auto) (values of type CTransferMode) @@ -1542,10 +1542,10 @@ class CPluginFSInterface : public CPluginFSInterfaceAbstract CPluginFSInterface(); ~CPluginFSInterface(); - // creates the user-part of an FTP path - format "//user@host:port/path"; 'buffer' is - // the buffer for the result with size 'bufferSize' bytes; 'path' is the FTP path, if - // 'path' is NULL the current FTP path is used; if 'ignorePath' is TRUE the user-part - // path is created without the FTP path; returns TRUE if the buffer 'buffer' + // creates the user part of an FTP path in the format "//user@host:port/path"; 'buffer' is + // the output buffer of size 'bufferSize' bytes; 'path' is the FTP path; if + // 'path' is NULL, the current FTP path is used; if 'ignorePath' is TRUE, the user part + // is created without the FTP path; returns TRUE if 'buffer' // is large enough for the result (otherwise the result is truncated and FALSE is returned) BOOL MakeUserPart(char* buffer, int bufferSize, char* path = NULL, BOOL ignorePath = FALSE); @@ -1645,16 +1645,16 @@ class CPluginFSInterface : public CPluginFSInterfaceAbstract // simply calls IsListCommandLIST_a() on the control connection BOOL IsListCommandLIST_a(); - // opens the operation progress window and runs it in the active "control connection" - // (the items are processed in a worker created based on the active control connection - // in the panel (when called, ControlConnection is guaranteed to be not NULL)); - // 'parent' is the "foreground" window of the thread (after pressing ESC it is used to - // determine whether ESC was pressed in this window and not in another application; in the main thread it is + // opens the operation progress window and starts the operation on the active "control connection" + // (the items are processed by a worker created from the active control connection + // in the panel (when called, ControlConnection is guaranteed to be non-NULL)); + // 'parent' is the thread's "foreground" window (after ESC is pressed, it is used to + // determine whether ESC was pressed in this window and not, for example, in another application; in the main thread it is // SalamanderGeneral->GetMsgBoxParent() or a dialog opened by the plugin); returns TRUE - // when the operation starts successfully (otherwise an error occurs and the operation is cancelled) + // if the operation starts successfully (otherwise an error occurs and the operation is canceled) BOOL RunOperation(HWND parent, int operUID, CFTPOperation* oper, HWND dropTargetWnd); - // returns TRUE if the "control connection" has the UID 'controlConUID' + // returns TRUE if there is a "control connection" with UID 'controlConUID' BOOL ContainsConWithUID(int controlConUID); // simply forwards the call to ControlConnection->GetConnectionFromWorker diff --git a/src/plugins/ftp/ftp2.cpp b/src/plugins/ftp/ftp2.cpp index c1b104da3..93be7912e 100644 --- a/src/plugins/ftp/ftp2.cpp +++ b/src/plugins/ftp/ftp2.cpp @@ -804,16 +804,16 @@ char* GetTypeNameForUser(char* typeName, char* buf, int bufSize) #define WSTF_MAX_LINE_LEN 80 // used when writing and reading a string to a file -// writes string 'str' to file 'file', returns any error in 'err' (must not be NULL); -// format (apart from "// " at the beginning of the line exactly as it will be in the file - '"', '\', etc. have no C++ meaning): -// "first line starts with double quotes -// long lines has backslash after each part of line: -// line-part1\ -// line-part2\ +// writes string 'str' to file 'file'; returns any error in 'err' ('err' must not be NULL); +// format (except for the "// " at the beginning of the line, exactly as it will be in the file - '"', '\\', etc. do not have C++ meaning): +// "first line starts with a double quote +// long lines have a backslash after each line part: +// line-part1\\ +// line-part2\\ // line-part3 -// next-line with escape sequence \" for double quotes and \\ for backslash -// NULL string is written only as \0 escape sequence -// lastline ends with double quotes" +// next-line with escape sequence \\\" for double quotes and \\\\ for backslash +// NULL string is written only as the \\0 escape sequence +// last line ends with a double quote" void WriteStrToFile(HANDLE file, const char* str, DWORD* err) { char line[WSTF_MAX_LINE_LEN + 3]; // 3 characters are overhead for easy writing @@ -821,7 +821,7 @@ void WriteStrToFile(HANDLE file, const char* str, DWORD* err) BOOL success; if (str == NULL) { - strcpy(line, "\"\\0\"\r\n"); // string for a NULL value + strcpy(line, "\"\\0\"\r\n"); // representation of a NULL string int len = (int)strlen(line); if ((success = WriteFile(file, line, len, &written, NULL)) == 0 || written != (DWORD)len) @@ -962,7 +962,7 @@ CServerType::ExportToFile(HANDLE file) ULONG written; BOOL success; int len = (int)strlen(line); - if (len > 0 && // there is something to write + if (len > 0 && // something to write ((success = WriteFile(file, line, len, &written, NULL)) == 0 || written != (DWORD)len)) { @@ -991,7 +991,7 @@ BOOL MatchString(char* beg, char* end, const char* str, char** afterStr) return FALSE; } -// returns a null-terminated allocated string from 'beg' to 'end'; on low memory +// returns a newly allocated null-terminated string from 'beg' to 'end'; if memory allocation fails // returns NULL and stores FALSE in 'ret' char* AllocString(char* beg, char* end, BOOL* ret) { @@ -1009,13 +1009,13 @@ char* AllocString(char* beg, char* end, BOOL* ret) return s; } -// gradually reads a string from the file lines; the currently processed line is 'line' to 'lineEnd' +// reads a string incrementally from the file lines; the currently processed line is 'line' to 'lineEnd' // (not null-terminated); 'firstLine' is an IN/OUT variable initialized to -// TRUE, the ReadStrFromLines function changes it to FALSE as soon as it finds the beginning of the string; +// TRUE; ReadStrFromLines changes it to FALSE as soon as it finds the beginning of the string; // 'dynStr' receives the part of the string read from the currently processed line; the pointers -// 'firstLine' and 'dynStr' do not change during the loading of one string (they act as global -// data); in 'success' (must not be NULL) FALSE is returned on a syntax error or a -// 'dynStr' allocation error; returns TRUE if the entire string has already been read and in 'isNULLStr' returns +// 'firstLine' and 'dynStr' do not change while reading one string (they serve as global +// data); 'success' (must not be NULL) is set to FALSE on a syntax error or a +// 'dynStr' allocation error; returns TRUE if the entire string has already been read, and 'isNULLStr' returns // TRUE if it is NULL (otherwise the string is stored in 'dynStr') BOOL ReadStrFromLines(const char* line, const char* lineEnd, BOOL* firstLine, CDynString* dynStr, BOOL* success, BOOL* isNULLStr) @@ -1065,7 +1065,7 @@ BOOL ReadStrFromLines(const char* line, const char* lineEnd, BOOL* firstLine, { foundEnd = TRUE; eol = FALSE; - break; // end of the string found (+ no more EOL) + break; // end of the string found (+ no following EOL) } } if (d + 2 >= end) // need to "flush" the local buffer to 'dynStr' (no space left for a character + EOL) @@ -1086,9 +1086,9 @@ BOOL ReadStrFromLines(const char* line, const char* lineEnd, BOOL* firstLine, return foundEnd; } -// helper function: if 'isNULLStr' is TRUE, it returns NULL in 'str'; otherwise, if 'success' -// is TRUE, it tries to duplicate the 'dynStr' string into 'str', and on low memory returns -// 'success' as FALSE +// helper function: if 'isNULLStr' is TRUE, it stores NULL in 'str'; otherwise, if 'success' +// is TRUE, it tries to duplicate the 'dynStr' string into 'str' and sets +// 'success' to FALSE on out-of-memory void GetStrResult(char** str, BOOL* success, CDynString* dynStr, BOOL isNULLStr) { if (isNULLStr) @@ -1278,7 +1278,7 @@ BOOL CServerType::ImportFromFile(HANDLE file, DWORD* err, int* errResID) case 5: // load columns { BOOL read2 = TRUE; - if (strFirstLine) // the string has not started yet, check whether there is still a column on the line or whether they have ended + if (strFirstLine) // the string has not started yet, check whether there is still a column on the line or whether the columns have ended { char* s2 = lineBeg; while (s2 < lineEnd && *s2 <= ' ') @@ -1497,16 +1497,17 @@ CProxyScriptParams::CProxyScriptParams() } // 'buf' with size 'bufSize' is the buffer for the resulting text (host or command); -// 'logBuf' with size 'logBufSize' is the buffer for the resulting text that can be published in the log +// 'logBuf' with size 'logBufSize' is the buffer for the resulting text suitable for publishing in the log // (commands only - passwords are not published, they are replaced with the word "hidden"); 'strBeg' to 'strEnd' -// is the script text to be expanded; 'hostVarsOnly' is TRUE when expanding -// the host (only the Host and ProxyHost variables are allowed, and CRLF is not appended at the end as it is for commands); -// 'proxyHostNeeded' (if not NULL) returns TRUE when the $(ProxyHost) variable is used during the expansion +// is the script text to expand; 'hostVarsOnly' is TRUE when expanding +// the host (only the Host and ProxyHost variables are allowed, and CRLF is not appended at the end as it is +// for commands); 'proxyHostNeeded' (if not NULL) receives TRUE if the $(ProxyHost) variable is used during +// string expansion // return values: -// - error: returns FALSE, the error code is returned in 'errCode' and '*errorPos' gives the error position -// - the line should be skipped: returns TRUE with 'skipThisLine'==TRUE -// - missing variable values: returns FALSE, but 'errCode' is 0 -// - everything OK: returns TRUE with text in 'buf' +// - error: returns FALSE, the error code is returned in 'errCode' and the error position is returned in '*errorPos' +// - the line should be skipped: returns TRUE and 'skipThisLine'==TRUE +// - variable values are missing: returns FALSE, but 'errCode' is 0 +// - everything OK: returns TRUE and the text is in 'buf' BOOL ExpandText(char* buf, int bufSize, char* logBuf, int logBufSize, const char* strBeg, const char* strEnd, CProxyScriptParams* scriptParams, const char** errorPos, int* errCode, BOOL hostVarsOnly, BOOL* skipThisLine, BOOL* proxyHostNeeded) @@ -1743,7 +1744,7 @@ BOOL ExpandText(char* buf, int bufSize, char* logBuf, int logBufSize, const char int i; for (i = 0; i < 9; i++) { - if (needUserInput & (1 << i)) // necessarily means that 'scriptParams' is not NULL + if (needUserInput & (1 << i)) // implies that 'scriptParams' is not NULL { switch (i) { @@ -1830,7 +1831,7 @@ BOOL ProcessProxyScript(const char* script, const char** execPoint, int lastCmdR int errCode = 0; const char* s = *execPoint == NULL ? script : *execPoint; BOOL validateScript = scriptParams == NULL; - BOOL processNextLine = s > script; // TRUE = we should process the next line with a command in the script + BOOL processNextLine = s > script; // TRUE = process the next command line in the script if (s == script) // we are at the beginning of the script { while (*s != 0 && *s <= ' ') @@ -2427,7 +2428,7 @@ BOOL CFTPProxyServer::Load(HWND parent, HKEY regKey, CSalamanderRegistryAbstract { saveProxyPassword = TRUE; - // detect and, if needed, clear the "unnecessary" (due to storing "save password" TRUE) empty scrambled password + // detect and, if needed, clear the empty scrambled password stored only to keep "save password" TRUE CSalamanderPasswordManagerAbstract* passwordManager = SalamanderGeneral->GetSalamanderPasswordManager(); if (!passwordManager->IsPasswordEncrypted(proxyEncryptedPassword, proxyEncryptedPasswordSize)) { diff --git a/src/plugins/ftp/ftp3.cpp b/src/plugins/ftp/ftp3.cpp index be4703b9c..5000628e0 100644 --- a/src/plugins/ftp/ftp3.cpp +++ b/src/plugins/ftp/ftp3.cpp @@ -95,7 +95,7 @@ void CServerTypeList::Load(HWND parent, HKEY regKey, CSalamanderRegistryAbstract TRACE_E(LOW_MEMORY); break; } - if (!item->Load(parent, subKey, registry)) // loading failed, we ignore this item + if (!item->Load(parent, subKey, registry)) // loading failed, ignore this item { delete item; } @@ -318,7 +318,7 @@ void CFTPServerList::CheckProxyServersUID(CFTPProxyServerList& ftpProxyServerLis if (s->ProxyServerUID != -1 && s->ProxyServerUID != -2 && !ftpProxyServerList.IsValidUID(s->ProxyServerUID)) { - s->ProxyServerUID = -2; // validate the UID by switching to "default" + s->ProxyServerUID = -2; // make the UID valid by switching to "default" } } } diff --git a/src/plugins/ftp/ftp4.cpp b/src/plugins/ftp/ftp4.cpp index 5e5c70266..2a6fc8216 100644 --- a/src/plugins/ftp/ftp4.cpp +++ b/src/plugins/ftp/ftp4.cpp @@ -460,7 +460,7 @@ BOOL GetColumnEmptyValue(const char* empty, CSrvTypeColumnTypes type, CQuadWord* } else { - if (type == stctGeneralDate) // for stctGeneralDate the value "" should be displayed + if (type == stctGeneralDate) // "" should be displayed for stctGeneralDate { day = 0; skipDateCheck = TRUE; diff --git a/src/plugins/ftp/ftputils.cpp b/src/plugins/ftp/ftputils.cpp index e43d71cc2..517d15108 100644 --- a/src/plugins/ftp/ftputils.cpp +++ b/src/plugins/ftp/ftputils.cpp @@ -25,7 +25,7 @@ BOOL FTPCutDirectory(CFTPServerPathType type, char* path, int pathBufSize, switch (type) { case ftpsptUnix: - case ftpsptAS400: // although it is not perfect, I think it will be enough (improvement: if it is a /qsys.lib path and the name ends with .mbr, cut two components and return them as the file name: "/QSYS.LIB/GARY.LIB/UCLSRC.FILE/BKPLIB2.MBR" -> "/QSYS.LIB/GARY.LIB" + "UCLSRC.FILE/BKPLIB2.MBR") + case ftpsptAS400: // not perfect, but sufficient for now (improvement: for a /qsys.lib path with a name ending in .mbr, cut two components and return them as the file name: "/QSYS.LIB/GARY.LIB/UCLSRC.FILE/BKPLIB2.MBR" -> "/QSYS.LIB/GARY.LIB" + "UCLSRC.FILE/BKPLIB2.MBR") { char* lastSlash = path + l - 1; while (--lastSlash >= path && *lastSlash != '/') @@ -351,7 +351,7 @@ BOOL FTPPathAppend(CFTPServerPathType type, char* path, int pathSize, const char default: { char slash = '/'; - if (type == ftpsptNetware || type == ftpsptWindows || type == ftpsptOS2) // novell + windows + OS/2 + if (type == ftpsptNetware || type == ftpsptWindows || type == ftpsptOS2) // NetWare + Windows + OS/2 { if (l > 0 && (path[l - 1] == '/' || path[l - 1] == '\\')) { @@ -367,7 +367,7 @@ BOOL FTPPathAppend(CFTPServerPathType type, char* path, int pathSize, const char if (*name != 0) { int n = (int)strlen(name); - if (l + 1 + n < pathSize) // do we fit even with the terminating zero? + if (l + 1 + n < pathSize) // do we fit even with the terminating null character? { if (!empty) path[l] = slash; @@ -429,7 +429,7 @@ BOOL FTPIsValidAndNotRootPath(CFTPServerPathType type, const char* path) if (l > 0) // valid path = non-empty { const char* s = strchr(path, '.'); - return s == NULL || s != path + l - 1; // root ends with '.' and contains only one period + return s == NULL || s != path + l - 1; // root must not end with '.' as its only period } return FALSE; } @@ -484,7 +484,7 @@ const char* FTPFindEndOfUserNameOrHostInURL(const char* url) while (--p >= url && *p != '@' && *p != ':' && *p != '\\') ; if (p < url) - return hostEnd; // it is only the server address and port + return hostEnd; // only the server address and port if (*p == '\\' || *p == ':') skip = TRUE; // neither '\\' nor ':' belongs here, stop parsing from the right } @@ -573,12 +573,12 @@ void FTPSplitPath(char* p, char** user, char** password, char** host, char** por *e-- = 0; // clip spaces at end } *p++ = 0; - if (passwd) // next is password + if (passwd) // password follows { beg = p; p = passEnd; if (password != NULL) - *password = beg; // let password as is (do not skip spaces) + *password = beg; // leave the password as is (do not skip spaces) *p++ = 0; } // next is host @@ -630,7 +630,7 @@ int FTPGetUserLength(const char* user) while (*s != 0 && *s != '/' && *s != '\\' && *s != ':' && *s != '@') s++; if (*s == 0) - return 0; // problem-free name (including anonymous user) + return 0; // valid name (including anonymous user) while (*s != 0) s++; return (int)(s - user); @@ -981,7 +981,7 @@ BOOL HaveSubstring(const char* text, const char* sub) } t++; } - return *sub == 0; // not found (exception: empty text and empty substring) + return *sub == 0; // not found (except when both text and substring are empty) } const char* KnownOSNames[] = {"UNIX", "Windows", "NETWARE", "TANDEM", "OS/2", "VMS", "MVS", "VM", "OS/400", NULL}; @@ -1005,7 +1005,7 @@ void FTPGetServerSystem(const char* serverSystem, char* sysName) if (serverSystem != NULL) { int replyLen = (int)strlen(serverSystem); - if (*serverSystem == '2' && replyLen > 4) // FTP_D1_SUCCESS + there is a chance of the system name string + if (*serverSystem == '2' && replyLen > 4) // FTP_D1_SUCCESS + the system name string may be present { const char* sys; if (serverSystem[3] == ' ') @@ -1245,7 +1245,7 @@ CFTPServerPathType GetFTPServerPathType(const char* serverFirstReply, const char return ftpsptTandem; } else - return ftpsptWindows; // Windows are more likely than NetWare + return ftpsptWindows; // Windows is more likely than NetWare } } if (charOnFirstPos && colonOnSecondPos && colon == 1 && // paths of the form "C:" @@ -1280,7 +1280,7 @@ CFTPServerPathType GetFTPServerPathType(const char* serverFirstReply, const char return ftpsptWindows; if (HaveSubstring(sysName, "NETWARE") || serverFirstReply != NULL && HaveSubstring(serverFirstReply, " NW 3") && - HaveSubstring(serverFirstReply, " HellSoft")) // known first server response and it is a Hellsoft server on NetWare + HaveSubstring(serverFirstReply, " HellSoft")) // the server's first response is known and it is a HellSoft server on NetWare { return ftpsptNetware; } @@ -1382,7 +1382,7 @@ BOOL FTPAddHexEscapeSequences(char* txt, int txtSize) s += 3; } else - return FALSE; // maly buffer + return FALSE; // small buffer } else s++; @@ -1436,7 +1436,7 @@ BOOL GetAttrsFromUNIXRights(DWORD* actAttr, DWORD* attrDiff, const char* rights) // CAUTION: if the format of UNIX permissions changes, IsUNIXLink() must be updated as well - if (rights != NULL && strlen(rights) == 10) // must be ten characters, otherwise it cannot be UNIX permissions (permissions with ACL have eleven characters, e.g. "drwxrwxr-x+", and we cannot modify them, so we pretend we do not know them) + if (rights != NULL && strlen(rights) == 10) // it must be ten characters, otherwise it cannot be UNIX permissions (permissions with ACL have eleven characters, e.g. "drwxrwxr-x+", but we cannot modify them, so we pretend they are unknown) { BOOL ok = TRUE; *actAttr = 0; @@ -1494,7 +1494,7 @@ BOOL IsUNIXLink(const char* rights) // CAUTION: if the format of UNIX permissions changes, GetAttrsFromUNIXRights() must be updated as well int len = (rights != NULL ? (int)strlen(rights) : 0); - return ((len == 10 || len == 11 && rights[10] == '+') && // must be ten characters, otherwise it cannot be UNIX permissions; exception: with ACL it is eleven characters, e.g. "drwxrwxr-x+" + return ((len == 10 || len == 11 && rights[10] == '+') && // it must be ten characters, otherwise it cannot be UNIX permissions; exception: with ACL it has eleven characters, e.g. "drwxrwxr-x+" rights[0] == 'l' && (rights[1] == 'r' || rights[1] == '-') && (rights[2] == 'w' || rights[2] == '-') && @@ -1544,7 +1544,7 @@ BOOL FTPReadFTPReply(char* readBytes, int readBytesCount, int readBytesOffset, char** reply, int* replySize, int* replyCode) { BOOL ret = FALSE; - if (readBytesOffset < readBytesCount) // if anything is loaded at all + if (readBytesOffset < readBytesCount) // if anything has been read at all { char* s = readBytes + readBytesOffset; char* end = readBytes + readBytesCount; @@ -1752,7 +1752,7 @@ BOOL FTPGetIPAndPortFromReply(const char* reply, int replySize, DWORD* ip, unsig int p1, p2; while (s < end) // looking for a sequence of six numbers separated by ',' and whitespace { - if (*s >= '0' && *s <= '9') // hope for the start of the sequence + if (*s >= '0' && *s <= '9') // possible start of the sequence { int i; for (i = 0; i < 6; i++) @@ -1790,7 +1790,7 @@ BOOL FTPGetIPAndPortFromReply(const char* reply, int replySize, DWORD* ip, unsig } } else - break; // number too large, cannot be the requested sextet + break; // number too large, cannot be the searched-for sextet if (i == 5) // end of search, success { @@ -2204,7 +2204,7 @@ BOOL FTPRemovePointsFromPath(char* path, CFTPServerPathType pathType) case ftpsptWindows: case ftpsptOS2: { - char backslashSep = backslash ? '\\' : '/'; // backslash==FALSE -> every check will test '/' twice (instead of both slash and backslash) + char backslashSep = backslash ? '\\' : '/'; // backslash==FALSE -> every check will test '/' twice (instead of testing both '/' and '\\') char* afterRoot = path + (*path == '/' || *path == backslashSep ? 1 : 0); if (pathType == ftpsptOS2 && afterRoot == path && *path != 0 && *(path + 1) == ':') afterRoot = path + 2 + (*(path + 2) == '/' || *(path + 2) == backslashSep ? 1 : 0); @@ -2420,7 +2420,7 @@ BOOL FTPMayBeValidNameComponent(const char* name, const char* path, BOOL isDir, default: { TRACE_E("FTPIsValidName(): unexpected path type!"); - return TRUE; // we do not know what path that is, so assume OK (if it is not, the server will report it later; at worst it creates more subdirectories, tough luck) + return TRUE; // we do not know what type of path this is, so assume OK (if it is not OK, the server will report it later; at worst it creates more subdirectories, etc.) } } } @@ -2557,10 +2557,10 @@ void FTPGenerateNewName(int* phase, char* newName, int* index, const char* origi case ftpsptWindows: case ftpsptOS2: *phase = 1; - // the break is not missing here! + // the break is intentionally omitted here case ftpsptUnix: { - if (*phase == 0) // at this stage we assume a classic UNIX (names max 255 characters, do not contain '/' or '\0') + if (*phase == 0) // at this stage we assume classic UNIX (names max 255 characters, do not contain '/' or '\0') { const char* s = originalName; char* n = newName; @@ -2620,7 +2620,7 @@ void FTPGenerateNewName(int* phase, char* newName, int* index, const char* origi if (255 - (n - newName) < suffixLen) { int cut = (int)(suffixLen - (255 - (n - newName))); - if (dot != NULL && dot - newName > cut) // shortening in the name + if (dot != NULL && dot - newName > cut) // shorten the name { memmove(dot - cut, dot, (n - dot) + 1); dot -= cut; @@ -2659,7 +2659,7 @@ void FTPGenerateNewName(int* phase, char* newName, int* index, const char* origi if (*index != 0) // append " (number)" after the name { char* n = newName + strlen(newName); - char* dot = isDir ? NULL : strrchr(newName + 1, '.'); // files only: the first period from the right that is not at the beginning of the name; NOTE: exception, because phase==0 means that we are not dealing with Windows: ".cvspass" on UNIX is not an extension + char* dot = isDir ? NULL : strrchr(newName + 1, '.'); // files only: the first period from the right that is not at the beginning of the name; NOTE: exception, because phase==0 means this is not Windows: ".cvspass" on UNIX is not an extension if (alreadyRenamedFile) // ensure "name (2)"->"name (3)" instead of ->"name (2) (2)" { char* s = dot == NULL ? n : dot; @@ -2693,7 +2693,7 @@ void FTPGenerateNewName(int* phase, char* newName, int* index, const char* origi if (MAX_PATH - 4 - (n - newName) < suffixLen) { int cut = (int)(suffixLen - (MAX_PATH - 4 - (n - newName))); - if (dot != NULL && dot - newName > cut) // shortening in the name + if (dot != NULL && dot - newName > cut) // shorten the name { memmove(dot - cut, dot, (n - dot) + 1); dot -= cut; @@ -2821,7 +2821,7 @@ void FTPGenerateNewName(int* phase, char* newName, int* index, const char* origi if (MAX_PATH - 4 - (n - newName) < suffixLen) { int cut = (int)(suffixLen - (MAX_PATH - 4 - (n - newName))); - if (dot != NULL && dot - newName > cut) // shortening in the name + if (dot != NULL && dot - newName > cut) // shorten the name { memmove(dot - cut, dot, (n - dot) + 1); dot -= cut; @@ -2985,8 +2985,8 @@ void FTPGenerateNewName(int* phase, char* newName, int* index, const char* origi } } } - if (*index == 0 && *s == 0 && !changed) // newName is identical to originalName, we must adjust newName - *index = 1; // also handles the reserved name "." (by the way: ".." -> "__" or "_.") + if (*index == 0 && *s == 0 && !changed) // newName is identical to originalName, so newName must be adjusted + *index = 1; // also handles the reserved name "." (note: ".." -> "__" or "_.") if (*index != 0) // append "_number" after the name { if (alreadyRenamedFile) // ensure "name_2"->"name_3" instead of ->"name_2_2" @@ -3053,7 +3053,7 @@ void FTPGenerateNewName(int* phase, char* newName, int* index, const char* origi break; } - case ftpsptAS400: // AS/400: we do not know anything about the naming format on AS/400 yet; for now we reuse the following Tandem code, it seems restrictive enough that AS/400 should be satisfied with it as well + case ftpsptAS400: // AS/400: we do not know anything about the AS/400 name format yet; for now we reuse the following Tandem code, which seems restrictive enough for AS/400 as well case ftpsptTandem: { // full path to a file: \\SYSTEM.$VVVVV.SUBVOLUM.FILENAME @@ -3094,7 +3094,7 @@ void FTPGenerateNewName(int* phase, char* newName, int* index, const char* origi } } *n = 0; - if (*index == 0 && *s == 0 && !change) // newName is identical to originalName, we must adjust newName + if (*index == 0 && *s == 0 && !change) // newName is identical to originalName, so newName must be adjusted *index = 1; if (*index != 0) // append "number" after the name { @@ -3230,7 +3230,7 @@ void FTPGenerateNewName(int* phase, char* newName, int* index, const char* origi if (MAX_PATH - 4 - (n - newName) < suffixLen) { int cut = (int)(suffixLen - (MAX_PATH - 4 - (n - newName))); - if (dot != NULL && dot - newName > cut) // shortening in the name + if (dot != NULL && dot - newName > cut) // shortening the name { memmove(dot - cut, dot, (n - dot) + 1); dot -= cut; diff --git a/src/plugins/ftp/ftputils.h b/src/plugins/ftp/ftputils.h index 95f680bc9..6480d8735 100644 --- a/src/plugins/ftp/ftputils.h +++ b/src/plugins/ftp/ftputils.h @@ -25,13 +25,13 @@ enum CFTPServerPathType // determines the path type on an FTP server; if 'serverFirstReply' is not NULL, it is the first // reply from the server (often containing the server version); if 'serverSystem' is not NULL, it -// is the FTP server response to the SYST command (our ftpcmdSystem); 'path' is the path on the FTP +// is the FTP server response to the SYST command (our ftpcmdSystem); 'path' is the path on the FTP server; returns the path type CFTPServerPathType GetFTPServerPathType(const char* serverFirstReply, const char* serverSystem, const char* path); // parses the system name from the server response to the SYST command stored in 'serverSystem' -// and stores it into 'sysName' (a buffer of at least 201 characters); if it is not possible to -// obtain the system name from this response, returns an empty string +// and stores it into 'sysName' (a buffer of at least 201 characters); if the system name cannot be +// obtained from this response, stores an empty string void FTPGetServerSystem(const char* serverSystem, char* sysName); // shortens the FTP server path by the last directory/file (directory separators depend on the @@ -45,11 +45,11 @@ void FTPGetServerSystem(const char* serverSystem, char* sysName); BOOL FTPCutDirectory(CFTPServerPathType type, char* path, int pathBufSize, char* cutDir, int cutDirBufSize, BOOL* fileNameCouldBeCut); -// concatenates the path 'path' and 'name' (file/directory name - 'isDir' is FALSE/TRUE) into -// 'path', performing the concatenation according to the path type - 'type'; 'path' is a buffer of -// at least 'pathSize' characters; returns TRUE if 'name' fits into 'path'; if 'path' or 'name' is -// empty, no concatenation occurs (the 'path' path may be adjusted - truncated to the minimal length - e.g. -// "/pub/" + "" = "/pub") +// concatenates 'path' and 'name' (file/directory name - 'isDir' is FALSE/TRUE) into 'path', +// performing the concatenation according to the path type - 'type'; 'path' is a buffer of at +// least 'pathSize' characters; returns TRUE if 'name' fits into 'path'; if 'path' or 'name' is +// empty, no concatenation is performed (the path in 'path' may still be adjusted - truncated to +// the minimal length - e.g. "/pub/" + "" = "/pub") BOOL FTPPathAppend(CFTPServerPathType type, char* path, int pathSize, const char* name, BOOL isDir); // determines whether the FTP server path (not a user-part path) 'path' is valid and whether it is @@ -57,7 +57,7 @@ BOOL FTPPathAppend(CFTPServerPathType type, char* path, int pathSize, const char // and is not a root path BOOL FTPIsValidAndNotRootPath(CFTPServerPathType type, const char* path); -// converts escape sequences (e.g. "%20" = " ") in the string 'txt' to ASCII characters +// converts hex escape sequences (e.g. "%20" = " ") in the string 'txt' to ASCII characters void FTPConvertHexEscapeSequences(char* txt); // prepares the text 'txt' so that it survives the subsequent conversion of escape sequences to // ASCII characters (e.g. "%20" = "%2520"); 'txtSize' is the size of the 'txt' buffer; returns @@ -65,11 +65,11 @@ void FTPConvertHexEscapeSequences(char* txt); BOOL FTPAddHexEscapeSequences(char* txt, int txtSize); // splits the user-part path into individual components (user name, host, port, and path (without -// '/' or '\\' at the beginning)); inserts zero terminators into the path string 'p' so each +// '/' or '\\' at the beginning)); inserts null terminators into the path string 'p' so each // component becomes a null-terminated string; if 'firstCharOfPath' is not NULL and the FTP path -// contains a path within the server ('path' string), 'firstCharOfPath' receives the separator of this -// path ('/' or '\\'); it does not need to return all components ('user', 'host', 'port', and 'path' -// can be NULL); if a particular component cannot be obtained (the path might not contain it), the +// contains a server path ('path' string), 'firstCharOfPath' receives the separator of that path +// ('/' or '\\'); it does not need to return all components ('user', 'host', 'port', and 'path' can +// be NULL); if a particular component cannot be obtained (the path might not contain it), the // corresponding variable receives NULL; 'user', 'host', and 'port' are returned trimmed of // whitespace on both sides; 'userLength' is zero if we do not know how long the user name is or if it // does not contain "forbidden" characters, otherwise it is the expected length of the user name; @@ -80,7 +80,7 @@ void FTPSplitPath(char* p, char** user, char** password, char** host, char** por // returns the length of the username for use in the "userLength" parameters (FTPSplitPath, // FTPFindPath, etc.); for an anonymous user and other usernames without special characters -// ('@', '/', '\', ':') returns zero; 'user' can also be NULL +// ('@', '/', '\\', ':') returns zero; 'user' can also be NULL int FTPGetUserLength(const char* user); // returns a pointer to the remote path in an FTP path (a pointer into the 'path' buffer); 'path' @@ -103,7 +103,8 @@ BOOL FTPIsTheSameServerPath(CFTPServerPathType type, const char* p1, const char* // determines whether 'prefix' is a prefix of 'path' - both paths are on the FTP server (not // user-part paths), returns TRUE if it is a prefix; 'type' is the type of at least one of the -// paths; if 'mustBeSame' is TRUE, 'prefix' and 'path' must match (same function as +// paths; if 'mustBeSame' is TRUE, 'prefix' and 'path' must match, which is equivalent to +// FTPIsTheSameServerPath() BOOL FTPIsPrefixOfServerPath(CFTPServerPathType type, const char* prefix, const char* path, BOOL mustBeSame = FALSE); @@ -126,18 +127,18 @@ char* FTPGetErrorText(int err, char* buf, int bufSize); // returns, based on the path type, the character used to separate path components (subdirectories) char FTPGetPathDelimiter(CFTPServerPathType pathType); -// only for the ftpsptIBMz_VM path type: obtains the root path from the path 'path'; -// 'root'+'rootSize' is the buffer for the result; returns success +// only for the ftpsptIBMz_VM path type: obtains the root path from 'path'; +// 'root'+'rootSize' is the output buffer; returns success BOOL FTPGetIBMz_VMRootPath(char* root, int rootSize, const char* path); -// only for the ftpsptOS2 path type: obtains the root path from the path 'path'; -// 'root'+'rootSize' is the buffer for the result; returns success +// only for the ftpsptOS2 path type: obtains the root path from 'path'; +// 'root'+'rootSize' is the output buffer; returns success BOOL FTPGetOS2RootPath(char* root, int rootSize, const char* path); -// obtains the numeric value from the UNIX rights string 'rights'; returns the value in actAttr -// (must not be NULL); if it finds permissions that cannot be set via "site chmod" ('s', 't', etc.), -// it ORs the respective bits into 'attrDiff' (must not be NULL); if the rights are UNIX rights, it -// returns TRUE, otherwise it returns FALSE (unknown rights string or e.g. ACL rights on UNIX (such +// obtains the numeric value from the UNIX rights string 'rights'; returns the value in 'actAttr' +// (must not be NULL); if it finds rights that cannot be set using "site chmod" ('s', 't', etc.), +// it ORs the corresponding bits into 'attrDiff' (must not be NULL); returns TRUE for UNIX rights +// and FALSE otherwise (unknown rights string or e.g. UNIX ACL rights, such as "drwxrwxr-x+") BOOL GetAttrsFromUNIXRights(DWORD* actAttr, DWORD* attrDiff, const char* rights); // converts 'attrs' (numeric rights on UNIX) to a UNIX rights string (without the first letter) @@ -153,30 +154,30 @@ BOOL IsUNIXLink(const char* rights); // NOTE: 'bufSize' must be greater than 2 void FTPGetErrorTextForLog(DWORD err, char* errBuf, int bufSize); -// method for detecting whether the buffer 'readBytes' (with 'readBytesCount' valid bytes, reading -// from position 'readBytesOffset') already contains the entire response from the FTP server; -// returns TRUE on success - 'reply' (must not be NULL) receives a pointer to the beginning of the -// response, 'replySize' (must not be NULL) receives the length of the response, 'replyCode' -// (if not NULL) receives the FTP response code or -1 if the response has no code (does not start +// detects whether the buffer 'readBytes' (with 'readBytesCount' valid bytes, starting at +// position 'readBytesOffset') already contains the complete response from the FTP server; +// returns TRUE on success: 'reply' (must not be NULL) receives a pointer to the start of the +// response, 'replySize' (must not be NULL) receives the response length, and 'replyCode' +// (if not NULL) receives the FTP reply code or -1 if the response has no code (does not start // with a three-digit number); if the response is not complete yet, returns FALSE BOOL FTPReadFTPReply(char* readBytes, int readBytesCount, int readBytesOffset, char** reply, int* replySize, int* replyCode); -// parses the directory from the string 'reply' (rules see RFC 959 - FTP response number "257"); -// does not strictly require "257" at the beginning of the string (handle if necessary before -// calling); returns TRUE if the directory was obtained successfully +// parses the directory from the string 'reply' (for the rules, see RFC 959, FTP reply code "257"); +// does not strictly require "257" at the beginning of the string (if necessary, handle this before calling); +// returns TRUE if the directory was parsed successfully // can be called from any thread BOOL FTPGetDirectoryFromReply(const char* reply, int replySize, char* dirBuf, int dirBufSize); -// parses IP+port from the string 'reply' of length 'replySize' (-1 == use 'strlen(reply)') (returns -// it in 'ip'+'port' (must not be NULL); rules see RFC 959 - FTP response number 227); -// does not strictly require "227" at the beginning of the string (handle if necessary before -// calling); returns TRUE if obtaining IP+port succeeded +// parses the IP address and port from the string 'reply' of length 'replySize' (-1 == use 'strlen(reply)') +// (returns them in 'ip' and 'port' (must not be NULL); for the rules, see RFC 959, FTP reply code 227); +// does not strictly require "227" at the beginning of the string (if necessary, handle this before calling); +// returns TRUE if the IP address and port were parsed successfully // can be called from any thread BOOL FTPGetIPAndPortFromReply(const char* reply, int replySize, DWORD* ip, unsigned short* port); -// parses the data size from the string 'reply' of length 'replySize' and returns it in 'size'; -// on success returns TRUE, otherwise FALSE and 'size' is set arbitrarily +// parses the data size from the string 'reply' of length 'replySize' and stores it in 'size'; +// returns TRUE on success; otherwise returns FALSE and 'size' is set to an arbitrary value BOOL FTPGetDataSizeInfoFromSrvReply(CQuadWord& size, const char* reply, int replySize); // creates a VMS directory name (adds ".DIR;1") @@ -184,7 +185,8 @@ void FTPMakeVMSDirName(char* vmsDirNameBuf, int vmsDirNameBufSize, const char* d // checks whether there is an escape sequence before the character 'checkedChar' in the path // 'pathBeginning' (e.g. "^." is '.', which VMS does not consider a path or extension separator, -// etc.); returns TRUE if there is an escape sequence before the character (meaning the character +// etc.); returns TRUE if there is an escape sequence before the character (i.e. the character has +// no special meaning) BOOL FTPIsVMSEscapeSequence(const char* pathBeginning, const char* checkedChar); // returns TRUE if the path 'path' of type 'type' ends with a path component delimiter @@ -192,9 +194,9 @@ BOOL FTPIsVMSEscapeSequence(const char* pathBeginning, const char* checkedChar); BOOL FTPPathEndsWithDelimiter(CFTPServerPathType type, const char* path); // shortens an IBM z/VM path on the FTP server by the last two components; 'path' is an in/out -// buffer (min. size 'pathBufSize' bytes), 'cutDir' (a buffer of at least -// 'cutDirBufSize') returns the last two components (the removed part; if the string -// does not fit into the buffer, it is truncated); returns TRUE if shortening occurred +// buffer (minimum size 'pathBufSize' bytes), and 'cutDir' (a buffer of at least +// 'cutDirBufSize' bytes) receives the last two components (the removed part; if the string +// does not fit into the buffer, it is truncated); returns TRUE if the path was shortened BOOL FTPIBMz_VmCutTwoDirectories(char* path, int pathBufSize, char* cutDir, int cutDirBufSize); // trims the file version number from an OpenVMS file name (e.g. "a.txt;1" -> "a.txt"); @@ -219,7 +221,7 @@ BOOL FTPCutFirstDirFromRelativePath(CFTPServerPathType pathType, char* path, // completes an absolute path to a full absolute path (for VMS the volume is added - e.g. // "PUB$DEVICE:", for OS/2 the drive - e.g. "C:"); 'pathType' is the path type; 'path' is an -// absolute path; 'path' (a buffer of at least 'pathBufSize' characters) returns the full +// absolute path; 'path' (a buffer of at least 'pathBufSize' characters) receives the full // absolute path (lack of space = truncated result); 'workPath' is the working // full absolute path (from which the volume/drive is taken); returns success (even if // 'path' is already a full absolute path on input - meaning there is nothing to do) @@ -235,21 +237,22 @@ BOOL FTPRemovePointsFromPath(char* path, CFTPServerPathType pathType); // otherwise it is case-insensitive (windows) BOOL FTPIsCaseSensitive(CFTPServerPathType pathType); -// returns TRUE if this is an error response to the LIST command that only says the directory is -// empty (so it is not actually an error - unfortunately VMS and Z/VM still report such errors) +// returns TRUE if this is an error response to the LIST command that only indicates the directory +// is empty (that is, it is not actually an error; unfortunately VMS and Z/VM report such +// non-errors this way) BOOL FTPIsEmptyDirListErrReply(const char* listErrReply); // returns TRUE if the name 'name' can be the name of a single file/directory ('isDir' is // FALSE/TRUE) on the path 'path' of type 'pathType'; used only to prevent creating multiple -// subdirectories instead of just one (e.g. "a.b.c" on VMS creates three subdirectories) -// the server reports the syntax error in the name +// subdirectories instead of just one (e.g. "a.b.c" on VMS creates three subdirectories); +// any syntax error in the name is reported only by the server BOOL FTPMayBeValidNameComponent(const char* name, const char* path, BOOL isDir, CFTPServerPathType pathType); // for uploading to the server: adds the *.* or * mask to the target path (for later processing of // the operation mask); 'pathType' is the path type; 'targetPath' is a buffer (of size // 'targetPathBufSize') containing the target path on input (full, including fs-name) -// and on output enriched with the mask; 'noFilesSelected' is TRUE if no files should be uploaded +// and the same path with the mask appended on output; 'noFilesSelected' is TRUE if no files should be uploaded // (only directories are selected in the panel) void FTPAddOperationMask(CFTPServerPathType pathType, char* targetPath, int targetPathBufSize, BOOL noFilesSelected); diff --git a/src/plugins/ftp/help/hh/salamander_help_shared.css b/src/plugins/ftp/help/hh/salamander_help_shared.css index a0f833192..f259c75cd 100644 --- a/src/plugins/ftp/help/hh/salamander_help_shared.css +++ b/src/plugins/ftp/help/hh/salamander_help_shared.css @@ -1,3 +1,4 @@ +/* CommentsTranslationProject: TRANSLATED */ /* Cascading Style Sheet for Open Salamander Help */ /* Shared part used for both CHM and WEB */ @@ -206,14 +207,14 @@ #help_page td.hdr { - /* tmavsi seda na leve strane */ + /* darker gray on the left side */ margin: .25em; background: #dddddd; vertical-align: top; padding: 2px 4px; font-weight: bold; - width: 10%; /* zuzime levou stranu tabulky na minimum */ - padding-right :10px; /* ale nechame tam alespon 10 bodu, at to trochu vypada */ + width: 10%; /* narrow the left side of the table to the minimum */ + padding-right :10px; /* but keep at least 10 points there so it still looks decent */ white-space: nowrap; } @@ -322,4 +323,3 @@ padding-left: 4px; text-align: left; } - diff --git a/src/plugins/ftp/menu.cpp b/src/plugins/ftp/menu.cpp index 48ec82f5c..cfdd77f64 100644 --- a/src/plugins/ftp/menu.cpp +++ b/src/plugins/ftp/menu.cpp @@ -22,7 +22,7 @@ CPluginInterfaceForMenuExt::GetMenuItemState(int id, DWORD eventMask) case FTPCMD_TRMODEBINARY: { CPluginFSInterfaceAbstract* fs = SalamanderGeneral->GetPanelPluginFS(PANEL_SOURCE); - if (fs != NULL) // it is our FS; otherwise it would be NULL + if (fs != NULL) // our FS; otherwise it would be NULL { return ((CPluginFSInterface*)fs)->GetTransferModeCmdState(id); } diff --git a/src/plugins/ftp/operats.h b/src/plugins/ftp/operats.h index b25445da8..7ca6a41ae 100644 --- a/src/plugins/ftp/operats.h +++ b/src/plugins/ftp/operats.h @@ -4,12 +4,12 @@ #pragma once -#pragma pack(push, enter_include_operats_h_dt) // so that all structures are as small as possible (speed is not needed, we mainly save space) +#pragma pack(push, enter_include_operats_h_dt) // to keep all structures as small as possible (speed is not important; the main goal is to save space) #pragma pack(1) -// returns a pointer to the textual description of the 'error'; if 'error' is NO_ERROR, returns -// a text like "unknown, maybe insufficient system resources", otherwise returns the standard -// Windows description of the error (it uses the buffer 'errBuf'+'errBufSize' to store it) +// returns a pointer to the text description of 'error'; if 'error' is NO_ERROR, returns +// a string such as "unknown, maybe insufficient system resources"; otherwise returns the standard +// Windows error description (using 'errBuf' and 'errBufSize' to store it) const char* GetWorkerErrorTxt(int error, char* errBuf, int errBufSize); // @@ -22,7 +22,7 @@ enum CFTPQueueItemType { fqitNone, // empty item (must be set to one of the following types) - fqitDeleteExploreDir, // explore directory for delete (note: we delete links to directories as a whole, the goal of the operation is fulfilled and nothing "extra" gets deleted) (object of class CFTPQueueItemDelExplore) + fqitDeleteExploreDir, // directory exploration for a delete operation (note: links to directories are deleted as a whole; the purpose of the operation is fulfilled and nothing "extra" is deleted) (object of class CFTPQueueItemDelExplore) fqitCopyResolveLink, // download: copy: find out whether it is a link to a file or a directory (object of class CFTPQueueItemCopyOrMove) fqitMoveResolveLink, // download: move: find out whether it is a link to a file or a directory (object of class CFTPQueueItemCopyOrMove) fqitCopyExploreDir, // download: explore a directory or a link to a directory for copying (object of class CFTPQueueItemCopyMoveExplore) @@ -36,15 +36,15 @@ enum CFTPQueueItemType fqitLastResolveOrExploreItem, // numeric constant only for distinguishing types (processing priority) of items - fqitDeleteLink, // delete for a link (object of class CFTPQueueItemDel) - fqitDeleteFile, // delete for a file (object of class CFTPQueueItemDel) - fqitDeleteDir, // delete for a directory (object of class CFTPQueueItemDir) + fqitDeleteLink, // delete operation for a link (object of class CFTPQueueItemDel) + fqitDeleteFile, // delete operation for a file (object of class CFTPQueueItemDel) + fqitDeleteDir, // delete operation for a directory (object of class CFTPQueueItemDir) fqitCopyFileOrFileLink, // download: copying a file or a link to a file (object of class CFTPQueueItemCopyOrMove) fqitMoveFileOrFileLink, // download: moving a file or a link to a file (object of class CFTPQueueItemCopyOrMove) fqitMoveDeleteDir, // download: delete a directory after moving its contents (object of class CFTPQueueItemDir) fqitMoveDeleteDirLink, // download: delete a link to a directory after moving its contents (object of class CFTPQueueItemDir) fqitChAttrsFile, // change file attributes (note: attributes cannot be changed on links) (object of class CFTPQueueItemChAttr) - fqitChAttrsDir, // change directory attributes (object of class CFTPQueueItemChAttrDir) + fqitChAttrsDir, // change directory attributes (object of type CFTPQueueItemChAttrDir) fqitUploadCopyFile, // upload: copy a file (object of class CFTPQueueItemCopyOrMoveUpload) fqitUploadMoveFile, // upload: move a file (object of class CFTPQueueItemCopyOrMoveUpload) fqitUploadMoveDeleteDir, // upload: delete a directory after moving its contents (object of class CFTPQueueItemDir) @@ -95,23 +95,23 @@ enum CFTPQueueItemState #define ITEMPR_UNABLETODELETEDIR 23 // issue "unable to delete the directory, server response: %s" (uses ErrAllocDescr to store the server response - it may span multiple lines) #define ITEMPR_UNABLETOCHATTRS 24 // issue "unable to change file/directory attributes, server response: %s" (uses ErrAllocDescr to store the server response - it may span multiple lines) #define ITEMPR_UNABLETORESUME 25 // issue "unable to resume file transfer" -#define ITEMPR_RESUMETESTFAILED 26 // issue "unable to resume file transfer, unexpected tail of file (file has changed)" +#define ITEMPR_RESUMETESTFAILED 26 // problem: "unable to resume file transfer, unexpected tail of file (file has changed)" #define ITEMPR_TGTFILEREADERROR 27 // issue "error reading the target file" (uses WinError) #define ITEMPR_TGTFILEWRITEERROR 28 // issue "error writing the target file" (uses WinError) #define ITEMPR_INCOMPLETEDOWNLOAD 29 // issue "unable to retrieve file from server: %s" (uses WinError and ErrAllocDescr) #define ITEMPR_UNABLETODELSRCFILE 30 // issue "Move: unable to delete the source file, server response: %s" (uses ErrAllocDescr to store the server response - it may span multiple lines) -#define ITEMPR_UPLOADCANNOTCREATETGTDIR 31 // upload: issue "the target directory cannot be created" (if FTPMayBeValidNameComponent() returns FALSE, ErrAllocDescr==NULL and WinError==NO_ERROR; if a file/link is in the way, WinError==ERROR_ALREADY_EXISTS; otherwise it uses ErrAllocDescr to store the server response - it may span multiple lines) +#define ITEMPR_UPLOADCANNOTCREATETGTDIR 31 // upload: issue "the target directory cannot be created" (if FTPMayBeValidNameComponent() returns FALSE, ErrAllocDescr==NULL and WinError==NO_ERROR; if a file/link blocks the path, WinError==ERROR_ALREADY_EXISTS; otherwise it uses ErrAllocDescr to store the server response - it may span multiple lines) #define ITEMPR_UPLOADCANNOTLISTTGTPATH 32 // upload: issue "unable to list the target path" (unable to detect possible name collisions) (uses WinError and ErrAllocDescr) #define ITEMPR_UPLOADTGTDIRALREADYEXISTS 33 // upload: issue "the target directory or a link to the directory already exists" #define ITEMPR_UPLOADCRDIRAUTORENFAILED 34 // upload: issue "unable to create the target directory under any name" (uses ErrAllocDescr to store the server response - it may span multiple lines) #define ITEMPR_UPLOADCANNOTLISTSRCPATH 35 // upload: issue "unable to list the source path" (uses WinError) #define ITEMPR_UNABLETOCWDONLYPATH 36 // issue "error while changing the working directory on the server, server response: %s" - change of the path to Path or TgtPath (uses ErrAllocDescr to store the server response - it may span multiple lines) -#define ITEMPR_UNABLETODELETEDISKDIR 37 // issue "unable to delete directory on disk, error:" (uses WinError) +#define ITEMPR_UNABLETODELETEDISKDIR 37 // error "unable to delete directory on disk, error:" (uses WinError) #define ITEMPR_UPLOADCANNOTCREATETGTFILE 38 // upload: issue "the target file cannot be created or opened" (if FTPMayBeValidNameComponent() returns FALSE, ErrAllocDescr==NULL and WinError==NO_ERROR; if a directory/link is in the way, WinError==ERROR_ALREADY_EXISTS; otherwise it uses ErrAllocDescr to store the server response - it may span multiple lines) #define ITEMPR_UPLOADCANNOTOPENSRCFILE 39 // issue "the source file cannot be opened" (uses WinError) #define ITEMPR_UPLOADTGTFILEALREADYEXISTS 40 // upload: issue "the target file or a link to the file already exists" #define ITEMPR_SRCFILEINUSE 41 // issue "the source file or link is locked by another operation" -#define ITEMPR_TGTFILEINUSE 42 // issue "the target file or link is locked by another operation" +#define ITEMPR_TGTFILEINUSE 42 // problem "the target file or link is locked by another operation" #define ITEMPR_SRCFILEREADERROR 43 // issue "error reading the source file" (uses WinError) #define ITEMPR_INCOMPLETEUPLOAD 44 // issue "unable to store file to server: %s" (uses WinError and ErrAllocDescr) #define ITEMPR_UNABLETODELETEDISKFILE 45 // issue "unable to delete file on disk, error:" (uses WinError) @@ -120,7 +120,7 @@ enum CFTPQueueItemState #define ITEMPR_UPLOADUNABLETORESUMEBIGTGT 48 // issue "unable to resume the file because the target file is larger than the source file" #define ITEMPR_UPLOADFILEAUTORENFAILED 49 // upload: issue "unable to create the target file under any name" (uses ErrAllocDescr to store the server response - it may span multiple lines) #define ITEMPR_SKIPPEDBYUSER 50 // after pressing the Skip button on a waiting item in the operation dialog -#define ITEMPR_UPLOADTESTIFFINISHEDNOTSUP 51 // issue "unable to verify whether the file uploaded successfully" (we sent the entire file + the server "just" did not respond, most likely the file is OK, but we are unable to test it - reasons: ASCII transfer mode or we do not have the size in bytes (neither listing nor the SIZE command)) +#define ITEMPR_UPLOADTESTIFFINISHEDNOTSUP 51 // issue "unable to verify whether the file was uploaded successfully" (the entire file was sent, but the server did not respond; the file is most likely OK, but this cannot be verified - reasons: ASCII transfer mode or the size in bytes is unavailable (neither from a listing nor from the SIZE command)) enum CFTPQueueItemAction { @@ -133,7 +133,7 @@ enum CFTPQueueItemAction fqiaReduceFileSizeAndResume, // the existing file should be truncated and then resumed fqiaUploadForceAutorename, // upload: autorename (use alternate name) should be used no matter what fqiaUploadContinueAutorename, // upload: continuation of autorename (use alternate name) - fqiaUploadTestIfFinished, // upload: we sent the entire file + the server "just" did not respond, most likely the file is OK, we will test it + fqiaUploadTestIfFinished, // upload: the entire file was sent, but the server did not respond; the file is probably OK, so this will be tested }; class CFTPQueueItemAncestor @@ -164,7 +164,7 @@ class CFTPQueueItem : public CFTPQueueItemAncestor // - if it is already in the queue: access only from the queue critical section static CRITICAL_SECTION NextItemUIDCritSect; // critical section for accessing NextItemUID - static int NextItemUID; // global counter for item UIDs (access only inside the NextItemUIDCritSect section!) + static int NextItemUID; // global counter for item UIDs (access only inside the NextItemUIDCritSect critical section!) int UID; // unique item number int ParentUID; // UID of the parent item (-1 = the parent is the operation) @@ -176,7 +176,7 @@ class CFTPQueueItem : public CFTPQueueItemAncestor DWORD ErrorOccurenceTime; // "time" when the error occurred (used to keep the order of error resolution according to their occurrence); -1 = no error occurred - CFTPQueueItemAction ForceAction; // action forced by the user (for example an autorename entered from the Solve Error dialog) + CFTPQueueItemAction ForceAction; // action forced by the user (for example an autorename specified in the Solve Error dialog) char* Path; // path to the processed file/directory (local path on the server or a Windows path) char* Name; // name of the processed file/directory (name without the path) @@ -204,9 +204,9 @@ class CFTPQueueItem : public CFTPQueueItemAncestor void SetItem(int parentUID, CFTPQueueItemType type, CFTPQueueItemState state, DWORD problemID, const char* path, const char* name); - // enabler for buttons in the operation dialog: returns TRUE if the "Solve Error" button makes sense; - // in 'canSkip' (if not NULL) it returns TRUE if the "Skip" button makes sense; - // in 'canRetry' (if not NULL) it returns TRUE if the "Retry" button makes sense + // button enable states in the operation dialog: returns TRUE if the "Solve Error" button should be enabled; + // in 'canSkip' (if not NULL), returns TRUE if the "Skip" button should be enabled; + // in 'canRetry' (if not NULL), returns TRUE if the "Retry" button should be enabled // CAUTION: call only from the queue critical section BOOL HasErrorToSolve(BOOL* canSkip, BOOL* canRetry); @@ -437,7 +437,7 @@ class CFTPQueueItemChAttr : public CFTPQueueItem public: WORD Attr; // requested mode (conversion to a string in octal digits is necessary) BYTE AttrErr; // TRUE = an unknown attribute should be preserved, which we cannot do (FALSE = everything OK) - char* OrigRights; // original file permissions (!=NULL only if they contain unknown permissions + if a permissions column was found at all) + char* OrigRights; // original file permissions (!=NULL only if they contain unknown permissions and a permissions column was found at all) public: CFTPQueueItemChAttr(); @@ -461,7 +461,7 @@ class CFTPQueueItemChAttrDir : public CFTPQueueItemDir public: WORD Attr; // requested mode (conversion to a string in octal digits is necessary) BYTE AttrErr; // TRUE = an unknown attribute should be preserved, which we cannot do (FALSE = everything OK) - char* OrigRights; // original directory permissions (!=NULL only if they contain unknown permissions + if a permissions column was found at all) + char* OrigRights; // original directory permissions (!=NULL only if they contain unknown permissions and a permissions column was found) public: CFTPQueueItemChAttrDir(); @@ -483,7 +483,7 @@ class CFTPQueueItemChAttrDir : public CFTPQueueItemDir class CFTPQueueItemChAttrExplore : public CFTPQueueItem { public: - char* OrigRights; // original directory permissions for computing Attr of the explored directory (!=NULL if a permissions column was found) + char* OrigRights; // original directory permissions for computing Attr of the directory being explored (!=NULL if a permissions column was found) public: CFTPQueueItemChAttrExplore(); @@ -514,7 +514,7 @@ class CFTPQueue int LastFoundUID; // UID of the last found item int LastFoundIndex; // index of the last found item (always a non-negative number, even after initialization) - int FirstWaitingItemIndex; // first item in the queue (array Items) that can (but does not have to) be in state sqisWaiting and if GetOnlyExploreAndResolveItems==TRUE it can also be an "explore" or "resolve" item (there simply are none before this index) + int FirstWaitingItemIndex; // first item in the queue (Items array) that may, but does not have to, be in state sqisWaiting; if GetOnlyExploreAndResolveItems==TRUE, it may also be an "explore" or "resolve" item (there are simply no such items before this index) BOOL GetOnlyExploreAndResolveItems; // TRUE = for now we return only "explore" and "resolve" items from the queue (FALSE only when no such item is in the "waiting" state) (Type < fqitLastResolveOrExploreItem) int ExploreAndResolveItemsCount; // number of queue items of type "explore" and "resolve" (Type < fqitLastResolveOrExploreItem) @@ -574,10 +574,10 @@ class CFTPQueue // returns the number of items in state sqisUserInputNeeded, sqisSkipped, sqisFailed or sqisForcedToFail // in the queue; if 'onlyUINeeded' is TRUE, fills the array 'UINeededArr' with items in state // sqisUserInputNeeded, sqisSkipped, sqisFailed or sqisForcedToFail; if 'focusedItemUID' is not -1, - // it returns in 'indexInAll' the index of the item with UID 'focusedItemUID' in the queue + - // returns in 'indexInUIN' the index of the item with UID 'focusedItemUID' in the array of items in state - // sqisUserInputNeeded, sqisSkipped, sqisFailed or sqisForcedToFail; if it does not find - // the item with UID 'focusedItemUID', it returns both 'indexInAll' and 'indexInUIN' equal to -1 + // returns in 'indexInAll' the index of the item with UID 'focusedItemUID' in the queue and in + // 'indexInUIN' the index of the item with UID 'focusedItemUID' in the array of items in state + // sqisUserInputNeeded, sqisSkipped, sqisFailed or sqisForcedToFail; if the item with UID + // 'focusedItemUID' is not found, sets both 'indexInAll' and 'indexInUIN' to -1 int GetUserInputNeededCount(BOOL onlyUINeeded, TDirectArray* UINeededArr, int focusedItemUID, int* indexInAll, int* indexInUIN); @@ -593,10 +593,10 @@ class CFTPQueue // valid, it does nothing (the list view refresh is already on the way) void GetListViewDataFor(int index, NMLVDISPINFO* lvdi, char* buf, int bufSize); - // button enabler in the operation dialog for the item at index 'index': - // returns TRUE if "Solve Error" makes sense; returns FALSE for an invalid index; - // in 'canSkip' (if not NULL) it returns TRUE if "Skip" makes sense; - // in 'canRetry' (if not NULL) it returns TRUE if "Retry" makes sense + // determines which buttons should be enabled in the operation dialog for the item at index 'index': + // returns TRUE if "Solve Error" should be enabled; returns FALSE for an invalid index; + // in 'canSkip' (if not NULL) returns TRUE if "Skip" should be enabled; + // in 'canRetry' (if not NULL) returns TRUE if "Retry" should be enabled BOOL IsItemWithErrorToSolve(int index, BOOL* canSkip, BOOL* canRetry); // performs Skip on the item with UID 'UID' (change to state "skipped"); returns the index @@ -660,7 +660,7 @@ class CFTPQueue // assigns 'attrErr' to AttrErr of item 'item' void UpdateAttrErr(CFTPQueueItemChAttrDir* item, BYTE attrErr); - // assigns 'attrErr' to AttrErr of item 'item' + // assigns 'attrErr' to the AttrErr member of 'item' void UpdateAttrErr(CFTPQueueItemChAttr* item, BYTE attrErr); // assigns 'isHiddenDir' to IsHiddenDir of item 'item' @@ -669,7 +669,7 @@ class CFTPQueue // assigns 'isHiddenFile' to IsHiddenFile of item 'item' void UpdateIsHiddenFile(CFTPQueueItemDel* item, BOOL isHiddenFile); - // assigns 'size' to Size and 'sizeInBytes' to SizeInBytes of item 'item' + adjusts + // assigns 'size' to Size and 'sizeInBytes' to SizeInBytes of item 'item' and adjusts // TotalSizeInBytes and TotalSizeInBlocks in the operation ('oper') void UpdateFileSize(CFTPQueueItemCopyOrMove* item, CQuadWord const& size, BOOL sizeInBytes, CFTPOperation* oper); @@ -677,23 +677,23 @@ class CFTPQueue // assigns 'asciiTransferMode' to AsciiTransferMode of item 'item' void UpdateAsciiTransferMode(CFTPQueueItemCopyOrMove* item, BOOL asciiTransferMode); - // assigns 'ignoreAsciiTrModeForBinFile' to IgnoreAsciiTrModeForBinFile of item 'item' + // assigns 'ignoreAsciiTrModeForBinFile' to the IgnoreAsciiTrModeForBinFile member of item 'item' void UpdateIgnoreAsciiTrModeForBinFile(CFTPQueueItemCopyOrMove* item, BOOL ignoreAsciiTrModeForBinFile); - // for upload: assigns 'asciiTransferMode' to AsciiTransferMode of item 'item' + // for upload: assigns 'asciiTransferMode' to the AsciiTransferMode member of item 'item' void UpdateAsciiTransferMode(CFTPQueueItemCopyOrMoveUpload* item, BOOL asciiTransferMode); - // for upload: assigns 'ignoreAsciiTrModeForBinFile' to IgnoreAsciiTrModeForBinFile of item 'item' + // for upload: assigns 'ignoreAsciiTrModeForBinFile' to the IgnoreAsciiTrModeForBinFile member of item 'item' void UpdateIgnoreAsciiTrModeForBinFile(CFTPQueueItemCopyOrMoveUpload* item, BOOL ignoreAsciiTrModeForBinFile); - // assigns 'tgtFileState' to TgtFileState of item 'item' + // assigns 'tgtFileState' to the TgtFileState member of 'item' void UpdateTgtFileState(CFTPQueueItemCopyOrMoveUpload* item, unsigned tgtFileState); - // assigns 'size' to Size of item 'item' + adjusts TotalSizeInBytes in the operation ('oper') + // assigns 'size' to the Size member of item 'item' and adjusts TotalSizeInBytes in operation 'oper' void UpdateFileSize(CFTPQueueItemCopyOrMoveUpload* item, CQuadWord const& size, CFTPOperation* oper); - // sets SizeWithCRLF_EOLs and NumberOfEOLs of item 'item' + // sets the SizeWithCRLF_EOLs and NumberOfEOLs members of item 'item' void UpdateTextFileSizes(CFTPQueueItemCopyOrMoveUpload* item, CQuadWord const& sizeWithCRLF_EOLs, CQuadWord const& numberOfEOLs); @@ -702,25 +702,25 @@ class CFTPQueue // on error it throws TRACE_E void DebugCheckCounters(CFTPOperation* oper); - // returns progress based on the ratio between completed ('doneOrSkippedCount') and all - // items ('totalCount'); returns in 'unknownSizeCount' the number of unfinished items - // with unknown size; returns in 'waitingCount' the number of items waiting for + // returns progress based on the ratio between done or skipped items ('doneOrSkippedCount') and all + // items ('totalCount'); stores in 'unknownSizeCount' the number of unfinished items + // with unknown size; stores in 'waitingCount' the number of items waiting for // processing (waiting + delayed + processing) int GetSimpleProgress(int* doneOrSkippedCount, int* totalCount, int* unknownSizeCount, int* waitingCount); - // returns information for download - copy/move progress; returns in 'downloaded' the sum of downloaded - // sizes in bytes; returns in 'unknownSizeCount' the number of unfinished items with - // unknown size; returns in 'totalWithoutErrors' the sum of sizes (in bytes) - // of items that are not in an error state (a prompt to the user is also an error state) + // returns information for download copy/move progress; 'downloaded' receives the total + // number of downloaded bytes; 'unknownSizeCount' receives the number of unfinished items + // with unknown size; 'totalWithoutErrors' receives the total size (in bytes) + // of items that are not in an error state (a prompt to the user is also considered an error state) void GetCopyProgressInfo(CQuadWord* downloaded, int* unknownSizeCount, CQuadWord* totalWithoutErrors, int* errorsCount, int* doneOrSkippedCount, int* totalCount, CFTPOperation* oper); - // returns information for upload - copy/move progress; returns in 'uploaded' the sum of uploaded - // sizes in bytes; returns in 'unknownSizeCount' the number of unfinished items with - // unknown size; returns in 'totalWithoutErrors' the sum of sizes (in bytes) - // of items that are not in an error state (a prompt to the user is also an error state) + // returns information for upload copy/move progress; 'uploaded' receives the total + // number of uploaded bytes; 'unknownSizeCount' receives the number of unfinished items + // with unknown size; 'totalWithoutErrors' receives the total size (in bytes) + // of items that are not in an error state (a prompt to the user is also considered an error state) void GetCopyUploadProgressInfo(CQuadWord* uploaded, int* unknownSizeCount, CQuadWord* totalWithoutErrors, int* errorsCount, int* doneOrSkippedCount, int* totalCount, CFTPOperation* oper); @@ -732,11 +732,11 @@ class CFTPQueue // CAUTION: call only in the QueueCritSect critical section!!! DWORD GiveLastErrorOccurenceTime() { return ++LastErrorOccurenceTime; } - // searches for the UID of the item that needs to open the Solve Error dialog (a - // "new" error appeared in it (the user has not seen it yet)); returns TRUE if such an - // item was found, its UID is returned in 'itemUID' + its index + // searches for the UID of the item for which the Solve Error dialog needs to be opened (a + // "new" error has appeared in it, which the user has not seen yet); returns TRUE if such an + // item was found; its UID is returned in 'itemUID' and its index // in the queue in 'itemIndex' (the index may change immediately, so it should - // be taken only as indicative) + // be treated as indicative only) BOOL SearchItemWithNewError(int* itemUID, int* itemIndex); protected: @@ -761,7 +761,7 @@ enum CFTPDiskWorkType fdwtNone, // initialization value fdwtCreateDir, // creating a directory fdwtCreateFile, // creating/opening a file in a situation where the file state is unknown - fdwtRetryCreatedFile, // creating/opening a file in a situation where the file has already been created/overwritten/resumed_with_overwrite_option + fdwtRetryCreatedFile, // creating/opening a file when the file has already been created/overwritten/resumed with overwrite enabled fdwtRetryResumedFile, // creating/opening a file in a situation where the file has already been resumed fdwtCheckOrWriteFile, // verifying contents or writing to a file (for "resume" it checks the end of the file, writing happens beyond the end of the file) fdwtCreateAndWriteFile, // if the file is not open, it creates it (overwrites an existing file if any) + writes flush data to the file (at the position of the current seek, so normally at the end of the file) @@ -847,7 +847,7 @@ struct CFTPDiskWork struct CFTPFileToClose { char FileName[MAX_PATH]; // file name - HANDLE File; // file handle we should close + HANDLE File; // file handle to close BOOL DeleteIfEmpty; // TRUE = if the file being closed is empty, delete it BOOL SetDateAndTime; // TRUE = set 'Date'+'Time' before closing the file CFTPDate Date; // date to set as the last write time of the file; if Date.Day==0, it is an "empty value" @@ -866,7 +866,7 @@ class CFTPDiskThread : public CThread HANDLE ContEvent; // "signaled" if there is work in the Work array or if the thread should terminate // critical section for accessing the data part of the object - // CAUTION: consult access to critical sections in servers\critsect.txt!!! + // CAUTION: consult servers\critsect.txt before accessing critical sections CRITICAL_SECTION DiskCritSect; TIndirectArray Work; @@ -892,9 +892,9 @@ class CFTPDiskThread : public CThread // or until CancelWork() is called; returns success BOOL AddWork(CFTPDiskWork* work); - // cancels the work 'work' added to the thread; returns TRUE if the work has not started yet - // or if it can still be interrupted (it is in progress and after finishing the opposite - // action will be performed); if the work is in progress, returns TRUE in 'workIsInProgress' (if not NULL); returns + // cancels work 'work' added to the thread; returns TRUE if the work has not started yet + // or if it can still be canceled (it is in progress and, after finishing, the reverse + // action will be performed); if the work is in progress, sets 'workIsInProgress' to TRUE (if not NULL); returns // FALSE if the work has already finished BOOL CancelWork(const CFTPDiskWork* work, BOOL* workIsInProgress); @@ -986,7 +986,7 @@ enum CFTPWorkerSubState // substates for individual states from CFTPWorkerState fwssWorkExplWaitForPWDRes, // explore-dir: waiting for the result of "PWD" (obtaining the working path of the explored directory) fwssWorkExplWaitForPASVRes, // explore-dir: waiting for the result of "PASV" (getting IP+port for the passive data connection) fwssWorkExplOpenActDataCon, // explore-dir: open the active data connection - fwssWorkExplWaitForListen, // explore-dir: waiting for the "listen" port to open (we open an active data connection) - local or on the proxy server + fwssWorkExplWaitForListen, // explore-dir: waiting for the "listen" port to open (opening an active data connection), either locally or on the proxy server fwssWorkExplSetTypeA, // explore-dir: set transfer mode to ASCII fwssWorkExplWaitForPORTRes, // explore-dir: waiting for the result of "PORT" (passing IP+port to the server for the active data connection) fwssWorkExplWaitForTYPERes, // explore-dir: waiting for the result of "TYPE" (switch to ASCII data transfer mode) @@ -1004,13 +1004,13 @@ enum CFTPWorkerSubState // substates for individual states from CFTPWorkerState fwssWorkChAttrWaitForCHMODQuotedRes, // change attributes (name in quotes): waiting for the result of "SITE CHMOD" (change file/directory mode, probably Unix only) fwssWorkCopyWaitForPASVRes, // copy/move file: waiting for the result of "PASV" (getting IP+port for the passive data connection) fwssWorkCopyOpenActDataCon, // copy/move file: open the active data connection - fwssWorkCopyWaitForListen, // copy/move file: waiting for the "listen" port to open (we open an active data connection) - local or on the proxy server + fwssWorkCopyWaitForListen, // copy/move file: waiting for the listening port to open (opening an active data connection), either locally or on the proxy server fwssWorkCopySetType, // copy/move file: set the required transfer mode (ASCII / binary) fwssWorkCopyWaitForPORTRes, // copy/move file: waiting for the result of "PORT" (passing IP+port to the server for the active data connection) fwssWorkCopyWaitForTYPERes, // copy/move file: waiting for the result of "TYPE" (switch to ASCII / binary data transfer mode) fwssWorkCopyResumeFile, // copy/move file: optionally ensure resume (send the REST command) fwssWorkCopyWaitForResumeRes, // copy/move file: waiting for the result of the "REST" command (resume file) - fwssWorkCopyResumeError, // copy/move file: error of the "REST" command (not implemented, etc.) or we already know REST will fail + fwssWorkCopyResumeError, // copy/move file: "REST" command error (not implemented, etc.) or REST is already known to fail fwssWorkCopySendRetrCmd, // copy/move file: send the RETR command (start reading the file, possibly from the offset specified by Resume) fwssWorkCopyActivateDataCon, // copy/move file: activate the data connection (right after sending the RETR command) fwssWorkCopyWaitForRETRRes, // copy/move file: waiting for the result of "RETR" (waiting for the file reading to finish) @@ -1018,7 +1018,7 @@ enum CFTPWorkerSubState // substates for individual states from CFTPWorkerState fwssWorkCopyFinishFlushData, // copy/move file: ensure flushing the data from the data connection is finished (the connection is already closed) fwssWorkCopyFinishFlushDataAfterQuitSent, // copy/move file: after sending "QUIT" wait for the control connection to close + wait for the data flush to disk to finish fwssWorkCopyProcessRETRRes, // copy/move file: process the result of "RETR" (after ending the "data connection", flushing data to disk and receiving the server response to "RETR") - fwssWorkCopyDelayedAutoRetry, // copy/move file: wait WORKER_DELAYEDAUTORETRYTIMEOUT milliseconds for auto-retry (so that all unexpected responses from the server can arrive) + fwssWorkCopyDelayedAutoRetry, // copy/move file: wait WORKER_DELAYEDAUTORETRYTIMEOUT milliseconds before auto-retry (so that all unexpected responses from the server can arrive) fwssWorkCopyTransferFinished, // copy/move file: file transferred, in case of Move delete the source file fwssWorkCopyMoveWaitForDELERes, // copy/move file: waiting for the result of "DELE" (Move: delete the source file/link after finishing the file transfer) fwssWorkCopyDone, // copy/move file: done, close the file and go to the next item @@ -1037,26 +1037,26 @@ enum CFTPWorkerSubState // substates for individual states from CFTPWorkerState fwssWorkUploadAutorenDirSendMKD, // upload copy/move file: autorename - try to generate another new name for the target directory and try to create it fwssWorkUploadAutorenDirWaitForMKDRes, // upload copy/move file: autorename - waiting for the result of "MKD" (creating the target directory under a new name) fwssWorkUploadGetTgtPath, // upload copy/move file: determine the path to the target directory on the server - start by changing to it - fwssWorkUploadGetTgtPathWaitForCWDRes, // upload copy/move file: waiting for the result of "CWD" (setting the path to the target directory) + fwssWorkUploadGetTgtPathWaitForCWDRes, // upload copy/move file: waiting for the result of "CWD" (changing to the target directory) fwssWorkUploadGetTgtPathSendPWD, // upload copy/move file: send "PWD" (getting the path to the target directory) fwssWorkUploadGetTgtPathWaitForPWDRes, // upload copy/move file: waiting for the result of "PWD" (getting the path to the target directory) - fwssWorkUploadListDiskDir, // upload copy/move file: list the directory being uploaded from disk + fwssWorkUploadListDiskDir, // upload copy/move file: list the source directory on disk fwssWorkUploadListDiskWaitForDisk, // upload copy/move file: waiting for the disk operation to finish (listing the directory) fwssWorkUploadListDiskWaitForDiskAftQuit, // upload copy/move file: after sending the "QUIT" command wait for the disk operation to finish (listing the directory) fwssWorkUploadCantCreateFileInvName, // upload copy/move file: handle error "target file cannot be created" (invalid name) fwssWorkUploadCantCreateFileDirEx, // upload copy/move file: handle error "target file cannot be created" (name already used for directory or link to directory) fwssWorkUploadFileExists, // upload copy/move file: handle error "target file already exists" fwssWorkUploadNewFile, // upload copy/move file: the target file does not exist, start uploading it - fwssWorkUploadAutorenameFile, // upload copy/move file: handle the error when creating the target file - autorename + fwssWorkUploadAutorenameFile, // upload copy/move file: handle the error when creating the target file - auto-rename fwssWorkUploadResumeFile, // upload copy/move file: problem "target file exists" - resume fwssWorkUploadTestIfFinished, // upload copy/move file: we sent the entire file + the server "just" did not respond, most likely the file is OK, we will test it - fwssWorkUploadResumeOrOverwriteFile, // upload copy/move file: problem "target file exists" - resume or overwrite + fwssWorkUploadResumeOrOverwriteFile, // upload copy/move file: issue "target file exists" - resume or overwrite fwssWorkUploadOverwriteFile, // upload copy/move file: problem "target file exists" - overwrite fwssWorkUploadFileSetTgtPath, // upload file: set the target path fwssWorkUploadFileSetTgtPathWaitForCWDRes, // upload file: waiting for the result of "CWD" (setting the target path) fwssWorkUploadGenNewName, // upload file: autorename: generate a new name fwssWorkUploadLockFile, // upload file: open the file in FTPOpenedFiles - fwssWorkUploadDelForOverwrite, // upload file: if this is an overwrite and delete should be used first, do it here + fwssWorkUploadDelForOverwrite, // upload file: if this is an overwrite and delete should be used first, perform the delete here fwssWorkUploadDelForOverWaitForDELERes, // upload file: waiting for the DELE result before overwrite fwssWorkUploadFileAllocDataCon, // upload file: allocate the data connection fwssWorkUploadGetFileSize, // upload file: resume: determine the file size (via the SIZE command or from the listing) @@ -1066,7 +1066,7 @@ enum CFTPWorkerSubState // substates for individual states from CFTPWorkerState fwssWorkUploadTestFileSizeFailed, // upload copy/move file: after an upload error the file size test failed fwssWorkUploadWaitForPASVRes, // upload copy/move file: waiting for the result of "PASV" (getting IP+port for the passive data connection) fwssWorkUploadOpenActDataCon, // upload copy/move file: open the active data connection - fwssWorkUploadWaitForListen, // upload copy/move file: waiting for the "listen" port to open (we open an active data connection) - local or on the proxy server + fwssWorkUploadWaitForListen, // upload copy/move file: waiting for the "listen" port to open (opening an active data connection), locally or on the proxy server fwssWorkUploadWaitForPORTRes, // upload copy/move file: waiting for the result of "PORT" (passing IP+port to the server for the active data connection) fwssWorkUploadSetType, // upload copy/move file: set the required transfer mode (ASCII / binary) fwssWorkUploadWaitForTYPERes, // upload copy/move file: waiting for the result of "TYPE" (switch to ASCII / binary data transfer mode) @@ -1082,11 +1082,11 @@ enum CFTPWorkerSubState // substates for individual states from CFTPWorkerState enum CFTPWorkerSocketEvent { - fwseConnect, // [error, 0], connection to the server opened + fwseConnect, // [error, 0], opening a connection to the server fwseClose, // [error, 0], socket was closed - fwseNewBytesRead, // [error, 0], another block of data read into the socket buffer + fwseNewBytesRead, // [error, 0], another block of data was read into the socket buffer fwseWriteDone, // [error, 0], buffer write finished (only if Write returned 'allBytesWritten'==FALSE) - fwseIPReceived, // [IP, error], we received the IP (while resolving the host name) + fwseIPReceived, // [IP, error], IP address received (while resolving the host name) fwseTimeout, // [0, 0], timer delivery reports timeout while sending FTP commands (see WORKER_TIMEOUTTIMERID) fwseWaitForCmdErr, // [0, 0], sending a command to the server failed, waiting whether FD_CLOSE arrives, if not, close the socket "manually" }; @@ -1152,11 +1152,11 @@ enum CFTPWorkerCmdState // the command or connection loss while sending/waiting for the reply or a timeout - connection closed // because we did not receive the server's reply to the FTP command) fwcsWaitForCmdReply, - fwcsWaitForLoginPrompt, // same functionality as fwcsWaitForCmdReply, we distinguish only because of error messages + fwcsWaitForLoginPrompt, // same functionality as fwcsWaitForCmdReply; distinguished only because of error messages - // waiting for the reason of an error that occurred when sending a command (writing to the socket): waiting for fwseClose, - // if it does not arrive we close the socket "manually" (on fwseWaitForCmdErr timeout); at the same time we capture an error - // message from the socket or at least from fwseClose; if we capture nothing, we at least print WaitForCmdErrError + // waiting for the cause of an error that occurred when sending a command (writing to the socket): waiting for fwseClose, + // if it does not arrive, close the socket "manually" (on fwseWaitForCmdErr timeout); at the same time, capture an error + // message from the socket or at least from fwseClose; if nothing is captured, at least print WaitForCmdErrError fwcsWaitForCmdError, }; @@ -1235,7 +1235,7 @@ enum CUploadType #define WORKER_RECONTIMEOUTTIMID 33 // timer ID for waiting for another connect attempt (reconnect) #define WORKER_STATUSUPDATETIMID 34 // timer ID for periodically updating the status #define WORKER_DATACONSTARTTIMID 35 // timer ID for detecting a timeout while waiting for the data connection to open after receiving the server reply to RETR (WarFTPD illogically sends 226 even before our data connection accept) -#define WORKER_DELAYEDAUTORETRYTIMID 36 // timer ID for delaying auto-retry (e.g. Quick&Easy FTPD returns 426 for RETR and immediately 220 - if you retry immediately, responses shift (220 is taken as the response to the next command instead of this command and everything goes wrong)) +#define WORKER_DELAYEDAUTORETRYTIMID 36 // timer ID used to delay auto-retry (e.g. Quick&Easy FTPD returns 426 for RETR and immediately afterwards 220; if retried immediately, the replies become misaligned, so 220 is taken as the response to the next command instead of this one) #define WORKER_LISTENTIMEOUTTIMID 37 // timer ID ensuring timeout detection when opening the "listen" port on the proxy server (when opening an active data connection) #define WORKER_STATUSUPDATETIMEOUT 1000 // time in milliseconds after which the status in the worker (and the worker progress and overall progress in the operation dialog) is updated - NOTE: linked to OPERDLG_STATUSMINIDLETIME @@ -1267,8 +1267,8 @@ class CFTPWorker : public CSocket int ReadBytesOffset; // number of bytes already processed (skipped) in the 'ReadBytes' buffer int ReadBytesAllocatedSize; // allocated size of the 'ReadBytes' buffer - CDataConnectionSocket* WorkerDataCon; // NULL; otherwise, the data connection currently used by this worker (state see WorkerDataConState) - CUploadDataConnectionSocket* WorkerUploadDataCon; // NULL; otherwise, the data connection currently used by this worker for upload (state see WorkerDataConState) + CDataConnectionSocket* WorkerDataCon; // NULL; otherwise, the data connection currently used by this worker (see WorkerDataConState for its state) + CUploadDataConnectionSocket* WorkerUploadDataCon; // NULL; otherwise, the data connection currently used by this worker for upload (state: see WorkerDataConState) // critical section for accessing the data part of the object (data for display in dialogs) // WARNING: consult access to critical sections in the file servers\critsect.txt !!! @@ -1281,7 +1281,7 @@ class CFTPWorker : public CSocket int LogUID; // log UID for this worker (-1 if the log is not created); NOTE: it is in WorkerCritSect and not SocketCritSect !!! CFTPWorkerState State; // worker state, see CFTPWorkerState CFTPWorkerSubState SubState; // state inside the worker state (substate for the processing steps of each State), see CFTPWorkerSubState - CFTPQueueItem* CurItem; // read-only data: processed item (in state sqisProcessing), NULL=worker has no work; write via Queue and CurItem->UID + CFTPQueueItem* CurItem; // read-only data: item being processed (in state sqisProcessing), NULL = worker has no work; write via Queue and CurItem->UID char ErrorDescr[FTPWORKER_ERRDESCR_BUFSIZE]; // textual description of the error, contains no CR or LF and does not end with a period; ensuring these conditions see CorrectErrorDescr(); displayed for fwsWaitingForReconnect and fwsConnectionError, filled on errors see CFTPWorkerEvent int ConnectAttemptNumber; // number of the current attempt to establish the connection; before the very first attempt this is zero (set to one when the connection is established) CCertificate* UnverifiedCertificate; // SSL: if the attempt to connect fails due to an unknown untrusted certificate, the connection is closed and the certificate is stored here (we show it to the user in the Solve Error dialog) @@ -1306,7 +1306,7 @@ class CFTPWorker : public CSocket const char* ProxyScriptExecPoint; // current proxy script command (NULL = first command); WARNING: not intended for reading, only for passing to CFTPOperation::PrepareNextScriptCmd() int ProxyScriptLastCmdReply; // reply to the last command sent from the proxy script (-1 = none) - BOOL DiskWorkIsUsed; // TRUE if DiskWork is inserted in FTPDiskThread + BOOL DiskWorkIsUsed; // TRUE if DiskWork is added to FTPDiskThread HANDLE OpenedFile; // target file for copy/move operations CQuadWord OpenedFileSize; // current size of the 'OpenedFile' @@ -1347,7 +1347,7 @@ class CFTPWorker : public CSocket BOOL UploadDirGetTgtPathListing; // only when processing upload-dir-explore or upload-file items: TRUE = the target path listing should be fetched - int UploadAutorenamePhase; // upload: current phase of generating names for the target directory/file (see FTPGenerateNewName()); 0 = beginning of the autorename process; -1 = it was the last generation phase, we simply cannot generate another name of that type + int UploadAutorenamePhase; // upload: current phase of generating names for the target directory/file (see FTPGenerateNewName()); 0 = beginning of the autorename process; -1 = this was the last generation phase, and another name of that type cannot be generated char UploadAutorenameNewName[MAX_PATH]; // upload: buffer for the last generated name for the target directory/file CUploadType UploadType; // type of upload (according to the state of the target file): new, resume, resume or overwrite, overwrite, autorename @@ -1379,8 +1379,8 @@ class CFTPWorker : public CSocket // returns State (in the WorkerCritSect critical section) CFTPWorkerState GetState(); - // returns ShouldBePaused (in the WorkerCritSect critical section); in 'isWorking' (must not be - // NULL) returns TRUE if the worker is working (not sleeping, not waiting for the user, and not terminated); + // returns ShouldBePaused (in the WorkerCritSect critical section); sets 'isWorking' (must not be + // NULL) to TRUE if the worker is working (not sleeping, not waiting for the user, and not terminated); BOOL IsPaused(BOOL* isWorking); // sets 'CopyOfUID' and 'CopyOfMsg' (in the CSocket::SocketCritSect and @@ -1422,9 +1422,9 @@ class CFTPWorker : public CSocket // if we already attempted deletion via DeleteWorkers); returns TRUE if cancellation is possible BOOL CanDeleteFromRetCons(); - // used to query whether the worker can be cancelled from DeleteWorkers (only if the - // connection from the worker is not being returned to the panel, or if we already attempted deletion - // from the CReturningConnections methods); returns TRUE if cancellation is possible + // used to query whether the worker can be deleted from DeleteWorkers (only if the + // worker's connection is not being returned to the panel, or if we have already attempted deletion + // from the CReturningConnections methods); returns TRUE if deletion is possible BOOL CanDeleteFromDelWorkers(); // informs the worker that it should attempt to stop; returns TRUE if the worker @@ -1440,7 +1440,7 @@ class CFTPWorker : public CSocket // informs the worker that it should attempt to pause/resume; returns TRUE if the worker // wants to post WORKER_SHOULDPAUSE or WORKER_SHOULDRESUME (fweWorkerShouldPause // or fweWorkerShouldResume) by calling PostShouldPauseOrResume() after this - // method; 'pause' is TRUE/FALSE depending on pause/resume + // method finishes; 'pause' is TRUE for pause and FALSE for resume // WARNING: may be called for one worker several times in a row (check whether it has already been called; if so, do nothing and return FALSE)! BOOL InformAboutPause(BOOL pause); @@ -1449,9 +1449,9 @@ class CFTPWorker : public CSocket // critical sections void PostShouldPauseOrResume(); - // determines whether the worker "control connection" socket is closed and the worker - // "data connection" does not exist; returns TRUE if the "control connection" socket is closed - // and the "data connection" does not exist (the worker can be cancelled) + // checks whether the worker's "control connection" socket is closed and the worker + // has no "data connection"; returns TRUE if the "control connection" socket is closed + // and no "data connection" exists (the worker can be deleted) BOOL SocketClosedAndDataConDoesntExist(); // determines whether the worker has work in the disk thread; returns FALSE if it has no work @@ -1478,13 +1478,13 @@ class CFTPWorker : public CSocket // clears the read and write buffers (useful for example before reopening the connection) void ResetBuffersAndEvents(); - // writes to the socket (performs "send") bytes from the 'buffer' of length 'bytesToWrite' + // writes bytes from 'buffer' to the socket (using "send") with length 'bytesToWrite' // (if 'bytesToWrite' is -1, writes strlen(buffer) bytes); on error returns FALSE and, - // if the Windows error code is known, returns it in 'error' (if not NULL); if it returns TRUE, - // at least part of the buffer was successfully written; in 'allBytesWritten' (must not be - // NULL) returns TRUE if the entire buffer was written; if 'allBytesWritten' - // returns FALSE, before the next call to Write you must wait for the fwseWriteDone event - // (once it arrives, the write is complete) + // if the Windows error code is known, stores it in 'error' (if not NULL); if it returns TRUE, + // at least part of the buffer was written successfully; 'allBytesWritten' (must not be + // NULL) is set to TRUE if the entire buffer was written; if 'allBytesWritten' is + // FALSE, you must wait for the fwseWriteDone event before the next call to Write + // (once it occurs, the write is complete) BOOL Write(const char* buffer, int bytesToWrite, DWORD* error, BOOL* allBytesWritten); // helper method to detect whether the entire reply from the FTP server is already in the 'ReadBytes' buffer; @@ -1553,10 +1553,10 @@ class CFTPWorker : public CSocket // a Windows error code (arrived with FD_CLOSE or arose while processing FD_CLOSE) virtual void SocketWasClosed(DWORD error); - // reception of a timer with ID 'id' and parameter 'param' + // receives a timer with ID 'id' and parameter 'param' virtual void ReceiveTimer(DWORD id, void* param); - // reception of a posted message with ID 'id' and parameter 'param' + // receives a posted message with ID 'id' and parameter 'param' virtual void ReceivePostMessage(DWORD id, void* param); protected: @@ -1669,7 +1669,7 @@ class CFTPWorker : public CSocket CQuadWord const* writeOrReadFromOffset, int validBytesInFlushDataBuffer, HANDLE workFile); - // returns the processed 'CurItem' back to the queue (returns it to the "waiting" state so another + // returns the current item being processed, 'CurItem', back to the queue (puts it back into the "waiting" state so another // worker can process it) // WARNING: call only inside the WorkerCritSect critical section !!! void ReturnCurItemToQueue(); @@ -1719,7 +1719,7 @@ class CFTPWorkersList { protected: // critical section for accessing the object's data - // WARNING: consult access to critical sections in the servers\critsect.txt file !!! + // WARNING: consult servers\critsect.txt before accessing critical sections. CRITICAL_SECTION WorkersListCritSect; TIndirectArray Workers; // array of workers @@ -1738,10 +1738,10 @@ class CFTPWorkersList // informs workers that they should attempt to stop; operates on all workers // of the operation (if 'workerInd' is -1) or only on the worker at index 'workerInd'; must - // be called repeatedly until it returns TRUE (processing is batched); 'victims'+'maxVictims' + // be called repeatedly as long as it returns TRUE (processing is batched); 'victims'+'maxVictims' // is an array for workers that need to close the data connection or post WORKER_SHOULDSTOP // (fweWorkerShouldStop) by calling CloseDataConnectionOrPostShouldStop() after this method - // finishes; 'foundVictims' receives the number of filled items in the 'victims' array on input and + // finishes; 'foundVictims' contains the number of filled items in the 'victims' array on input and // returns the updated count of filled items BOOL InformWorkersAboutStop(int workerInd, CFTPWorker** victims, int maxVictims, int* foundVictims); @@ -1842,13 +1842,13 @@ class CFTPWorkersList // WARNING: enters the CSocketsThread::CritSect section !!! void PostLoginChanged(int workerID); - // informs workers in the "sleeping" state about the existence of new work (impulse to search - // for work in the item queue); if 'onlyOneItem' is TRUE, there is just one item - // (informing one worker is enough), otherwise there are more items (inform all - // workers); informing the workers = posting WORKER_WAKEUP; - // WARNING: does not fully lock the WorkersListCritSect, it may not be executed for a worker - // added while the method is running (see AddWorker()) !!! - // WARNING: enters the CSocketsThread::CritSect section !!! + // informs workers in the "sleeping" state that new work is available (a signal to search + // for work in the item queue); if 'onlyOneItem' is TRUE, there is only one item + // (informing one worker is enough), otherwise there are multiple items (inform all + // workers); workers are notified by posting WORKER_WAKEUP; + // WARNING: does not fully use the WorkersListCritSect critical section, so a worker + // added while the method is running may not be informed (see AddWorker()) !!! + // WARNING: enters the CSocketsThread::CritSect critical section !! void PostNewWorkAvailable(BOOL onlyOneItem); // attempts to find a "sleeping" worker with an open connection; on success, @@ -1864,11 +1864,11 @@ class CFTPWorkersList // adds to 'uploaded' the size (in bytes) of the files currently being uploaded by all workers void AddCurrentUploadSize(CQuadWord* uploaded); - // searches for the index of a worker that needs to open the Solve Error dialog (a - // "new" error appeared there (the user has not seen it yet)); 'lastErrorOccurenceTime' is the "time" - // assigned to the last error (used for a quick test whether it even makes sense to look - // for a "new" error); returns TRUE if such a worker was found, - // its index is returned in 'index' + // searches for the index of a worker that needs the Solve Error dialog to be opened (a + // "new" error has appeared for that worker and the user has not seen it yet); 'lastErrorOccurenceTime' is the "time" + // assigned to the last error (used as a quick test of whether it makes sense to search + // for a "new" error at all); returns TRUE if such a worker is found, + // and returns its index in 'index' BOOL SearchWorkerWithNewError(int* index, DWORD lastErrorOccurenceTime); // returns TRUE if the worker list is empty or all workers should stop @@ -1908,8 +1908,8 @@ class CTransferSpeedMeter // can be called from any thread void Clear(); - // returns the connection speed in bytes per second; in 'transferIdleTime' (may be NULL) - // returns the time in seconds since the last data reception + // returns the connection speed in bytes per second; stores in 'transferIdleTime' (may be NULL) + // the time in seconds since the last data was received // can be called from any thread DWORD GetSpeed(DWORD* transferIdleTime); @@ -1999,35 +1999,35 @@ enum CFTPOperationType #define RETRYONRESUMFILE_SKIP 5 // skip (simply do not perform the operation) // WARNING: when adding a value, check the bit range in CFTPOperation !!! -// how to solve the problem "ASCII transfer mode for a binary file" +// how to handle the problem "ASCII transfer mode for a binary file" #define ASCIITRFORBINFILE_USERPROMPT 0 // ask the user #define ASCIITRFORBINFILE_IGNORE 1 // ignore it, the user knows what they are doing #define ASCIITRFORBINFILE_INBINMODE 2 // change the transfer mode to binary and restart the transfer (assuming nothing has been written to the file yet) #define ASCIITRFORBINFILE_SKIP 3 // skip (simply do not perform the operation) // WARNING: when adding a value, check the bit range in CFTPOperation !!! -// how to solve the situation "deleting a non-empty directory" +// how to handle the situation "deleting a non-empty directory" #define NONEMPTYDIRDEL_USERPROMPT 0 // ask the user #define NONEMPTYDIRDEL_DELETEIT 1 // delete it without asking #define NONEMPTYDIRDEL_SKIP 2 // skip (simply do not perform the operation) // WARNING: when adding a value, check the bit range in CFTPOperation !!! -// how to solve the situation "deleting a hidden file" +// how to handle the situation "deleting a hidden file" #define HIDDENFILEDEL_USERPROMPT 0 // ask the user #define HIDDENFILEDEL_DELETEIT 1 // delete it without asking #define HIDDENFILEDEL_SKIP 2 // skip (simply do not perform the operation) // WARNING: when adding a value, check the bit range in CFTPOperation !!! -// how to solve the situation "deleting a hidden directory" +// how to handle the situation "deleting a hidden directory" #define HIDDENDIRDEL_USERPROMPT 0 // ask the user #define HIDDENDIRDEL_DELETEIT 1 // delete it without asking #define HIDDENDIRDEL_SKIP 2 // skip (simply do not perform the operation) // WARNING: when adding a value, check the bit range in CFTPOperation !!! -// how to solve the problem "file/directory has unknown attributes that we cannot preserve (permissions other than 'r'+'w'+'x')" +// how to handle the problem "a file/directory has unknown attributes that we cannot preserve (permissions other than 'r'+'w'+'x')" #define UNKNOWNATTRS_USERPROMPT 0 // ask the user #define UNKNOWNATTRS_IGNORE 1 // ignore it, the user knows what they are doing (set attributes as close to the requested ones as possible) -#define UNKNOWNATTRS_SKIP 2 // we will not change attributes on this file/directory (skip the file/directory) +#define UNKNOWNATTRS_SKIP 2 // do not change attributes on this file/directory (skip the file/directory) // WARNING: when adding a value, check the bit range in CFTPOperation !!! class CExploredPaths @@ -2052,7 +2052,7 @@ class CExploredPaths BOOL AddPath(const char* path); protected: - // returns "found?" and the index of the item or where it should be inserted (sorted array) + // returns "found?" and the item index or the insertion position (sorted array) BOOL GetPathIndex(const char* path, int pathLen, int& index); }; @@ -2065,7 +2065,7 @@ enum COperationState opstFinishedWithErrors // the operation was completed but with errors (items are in the sqisDone, sqisSkipped, sqisFailed or sqisForcedToFail states) }; -#define SMPLCMD_APPROXBYTESIZE 1000 // approximate size of processing a single item in bytes for measuring the speed of Delete and ChangeAttrs operations +#define SMPLCMD_APPROXBYTESIZE 1000 // approximate number of bytes to process one item, for measuring the speed of Delete and ChangeAttrs operations class CFTPOperation { @@ -2075,7 +2075,7 @@ class CFTPOperation protected: // critical section for accessing the object's data - // WARNING: consult access to critical sections in the servers\critsect.txt file !!! + // WARNING: consult servers\critsect.txt before accessing critical sections. CRITICAL_SECTION OperCritSect; int UID; // unique operation number (index in the CFTPOperationsList::Operations array + link for items in the Queue) @@ -2100,16 +2100,16 @@ class CFTPOperation char* User; // user (NULL = unknown) WARNING: anonymous is already part of the string here char* Password; // password (NULL = unknown) WARNING: anonymous password (email) is already part of the string here char* Account; // account info (see FTP command "ACCT") (NULL = unknown) - BOOL RetryLoginWithoutAsking; // TRUE = the worker should try to reconnect even for "error" server replies (code "5xx"); FALSE = reconnect only for "transient-error" replies (code "4xx"); set later by the user when resolving the worker connection problem + BOOL RetryLoginWithoutAsking; // TRUE = the worker should try to reconnect even for "error" server replies (code "5xx"); FALSE = reconnect only for "transient-error" replies (code "4xx"); set later by the user when resolving the worker's connection problem char* InitFTPCommands; // list of FTP commands to send to the server immediately after connecting (NULL = no commands) BOOL UsePassiveMode; // TRUE/FALSE = passive/active data connection mode - BOOL SizeCmdIsSupported; // FALSE = the SIZE command received the server reply "not supported" (no point trying again) + BOOL SizeCmdIsSupported; // FALSE = the server replied "not supported" to the SIZE command (no point trying again) char* ListCommand; // command to obtain a listing of a path on this server (NULL = "LIST") DWORD ServerIP; // IP address of the FTP/Proxy server 'ConnectToHost' (==INADDR_NONE until the IP is known) char* ServerSystem; // server system (reply to the SYST command) - may also be NULL char* ServerFirstReply; // first server reply (often contains the FTP server version) - may also be NULL BOOL UseListingsCache; // TRUE = the user wants to store listings in the cache for this connection - char* ListingServerType; // server type for parsing listings: NULL = autodetect; otherwise the server type name (without the optional leading '*'; if it stops existing, it switches to autodetect) + char* ListingServerType; // server type for parsing listings: NULL = autodetect; otherwise the server type name (without the optional leading '*'; if it no longer exists, it switches to autodetect) BOOL EncryptControlConnection; BOOL EncryptDataConnection; int CompressData; @@ -2134,7 +2134,7 @@ class CFTPOperation int ChildItemsNotDone; // number of unfinished "child" items (except type sqisDone) int ChildItemsSkipped; // number of skipped "child" items (type sqisSkipped) int ChildItemsFailed; // number of failed "child" items (types sqisFailed and sqisForcedToFail) - int ChildItemsUINeeded; // number of user-input-needed "child" items (types sqisFailed and sqisForcedToFail) + int ChildItemsUINeeded; // number of "child" items that require user input (types sqisFailed and sqisForcedToFail) char* SourcePath; // operation source path (full path, possibly including fs-name) char SrcPathSeparator; // most frequently used source path separator ('/', '.', etc.) @@ -2168,8 +2168,8 @@ class CFTPOperation // valid only for download: // data for estimating the block size (for VMS, MVS and other servers that use // blocks - ignored elsewhere) - CQuadWord BlkSizeTotalInBytes; // total size of files obtained so far in bytes (we take only files with a size of at least two blocks) - CQuadWord BlkSizeTotalInBlocks; // total size of files obtained so far in blocks (we take only files with a size of at least two blocks) + CQuadWord BlkSizeTotalInBytes; // total size of files obtained so far in bytes (counting only files at least two blocks in size) + CQuadWord BlkSizeTotalInBlocks; // total size of files obtained so far in blocks (counting only files at least two blocks in size) DWORD BlkSizeActualValue; // current value of the real block size (for progress estimation) (-1 = unknown) BOOL ResumeIsNotSupported; // TRUE = the FTP REST/APPE command returns a permanent error (e.g. "not implemented") @@ -2208,7 +2208,7 @@ class CFTPOperation unsigned ConfirmDelOnHiddenDir : 2; // see constants HIDDENDIRDEL_XXX // **************************************************************************** - // more for Change Attributes: + // additional settings for Change Attributes: // **************************************************************************** unsigned ChAttrOfFiles : 1; // TRUE/FALSE = change/do not change file attributes @@ -2326,9 +2326,9 @@ class CFTPOperation void AddToNotDoneSkippedFailed(int notDone, int skipped, int failed, int uiNeeded, BOOL onlyUINeededOrFailedToSkipped); - // determines whether the name matches the aggregate ASCIIFileMasks mask; 'name'+'ext' are pointers - // to the name and extension (or the end of the name), both placed in a single buffer; returns TRUE if - // the name matches the aggregate mask + // determines whether the name matches the ASCIIFileMasks wildcard mask; 'name' and 'ext' are pointers + // to the name and extension (or the end of the name), both pointing into a single buffer; returns TRUE if + // the name matches the wildcard mask BOOL IsASCIIFile(const char* name, const char* ext); // adds/subtracts 'size' to/from 'TotalSizeInBytes' (if 'sizeInBytes' is TRUE) or to/from 'TotalSizeInBlocks' @@ -2341,7 +2341,7 @@ class CFTPOperation // sets OperationDlg (in the critical section) void SetOperationDlg(COperationDlg* operDlg); - // activates or opens the operation dialog (see OperationDlg); returns success of the operation + // activates or opens the operation dialog (see OperationDlg); returns whether the operation succeeded BOOL ActivateOperationDlg(HWND dropTargetWnd); // closes the operation dialog (if open) and returns the handle of the thread in which the @@ -2449,16 +2449,16 @@ class CFTPOperation void ReportWorkerChange(int workerID, BOOL reportProgressChange); // called by the operation dialog after a change is reported via ReportWorkerChange(); returns the ID of the changed worker - // or -1 if more than one changed; in 'reportProgressChange' (if not NULL) returns TRUE if - // it was a worker change associated with a progress (status) change + // or -1 if more than one worker changed; stores TRUE in 'reportProgressChange' (if not NULL) if + // the worker change was associated with a progress/status change int GetChangedWorker(BOOL* reportProgressChange); // just calls CFTPWorkersList::PostNewWorkAvailable() // WARNING: enters the CSocketsThread::CritSect section !!! void PostNewWorkAvailable(BOOL onlyOneItem); - // just calls CFTPWorkersList::GiveWorkToSleepingConWorker() - // WARNING: enters the CSocketsThread::CritSect section !!! + // only calls CFTPWorkersList::GiveWorkToSleepingConWorker() + // WARNING: enters the CSocketsThread::CritSect critical section !! BOOL GiveWorkToSleepingConWorker(CFTPWorker* sourceWorker); // called to report an item change (only changes that affect the item display in the Operations listview @@ -2528,7 +2528,7 @@ class CFTPOperation BOOL GetEncryptControlConnection() { return EncryptControlConnection; } BOOL GetEncryptDataConnection() { return EncryptDataConnection; } int GetCompressData() { return CompressData; } - CCertificate* GetCertificate(); // WARNING: returns the certificate only after calling its AddRef(), so the caller is responsible for releasing it by calling Release() + CCertificate* GetCertificate(); // WARNING: returns the certificate after calling AddRef() on it, so the caller is responsible for releasing it by calling Release() void SetEncryptDataConnection(BOOL encryptDataConnection) { EncryptDataConnection = encryptDataConnection; } void SetEncryptControlConnection(BOOL encryptControlConnection) { EncryptControlConnection = encryptControlConnection; } @@ -2593,10 +2593,10 @@ class CFTPOperation // determines whether 'ServerSystem' contains the name 'systemName' BOOL IsServerSystem(const char* systemName); - // returns TRUE if the path 'path' is already in the list of explored paths (see 'ExploredPaths'); + // returns TRUE if 'path' is already in the list of explored paths (see 'ExploredPaths'); // WARNING: assumes that 'path' is a path returned by the server, so paths // are compared only as case-sensitive strings (slashes/backslashes/dots, etc., are not trimmed) - // - a cycle may be detected only on its second pass, which is sufficient for our purposes + // - a cycle may be detected only when it is encountered a second time, which is sufficient for our purposes BOOL IsAlreadyExploredPath(const char* path); // stores the path 'path' in the list of explored paths (see 'ExploredPaths'); @@ -2755,9 +2755,9 @@ class CFTPOperation const char* path, CFTPServerPathType pathType, int userLength); - // determines whether among the operations there is an upload to the server 'user'+'host'+'port'; - // 'user' is NULL for anonymous connections; 'userLength' is zero if we do not know how long the username is - // or if it does not contain "forbidden" characters, otherwise it is the expected username length + // determines whether the operations include an upload to the server 'user'+'host'+'port'; + // 'user' is NULL for anonymous connections; 'userLength' is zero if the username length is unknown + // or if the username does not contain "forbidden" characters, otherwise it is the expected username length BOOL IsUploadingToServer(const char* user, const char* host, unsigned short port, int userLength); @@ -2783,7 +2783,7 @@ class CFTPOperationsList { protected: // critical section for accessing the object's data - // WARNING: consult access to critical sections in the servers\critsect.txt file !!! + // WARNING: consult servers\critsect.txt before accessing critical sections. CRITICAL_SECTION OpListCritSect; // list of existing operations; the operation UID is the index into this array, @@ -2800,32 +2800,32 @@ class CFTPOperationsList // returns TRUE if there is no operation in the list BOOL IsEmpty(); - // adds a new operation to the array (works with FirstFreeIndexInOperations); in 'newuid' (if not NULL) + // adds a new operation to the array (uses FirstFreeIndexInOperations); in 'newuid' (if not NULL) // returns the UID of the added operation; returns TRUE on success BOOL AddOperation(CFTPOperation* newOper, int* newuid); // closes all open operation dialogs and waits for all dialog threads to finish void CloseAllOperationDlgs(); - // stops and cancels selected workers of operations; 'parent' is the thread's "foreground" window (after - // pressing ESC it is used to determine whether ESC was pressed in this window and not - // for example in another application; in the main thread it is SalamanderGeneral->GetMsgBoxParent() + // stops and cancels the selected operation workers; 'parent' is the thread's "foreground" window (after + // pressing ESC, it is used to determine whether ESC was pressed in this window and not, + // for example, in another application; in the main thread it is SalamanderGeneral->GetMsgBoxParent() // or a dialog opened by the plugin); if 'operUID' is -1, it works with all workers of all // operations; if 'operUID' is not -1 and 'workerInd' is -1, it works with all workers // of the operation with UID 'operUID'; if neither 'operUID' nor 'workerInd' is -1, it works with the worker // at index 'workerInd' of the operation with UID 'operUID' - // WARNING: enters the CSocketsThread::CritSect and CSocket::SocketCritSect sections !!! + // WARNING: enters the CSocketsThread::CritSect and CSocket::SocketCritSect critical sections !! void StopWorkers(HWND parent, int operUID, int workerInd); - // pauses or resumes selected workers of operations; 'parent' is the thread's "foreground" window (after - // pressing ESC it is used to determine whether ESC was pressed in this window and not - // for example in another application; in the main thread it is SalamanderGeneral->GetMsgBoxParent() + // pauses or resumes the selected operation workers; 'parent' is the thread's "foreground" window (after + // pressing ESC, it is used to determine whether ESC was pressed in this window and not, + // for example, in another application; in the main thread it is SalamanderGeneral->GetMsgBoxParent() // or a dialog opened by the plugin); if 'operUID' is -1, it works with all workers of all // operations; if 'operUID' is not -1 and 'workerInd' is -1, it works with all workers // of the operation with UID 'operUID'; if neither 'operUID' nor 'workerInd' is -1, it works with the worker - // at index 'workerInd' of the operation with UID 'operUID'; if 'pause' is TRUE the selected - // workers should pause, otherwise they should resume - // WARNING: enters the CSocketsThread::CritSect and CSocket::SocketCritSect sections !!! + // at index 'workerInd' of the operation with UID 'operUID'; if 'pause' is TRUE, the selected + // workers are paused, otherwise they are resumed + // WARNING: enters the CSocketsThread::CritSect and CSocket::SocketCritSect critical sections !! void PauseWorkers(HWND parent, int operUID, int workerInd, BOOL pause); // removes the operation with UID 'uid' from the array (updates FirstFreeIndexInOperations); @@ -2905,7 +2905,7 @@ class CUIDArray struct CReturningConnectionData { - int ControlConUID; // to which "control connection" in the panel we return the connection + int ControlConUID; // control connection in the panel to which the connection is returned CFTPWorker* WorkerWithCon; // worker with the returned connection CReturningConnectionData(int controlConUID, CFTPWorker* workerWithCon) @@ -2966,7 +2966,7 @@ struct CUploadListingItem // data of a single file/directory/link in the listing enum CUploadListingChangeType { - ulctDelete, // deleting a name + ulctDelete, // deleting a file name ulctCreateDir, // creating a directory ulctStoreFile, // start uploading a file (may also overwrite a file/link) ulctFileUploaded, // upload finished (may also overwrite a file/link) @@ -3018,7 +3018,7 @@ struct CUploadPathListing // listing for a specific path on the server CUploadListingChange* LastChange; // only in ulsInProgress: last change in the listing (a new change is appended after this one) DWORD LatestChangeTime; // IncListingCounter() from the moment of the last listing change (used to check whether it is possible to update the listing with a new listing - only if LatestChangeTime is less than the start time of downloading the new listing) CUploadWaitingWorker* FirstWaitingWorker; // only in ulsInProgress* states: list of workers waiting for the path listing to finish (or fail) - BOOL FromPanel; // TRUE = listing taken from the panel (may be outdated; if there is doubt about the listing freshness, refresh it) + BOOL FromPanel; // TRUE = listing taken from the panel (may be outdated; if its freshness is in doubt, it is refreshed) TIndirectArray ListingItem; // array of listing items @@ -3040,13 +3040,13 @@ struct CUploadPathListing // listing for a specific path on the server // a possible new item with CUploadListingItem::Name == 'name' should be inserted BOOL FindItem(const char* name, int& index); - // parses the listing 'pathListing'+'pathListingLen'+'pathListingDate'; 'welcomeReply' (must not + // parses the listing from 'pathListing'+'pathListingLen'+'pathListingDate'; 'welcomeReply' (must not // be NULL) is the first server reply (often contains the FTP server version); // 'systReply' (must not be NULL) is the server system (reply to the SYST command); - // 'suggestedListingServerType' is the server type used for parsing the listing: NULL = autodetect, - // otherwise the server type name (without the optional leading '*'; if it stops existing, it switches - // to autodetect); if 'lowMemory' is not NULL, it returns TRUE in it when memory is low; - // returns TRUE if the entire listing was successfully parsed and the object is filled with new items + // 'suggestedListingServerType' is the server type for parsing the listing: NULL = autodetect, + // otherwise the server type name (without the optional leading '*'; if that type no longer exists, + // parsing switches to autodetect); if 'lowMemory' is not NULL, TRUE is returned in it when memory is low; + // returns TRUE if the entire listing was parsed successfully and the object is populated with new items BOOL ParseListing(const char* pathListing, int pathListingLen, const CFTPDate& pathListingDate, CFTPServerPathType pathType, const char* welcomeReply, const char* systReply, const char* suggestedListingServerType, BOOL* lowMemory); @@ -3070,10 +3070,10 @@ struct CUploadPathListing // listing for a specific path on the server // WARNING: do not call directly, called through CUploadListingCache::ReportStoreFile() void ReportStoreFile(const char* name, BOOL* lowMem); - // see CUploadListingCache::ReportFileUploaded(); returns TRUE in 'lowMem' (must not be NULL) - // if there is not enough memory to add the change to the change queue (only in the - // ulsInProgress state) - // WARNING: do not call directly, called through CUploadListingCache::ReportFileUploaded() + // for a description, see CUploadListingCache::ReportFileUploaded(); 'lowMem' (must not be NULL) + // is set to TRUE if there is not enough memory to add the change to the change queue (only in + // the ulsInProgress state) + // WARNING: do not call directly; call through CUploadListingCache::ReportFileUploaded() void ReportFileUploaded(const char* name, const CQuadWord& fileSize, BOOL* lowMem); // applies the change 'change' to the listing; returns success (failure = the entire listing must be invalidated) @@ -3083,10 +3083,10 @@ struct CUploadPathListing // listing for a specific path on the server // to finish (or fail); returns FALSE only when memory is low BOOL AddWaitingWorker(int workerMsg, int workerUID); - // to all workers from the FirstWaitingWorker list: if 'uploadFirstWaitingWorker' is NULL, + // for all workers in the FirstWaitingWorker list: if 'uploadFirstWaitingWorker' is NULL, // WORKER_TGTPATHLISTINGFINISHED messages are sent; otherwise 'uploadFirstWaitingWorker' - // is the list where these workers should be added - // WARNING: if 'uploadFirstWaitingWorker' is NULL, must be called inside CSocketsThread::CritSect! + // is the list to which these workers should be added + // WARNING: if 'uploadFirstWaitingWorker' is NULL, this must be called inside CSocketsThread::CritSect void InformWaitingWorkers(CUploadWaitingWorker** uploadFirstWaitingWorker); private: @@ -3151,10 +3151,10 @@ struct CUploadListingsOnServer // listings of paths on a single server // see CUploadListingCache::IsListingFromPanel BOOL IsListingFromPanel(const char* path, CFTPServerPathType pathType); - // adds an empty listing for path 'path'+'dirName' of type 'pathType' with state 'listingState'; + // adds an empty listing for the path 'path'+'dirName' of type 'pathType' with state 'listingState'; // 'dirName' may also be NULL (a listing for the path 'path' is added); 'doNotCheckIfPathIsKnown' - // is TRUE if we know the path is not in the 'Listing' array; returns a pointer to the new - // listing on success, otherwise returns NULL + // is TRUE if we know the path is not in the 'Listings' array; returns a pointer to the new + // listing on success, otherwise NULL CUploadPathListing* AddEmptyListing(const char* path, const char* dirName, CFTPServerPathType pathType, CUploadListingState listingState, @@ -3195,8 +3195,8 @@ struct CUploadListingsOnServer // listings of paths on a single server // invalidates the listing at index 'index' (e.g. after an "unknown change" in this listing) void InvalidateListing(int index); - // see CUploadListingCache::GetListing() - // WARNING: do not call directly, called through CUploadListingCache::GetListing() + // for a description, see CUploadListingCache::GetListing() + // WARNING: do not call directly; call through CUploadListingCache::GetListing() BOOL GetListing(const char* path, CFTPServerPathType pathType, int workerMsg, int workerUID, BOOL* listingInProgress, BOOL* notAccessible, BOOL* getListing, const char* name, CUploadListingItem** existingItem, @@ -3230,18 +3230,19 @@ class CUploadListingCache ~CUploadListingCache(); // adds or updates a listing from the panel (before starting an upload operation and after a panel refresh - // during the upload operation); 'user'+'host'+'port' describes the server; 'path' is the - // local path on the server of type 'pathType'; 'pathListing'+'pathListingLen' is the listing text; - // 'pathListingDate' is the listing timestamp (needed for "year_or_time"); - // 'listingStartTime' is IncListingCounter() from the moment the LIST command was sent to the server - // (listing started); if 'onlyUpdate' is TRUE, only an update of a listing already in the cache is performed; - // 'welcomeReply' (must not be NULL) is the first server reply (often contains the FTP server version); - // 'systReply' (must not be NULL) is the server system (reply to the SYST command); - // 'suggestedListingServerType' is the server type for parsing the listing: - // NULL = autodetect, otherwise the server type name (without the optional leading '*'; if it stops existing, - // it switches to autodetect); returns FALSE if the listing cannot be parsed or if memory is low or parameters are invalid; - // returns TRUE if the listing was added or updated or was not updated because 'onlyUpdate'==TRUE or because - // an update is not needed (i.e. returns TRUE if the cached path listing can be used) + // during an upload operation); 'user'+'host'+'port' describes the server; 'path' is the + // local path on the server of type 'pathType'; 'pathListing'+'pathListingLen' is the listing + // text; 'pathListingDate' is the date when the listing was obtained (needed for "year_or_time"); + // 'listingStartTime' is IncListingCounter() from the moment the LIST command was sent to the + // server (listing start); if 'onlyUpdate' is TRUE, only a listing already in the cache is + // updated; 'welcomeReply' (must not be NULL) is the first server reply (often containing the + // FTP server version); 'systReply' (must not be NULL) is the server system reply (reply to the + // SYST command); 'suggestedListingServerType' is the server type for parsing the listing: + // NULL = autodetection, otherwise the server type name (without an optional leading '*'; if it + // no longer exists, it switches to autodetection); returns FALSE if the listing cannot be + // parsed, on out-of-memory, or on invalid parameters; returns TRUE if the listing was added or + // updated, or was not updated because 'onlyUpdate'==TRUE or because no update is needed (i.e. + // returns TRUE if the cached path listing can be used) BOOL AddOrUpdateListing(const char* user, const char* host, unsigned short port, const char* path, CFTPServerPathType pathType, const char* pathListing, int pathListingLen, @@ -3313,19 +3314,18 @@ class CUploadListingCache void ReportUnknownChange(const char* user, const char* host, unsigned short port, const char* workPath, CFTPServerPathType pathType); - // obtaining the listing of path 'path' (of type 'pathType') on server 'user'+'host'+'port' - // from the cache - if it is not yet in the cache, it is added; if it is already being fetched, we wait; - // if the path is not in the cache, it is added in the ulsInProgress state, returns TRUE in 'getListing' - // and TRUE in 'listingInProgress'; if the path listing is "unobtainable", returns TRUE - // in 'notAccessible' and FALSE in 'listingInProgress'; if the path is in the cache - // in one of the ulsInProgress* states, returns FALSE in 'getListing', TRUE - // in 'listingInProgress', and after the listing download finishes (or fails) - // posts WORKER_TGTPATHLISTINGFINISHED to worker 'workerMsg'+'workerUID'; - // if the path is in the cache in the ulsReady state, returns FALSE in 'notAccessible', - // FALSE in 'listingInProgress', returns the item named 'name' in the allocated - // structure 'existingItem' (NULL if an item with that name was not found), - // and TRUE/FALSE in 'nameExists' depending on whether an item named 'name' was found; - // returns FALSE only when memory is low + // obtains the listing of path 'path' (of type 'pathType') on server 'user'+'host'+'port' + // from the cache - if it is not yet in the cache, it is added; if it is already being fetched, + // the caller waits; if the path is not in the cache, it is added in the ulsInProgress state, + // returns TRUE in 'getListing' and TRUE in 'listingInProgress'; if the path listing is + // "unobtainable", it returns TRUE in 'notAccessible' and FALSE in 'listingInProgress'; if the + // path is in the cache in one of the ulsInProgress* states, it returns FALSE in 'getListing', + // TRUE in 'listingInProgress', and after the listing download finishes (or on failure) it posts + // WORKER_TGTPATHLISTINGFINISHED to worker 'workerMsg'+'workerUID'; if the path is in the cache + // in the ulsReady state, it returns FALSE in 'notAccessible', FALSE in 'listingInProgress', + // returns the item named 'name' in the allocated structure 'existingItem' (NULL if no item + // with that name was found), and TRUE/FALSE in 'nameExists' depending on whether an item + // named 'name' was found; returns FALSE only on out-of-memory BOOL GetListing(const char* user, const char* host, unsigned short port, const char* path, CFTPServerPathType pathType, int workerMsg, int workerUID, BOOL* listingInProgress, BOOL* notAccessible, @@ -3411,8 +3411,8 @@ class CFTPOpenedFile const char* path, CFTPServerPathType pathType, const char* name, CFTPFileAccessType accessType); - // compares this opened file with the file specified by the method parameters; returns TRUE if - // it is the same file + // compares this open file with the file specified by the method parameters; returns TRUE if + // they are the same file BOOL IsSameFile(const char* user, const char* host, unsigned short port, const char* path, CFTPServerPathType pathType, const char* name); diff --git a/src/plugins/ftp/operats1.cpp b/src/plugins/ftp/operats1.cpp index 50e7dc172..ca0b3b4dd 100644 --- a/src/plugins/ftp/operats1.cpp +++ b/src/plugins/ftp/operats1.cpp @@ -139,7 +139,7 @@ void CFTPOperationsList::DeleteOperation(int uid, BOOL doNotPostChangeOnPathNoti if (FirstFreeIndexInOperations >= Operations.Count) FirstFreeIndexInOperations = -1; } - else // deleting inside the array, no array deallocation is possible + else // deletion inside the array; no array deallocation is possible { if (FirstFreeIndexInOperations == -1 || uid < FirstFreeIndexInOperations) FirstFreeIndexInOperations = uid; @@ -150,7 +150,7 @@ void CFTPOperationsList::DeleteOperation(int uid, BOOL doNotPostChangeOnPathNoti HANDLES(LeaveCriticalSection(&OpListCritSect)); // if an upload operation was canceled and no other upload operation is working with - // the server used by the canceled operation, we can release this server from the upload + // the server used by the canceled operation, we can release that server from the upload // listing cache if (uploadOperDeleted && !IsUploadingToServer(uploadUser, uploadHost, uploadPort)) UploadListingCache.RemoveServer(uploadUser, uploadHost, uploadPort); @@ -171,7 +171,7 @@ void CFTPOperationsList::CloseAllOperationDlgs() oper->CloseOperationDlg(&t); if (t != NULL) { - HANDLES(LeaveCriticalSection(&OpListCritSect)); // we must leave the section; the dialog thread calls CFTPOperationsList::SetOperationDlg() + HANDLES(LeaveCriticalSection(&OpListCritSect)); // we must leave the critical section; the dialog thread calls CFTPOperationsList::SetOperationDlg() CALL_STACK_MESSAGE1("AuxThreadQueue.WaitForExit()"); AuxThreadQueue.WaitForExit(t, INFINITE); HANDLES(EnterCriticalSection(&OpListCritSect)); @@ -211,7 +211,7 @@ void CFTPOperationsList::WaitForFinishOrESC(HWND parent, int milliseconds, CWait waitTime = cycleTime; DWORD waitRes = MsgWaitForMultipleObjects(1, &WorkerMayBeClosedEvent, FALSE, waitTime, QS_ALLINPUT); - // check the ESC key first (so we do not ignore it for the user) + // check for ESC first (so we do not ignore the user's key press) if (milliseconds != 0 && // if the timeout is zero we are only pumping messages, do not handle ESC ((GetAsyncKeyState(VK_ESCAPE) & 0x8001) && GetForegroundWindow() == parent || // ESC pressed waitWnd != NULL && waitWnd->GetWindowClosePressed())) // close button in the wait window @@ -222,7 +222,7 @@ void CFTPOperationsList::WaitForFinishOrESC(HWND parent, int milliseconds, CWait reason = wwsrEsc; break; // report ESC } - if (waitRes != WAIT_OBJECT_0) // no additional worker was closed (we ignore this event; it only "wakes" the waiting) + if (waitRes != WAIT_OBJECT_0) // no additional worker was closed (we ignore this event; it only wakes the wait) { if (waitRes == WAIT_OBJECT_0 + 1) // process Windows messages { @@ -247,11 +247,11 @@ void CFTPOperationsList::WaitForFinishOrESC(HWND parent, int milliseconds, CWait restOfWaitTime == waitTime) // this is not just the ESC key test cycle timeout but the global timeout { reason = wwsrTimeout; - break; // report the timeout + break; // indicate a timeout } } } - if (milliseconds != INFINITE) // recalculate the remaining wait time (according to real time) + if (milliseconds != INFINITE) // recalculate the remaining wait time based on actual elapsed time { DWORD t = GetTickCount() - timeStart; // works even when the tick counter overflows if (t < (DWORD)milliseconds) @@ -269,7 +269,7 @@ void CFTPOperationsList::StopWorkers(HWND parent, int operUID, int workerInd) CALL_STACK_MESSAGE3("CFTPOperationsList::StopWorkers(, %d, %d)", operUID, workerInd); parent = FindPopupParent(parent); - // remember the focus from 'parent' (store NULL if the focus is not within 'parent') + // remember the focused window in 'parent' (store NULL if the focus is not within 'parent') HWND focusedWnd = GetFocus(); HWND hwnd = focusedWnd; while (hwnd != NULL && hwnd != parent) @@ -320,7 +320,7 @@ void CFTPOperationsList::StopWorkers(HWND parent, int operUID, int workerInd) for (i = 0; i < count; i++) victims[i]->CloseDataConnectionOrPostShouldStop(); if (done) - break; // all operations reported they do not want another call + break; // all operations reported they do not want any further calls } // ensure that the "elapsed time" stops in the operation dialogs of the halted operations @@ -400,9 +400,9 @@ void CFTPOperationsList::StopWorkers(HWND parent, int operUID, int workerInd) // case wwsrWorkerSocketClosure: break; // only check whether all worker sockets are already closed } - if (terminate) // cancel or timeout, force workers to finish quickly and continue waiting for them to end + if (terminate) // cancel or timeout, force workers to terminate quickly and continue waiting for them to finish { - lastOpIndex = 0; // optimization (index of the last processed operation - start with it in the next round) + lastOpIndex = 0; // optimization (index of the last processed operation - start from it in the next round) while (1) { BOOL done = TRUE; @@ -435,7 +435,7 @@ void CFTPOperationsList::StopWorkers(HWND parent, int operUID, int workerInd) for (i = 0; i < count; i++) victims[i]->ForceClose(); if (done) - break; // all operations reported they do not want another call + break; // all operations reported that they do not want any further calls } } @@ -516,7 +516,7 @@ void CFTPOperationsList::StopWorkers(HWND parent, int operUID, int workerInd) for (i = 0; i < count; i++) DeleteSocket(victims[i]); if (done) - break; // all operations reported they do not want another call + break; // all operations reported that they do not want another call } Logs.RefreshListOfLogsInLogsDlg(); // refresh the Log - workers are closed @@ -1061,10 +1061,10 @@ int CFTPQueue::GetUserInputNeededCount(BOOL onlyUINeeded, TDirectArray* U if (item->UID == focusedItemUID) { *indexInAll = i; - if (item->GetItemState() >= sqisSkipped /* sqisSkipped, sqisFailed, sqisForcedToFail nebo sqisUserInputNeeded */) + if (item->GetItemState() >= sqisSkipped /* sqisSkipped, sqisFailed, sqisForcedToFail, or sqisUserInputNeeded */) *indexInUIN = c; } - if (item->GetItemState() >= sqisSkipped /* sqisSkipped, sqisFailed, sqisForcedToFail nebo sqisUserInputNeeded */) + if (item->GetItemState() >= sqisSkipped /* sqisSkipped, sqisFailed, sqisForcedToFail, or sqisUserInputNeeded */) { if (onlyUINeeded) UINeededArr->Add(i); @@ -1526,7 +1526,7 @@ int CFTPQueue::RetryItem(int UID, CFTPOperation* oper) ret = LastFoundIndex; found->ChangeStateAndCounters(newState, oper, this); if (found->ProblemID == ITEMPR_UNABLETORESUME) - oper->SetResumeIsNotSupported(FALSE); // so Retry makes any sense at all + oper->SetResumeIsNotSupported(FALSE); // so that Retry makes sense at all oper->SetSizeCmdIsSupported(TRUE); // so that the SIZE command is tried again if needed found->ProblemID = ITEMPR_OK; found->WinError = NO_ERROR; @@ -1535,7 +1535,7 @@ int CFTPQueue::RetryItem(int UID, CFTPOperation* oper) SalamanderGeneral->Free(found->ErrAllocDescr); found->ErrAllocDescr = NULL; } - found->ForceAction = fqiaNone; // to ensure Autorename is not performed instead of Retry + found->ForceAction = fqiaNone; // so that, for example, Autorename is not performed instead of Retry } else TRACE_I("CFTPQueue::RetryItem(): cannot retry item because it's not in any of error states!"); @@ -2190,7 +2190,7 @@ int CFTPQueue::SolveErrorOnItem(HWND parent, int UID, CFTPOperation* oper) case 45: // upload: unable to resume (Copy/Move) - server does not support resuming case 46: // upload: unable to resume the file because the target file size is unknown case 47: // upload: unable to resume the file because the target file is larger than the source file - case 51: // issue "unable to verify whether the file was uploaded successfully" (we sent the entire file and the server simply did not respond; the file is most likely OK but we cannot test it - reasons: ASCII transfer mode or we do not have the size in bytes (neither listing nor the SIZE command)) + case 51: // issue "unable to verify whether the file was uploaded successfully" (we sent the entire file and the server simply did not respond; the file is most likely OK, but we cannot verify it - reasons: ASCII transfer mode or we do not have the size in bytes (neither from a listing nor from the SIZE command)) { CSolveServerCmdErr2 dlg(parent, openDlgWithID == 21 || openDlgWithID == 22 || openDlgWithID == 44 || @@ -2266,7 +2266,7 @@ int CFTPQueue::SolveErrorOnItem(HWND parent, int UID, CFTPOperation* oper) } } - if (dlgResult != IDCANCEL) // store the values entered by the user in the item + if (dlgResult != IDCANCEL) // store the user-entered values in the item { HANDLES(EnterCriticalSection(&QueueCritSect)); found = FindItemWithUID(UID); @@ -2348,7 +2348,7 @@ int CFTPQueue::SolveErrorOnItem(HWND parent, int UID, CFTPOperation* oper) } if (openDlgWithID == 12 && (item->Type == fqitUploadCopyExploreDir || item->Type == fqitUploadMoveExploreDir)) - { // invalidate the target path listing (if an outdated listing containing the target directory is used, CWD into this directory reports "path not found" - with an up-to-date listing the directory is created via MKD) + { // invalidate the target path listing (if an outdated listing containing the target directory is used, CWD to this directory returns "path not found"; with an up-to-date listing, the directory is created via MKD) CFTPQueueItemCopyMoveUploadExplore* curItem = (CFTPQueueItemCopyMoveUploadExplore*)item; UpdateUploadTgtDirState(curItem, UPLOADTGTDIRSTATE_UNKNOWN); oper->GetUserHostPort(userBuf, hostBuf, &portBuf); @@ -2356,7 +2356,7 @@ int CFTPQueue::SolveErrorOnItem(HWND parent, int UID, CFTPOperation* oper) UploadListingCache.InvalidatePathListing(userBuf, hostBuf, portBuf, curItem->TgtPath, pathType); } if (found->ProblemID == ITEMPR_UNABLETORESUME) - oper->SetResumeIsNotSupported(FALSE); // so Retry makes any sense at all + oper->SetResumeIsNotSupported(FALSE); // so that Retry makes sense at all item->ProblemID = ITEMPR_OK; item->WinError = NO_ERROR; if (item->ErrAllocDescr != NULL) @@ -2459,7 +2459,7 @@ int CFTPQueue::SolveErrorOnItem(HWND parent, int UID, CFTPOperation* oper) ((CFTPQueueItemChAttrDir*)item)->AttrErr = FALSE; // fqitChAttrsDir } - if (dlgResult == CM_SIEA_SETNEWATTRS) // wants to set a new attribute value + if (dlgResult == CM_SIEA_SETNEWATTRS) // set a new attribute value { if (item->Type == fqitChAttrsFile) { @@ -2501,11 +2501,11 @@ int CFTPQueue::SolveErrorOnItem(HWND parent, int UID, CFTPOperation* oper) break; } - case fqitDeleteExploreDir: // explore a directory for delete (note: directory links are removed as a whole, the operation objective is met and nothing "extra" is deleted) (object of class CFTPQueueItemDelExplore) + case fqitDeleteExploreDir: // explore a directory for a delete operation (note: links to directories are deleted as a whole; the purpose of the operation is achieved and nothing "extra" is deleted) (object of class CFTPQueueItemDelExplore) case fqitDeleteLink: // delete for a link (object of class CFTPQueueItemDel) case fqitDeleteFile: // delete for a file (object of class CFTPQueueItemDel) { - if (openDlgWithID == 9 || // delete directory error: the directory is hidden (more a confirmation than an error) + if (openDlgWithID == 9 || // delete directory error: the directory is hidden (more of a confirmation than an error) openDlgWithID == 10 || // delete file or link error: the file is hidden (more a confirmation than an error) openDlgWithID == 11) // delete directory error: the directory is not empty (more a confirmation than an error) { @@ -2529,7 +2529,7 @@ int CFTPQueue::SolveErrorOnItem(HWND parent, int UID, CFTPOperation* oper) { if (openDlgWithID == 9) // error: hidden directory ((CFTPQueueItemDelExplore*)item)->IsHiddenDir = FALSE; - else // error: directory not empty + else // error: non-empty directory ((CFTPQueueItemDelExplore*)item)->IsTopLevelDir = FALSE; break; } @@ -2544,7 +2544,7 @@ int CFTPQueue::SolveErrorOnItem(HWND parent, int UID, CFTPOperation* oper) item->ChangeStateAndCounters(sqisWaiting, oper, this); item->ProblemID = ITEMPR_OK; item->WinError = NO_ERROR; - if (item->ErrAllocDescr != NULL) // just to be safe (probably not needed) + if (item->ErrAllocDescr != NULL) // as a precaution (probably not needed) { SalamanderGeneral->Free(item->ErrAllocDescr); item->ErrAllocDescr = NULL; @@ -2723,7 +2723,7 @@ int CFTPQueue::SolveErrorOnItem(HWND parent, int UID, CFTPOperation* oper) { case IDOK: item->ForceAction = fqiaNone; - break; // to make sure Retry is performed and not, for example, Autorename + break; // to ensure Retry is used instead of, for example, Autorename case CM_SCRD_USEALTNAME: item->ForceAction = fqiaUseAutorename; break; // force Autorename on the next attempt @@ -2823,7 +2823,7 @@ void CFTPQueue::UpdateItemState(CFTPQueueItem* item, CFTPQueueItemState state, D else { if (errAllocDescr != NULL) - free(errAllocDescr); // there is nowhere to store the value, so at least free it + free(errAllocDescr); // no place to store the value, so at least free it } HANDLES(LeaveCriticalSection(&QueueCritSect)); } @@ -3226,7 +3226,7 @@ BOOL CFTPQueue::SearchItemWithNewError(int* itemUID, int* itemIndex) CALL_STACK_MESSAGE1("CFTPQueue::SearchItemWithNewError()"); HANDLES(EnterCriticalSection(&QueueCritSect)); BOOL res = FALSE; - if (LastFoundErrorOccurenceTime + 1 < LastErrorOccurenceTime + 1) // +1 is here because -1 is used as the initial value + if (LastFoundErrorOccurenceTime + 1 < LastErrorOccurenceTime + 1) // +1 is here because -1 is used as the initial values { // it makes sense to search int foundUID = -1; int foundIndex = -1; @@ -3239,7 +3239,7 @@ BOOL CFTPQueue::SearchItemWithNewError(int* itemUID, int* itemIndex) if (item->IsItemInSimpleErrorState() && item->HasErrorToSolve(NULL, NULL)) itemErrorOccurenceTime = item->ErrorOccurenceTime; if (itemErrorOccurenceTime != -1 && // the item contains an error - itemErrorOccurenceTime >= LastFoundErrorOccurenceTime + 1 && // it is a "new" error + itemErrorOccurenceTime >= LastFoundErrorOccurenceTime + 1 && // this is a "new" error (foundUID == -1 || foundErrorOccurenceTime > itemErrorOccurenceTime)) // so far the first found or the "oldest" (we resolve errors in the order they occurred) { foundErrorOccurenceTime = itemErrorOccurenceTime; @@ -3525,7 +3525,7 @@ void CFTPQueue::ReturnToWaitingItems(CFTPQueueItem* item, CFTPOperation* oper) BOOL exploreOrResolve = item->IsExploreOrResolveItem(); if (exploreOrResolve || !GetOnlyExploreAndResolveItems) { - FirstWaitingItemIndex = 0; // we will not determine the index of the returned item (computationally as difficult as finding the first "waiting" item - which is done only once, unlike calling this function) + FirstWaitingItemIndex = 0; // we will not determine the index of the returned item (that is as computationally expensive as finding the first "waiting" item, which is done only once, unlike calls to this function) if (exploreOrResolve) GetOnlyExploreAndResolveItems = TRUE; } diff --git a/src/plugins/ftp/operats2.cpp b/src/plugins/ftp/operats2.cpp index 432c22d22..c37592c2c 100644 --- a/src/plugins/ftp/operats2.cpp +++ b/src/plugins/ftp/operats2.cpp @@ -30,8 +30,8 @@ class COperationDlgThread : public CThread CALL_STACK_MESSAGE1("COperationDlgThread::Body()"); // 'sendWMClose': the dialog sets it to TRUE when WM_CLOSE is received - // when a modal dialog above the operation dialog is open - once that - // modal dialog closes, WM_CLOSE is sent again to the operation dialog + // while a modal dialog is open over the operation dialog - once that + // modal dialog closes, WM_CLOSE is sent to the operation dialog again BOOL sendWMClose = FALSE; OperDlg->SendWMClose = &sendWMClose; if (OperDlg->Create() == NULL || OperDlg->CloseDlg) @@ -44,7 +44,7 @@ class COperationDlgThread : public CThread else { HWND dlg = OperDlg->HWindow; // safely stored window handle (valid even after OperDlg is destroyed) - if (AlwaysOnTop) // handle always-on-top at least "statically" (it's not in the system menu) + if (AlwaysOnTop) // handle always-on-top at least statically (it is not in the system menu) SetWindowPos(dlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); SetForegroundWindow(dlg); @@ -91,7 +91,7 @@ BOOL CFTPOperation::SetConnection(CFTPProxyServer* proxyServer, const char* host BOOL err = (host == NULL || *host == 0); Host = SalamanderGeneral->DupStr(host); Port = port; - User = SalamanderGeneral->DupStr((user != NULL && *user == 0) ? NULL : user); // remains NULL if it is NULL + User = SalamanderGeneral->DupStr((user != NULL && *user == 0) ? NULL : user); // remains NULL if user is NULL Password = SalamanderGeneral->DupStr((password != NULL && *password == 0) ? NULL : password); Account = SalamanderGeneral->DupStr((account != NULL && *account == 0) ? NULL : account); InitFTPCommands = SalamanderGeneral->DupStr((initFTPCommands != NULL && *initFTPCommands == 0) ? NULL : initFTPCommands); @@ -119,7 +119,7 @@ BOOL CFTPOperation::SetConnection(CFTPProxyServer* proxyServer, const char* host { ProxyScriptText = GetProxyScriptText(proxyType, FALSE); if (ProxyScriptText[0] == 0) - ProxyScriptText = GetProxyScriptText(fpstNotUsed, FALSE); // undefined script = "not used (direct connection)" script - SOCKS 4/4A/5, HTTP 1.1 + ProxyScriptText = GetProxyScriptText(fpstNotUsed, FALSE); // undefined script means the "not used (direct connection)" script for SOCKS 4/4A/5 and HTTP 1.1 } if (!err) { @@ -131,7 +131,7 @@ BOOL CFTPOperation::SetConnection(CFTPProxyServer* proxyServer, const char* host &proxyScriptParams, connectToHost, &ConnectToPort, NULL, NULL, errBuf, NULL)) { - if (proxyScriptParams.NeedUserInput()) // theoretically should not happen (already verified by running it in the panel) + if (proxyScriptParams.NeedUserInput()) // this should theoretically never happen (already verified by running it in the panel) { err = TRUE; TRACE_E("CFTPOperation::SetConnection(): unexpected situation: proxy script needs user input!"); @@ -153,7 +153,7 @@ void CFTPOperation::SetBasicData(char* operationSubject, const char* listingServ CALL_STACK_MESSAGE1("CFTPOperation::SetBasicData()"); OperationSubject = SalamanderGeneral->DupStr(operationSubject); - ListingServerType = SalamanderGeneral->DupStr(listingServerType); // remains NULL if it is NULL + ListingServerType = SalamanderGeneral->DupStr(listingServerType); // remains NULL if user is NULL } void CFTPOperation::SetOperationDelete(const char* sourcePath, char srcPathSeparator, @@ -426,7 +426,7 @@ void CFTPOperation::AddToNotDoneSkippedFailed(int notDone, int skipped, int fail { BOOL softRefresh = state == opstFinishedWithErrors || // FIXME: once a window with the operation queue exists, we must replace OperationDlg->DlgWillCloseIfOpFinWithSkips with a different detection of whether the worker closes (passing the connection back to the panel) state == opstFinishedWithSkips && (OperationDlg != NULL ? !OperationDlg->DlgWillCloseIfOpFinWithSkips : TRUE); - PostChangeOnPathNotifications(softRefresh); // the line is free now (at least for this operation), so we can afford listing refreshes + PostChangeOnPathNotifications(softRefresh); // the connection is free now (at least for this operation), so we can afford to refresh the listing } HANDLES(LeaveCriticalSection(&OperCritSect)); } @@ -517,7 +517,7 @@ BOOL CFTPOperation::ActivateOperationDlg(HWND dropTargetWnd) else ret = TRUE; // success } - else // low memory, error + else // out of memory, error { delete OperationDlg; OperationDlg = NULL; @@ -528,7 +528,7 @@ BOOL CFTPOperation::ActivateOperationDlg(HWND dropTargetWnd) } } else - TRACE_E(LOW_MEMORY); // low memory, error + TRACE_E(LOW_MEMORY); // out of memory, error } HANDLES(LeaveCriticalSection(&OperCritSect)); return ret; @@ -849,7 +849,7 @@ BOOL CFTPOperation::PrepareNextScriptCmd(char* buf, int bufSize, char* logBuf, i char proxyLogCmdBuf[FTPCOMMAND_MAX_SIZE]; BOOL ret = TRUE; if (*proxyScriptExecPoint == NULL) - *proxyScriptExecPoint = ProxyScriptStartExecPoint; // we should prepare the first script command + *proxyScriptExecPoint = ProxyScriptStartExecPoint; // prepare the first script command if (ProcessProxyScript(ProxyScriptText, proxyScriptExecPoint, proxyScriptLastCmdReply, &proxyScriptParams, NULL, NULL, proxySendCmdBuf, proxyLogCmdBuf, errDescrBuf, NULL)) @@ -860,7 +860,7 @@ BOOL CFTPOperation::PrepareNextScriptCmd(char* buf, int bufSize, char* logBuf, i int resID = 0; if (proxyScriptParams.NeedProxyHost) { - resID = IDS_WORKERUNKNOWNPROXYHOST; // we do say we need it, but the user cannot provide it - if it is ever required (should not happen yet because the login in the panel succeeded even without ProxyHost, so it likely will not be needed here either), add a dialog for entering ProxyHost... + resID = IDS_WORKERUNKNOWNPROXYHOST; // we indicate that it is required, but the user cannot enter it; if that ever becomes necessary (it should not for now, because login in the panel already succeeded without ProxyHost, so it is not expected here either), add a dialog for entering ProxyHost... TRACE_E("CFTPOperation::PrepareNextScriptCmd(): unexpected situation: ProxyHost is empty!"); } if (proxyScriptParams.NeedProxyPassword) @@ -1500,7 +1500,7 @@ void CFTPOperation::SetCertificate(CCertificate* certificate) CALL_STACK_MESSAGE1("CFTPOperation::SetCertificate()"); HANDLES(EnterCriticalSection(&OperCritSect)); - CCertificate* old = pCertificate; // ensures AddRef is called via Release (in case pCertificate == certificate) + CCertificate* old = pCertificate; // ensures AddRef is called before Release (in case pCertificate == certificate) pCertificate = certificate; if (pCertificate) pCertificate->AddRef(); @@ -1684,7 +1684,7 @@ void CFTPOperation::PostNewWorkAvailable(BOOL onlyOneItem) BOOL CFTPOperation::GiveWorkToSleepingConWorker(CFTPWorker* sourceWorker) { CALL_STACK_MESSAGE1("CFTPOperation::GiveWorkToSleepingConWorker()"); - return WorkersList.GiveWorkToSleepingConWorker(sourceWorker); // synchronization is inside WorkersList (the OperCritSect section is not needed here) + return WorkersList.GiveWorkToSleepingConWorker(sourceWorker); // synchronization is handled within WorkersList (the OperCritSect section is not needed here) } CFTPServerPathType @@ -2107,7 +2107,7 @@ void CFTPQueueItem::SetItem(int parentUID, CFTPQueueItemType type, CFTPQueueItem BOOL CFTPQueueItem::HasErrorToSolve(BOOL* canSkip, BOOL* canRetry) { - BOOL solvableErr = ProblemID != ITEMPR_INVALIDPATHTODIR && // not an unsolvable problem (no Retry can help) + BOOL solvableErr = ProblemID != ITEMPR_INVALIDPATHTODIR && // not an unsolvable problem (where Retry cannot help) ProblemID != ITEMPR_DIREXPLENDLESSLOOP && ProblemID != ITEMPR_INVALIDPATHTOLINK; if (canSkip != NULL) @@ -2240,7 +2240,7 @@ void CFTPQueueItem::GetProblemDescr(char* buf, int bufSize) } if (attrs == NULL) attrs = LoadStr(IDS_OPERDOPPR_UNKEXISTATTR); - _snprintf_s(buf, bufSize, _TRUNCATE, LoadStr(IDS_OPERDOPPR_UNKNOWNATTRS), attrs); // attrs might even be NULL (on error); sprintf can cope with that + _snprintf_s(buf, bufSize, _TRUNCATE, LoadStr(IDS_OPERDOPPR_UNKNOWNATTRS), attrs); // attrs might even be NULL (on failure); _snprintf_s can cope with that break; } @@ -2548,7 +2548,7 @@ void CFTPQueueItemAncestor::ChangeStateAndCounters(CFTPQueueItemState state, CFT break; } } - queue->UpdateCounters((CFTPQueueItem*)this, FALSE); // handle the state change by virtually removing the item and adding it back after the state changes + queue->UpdateCounters((CFTPQueueItem*)this, FALSE); // handle the state change by virtually removing the item and adding it back after the state change State = state; queue->UpdateCounters((CFTPQueueItem*)this, TRUE); if (((CFTPQueueItem*)this)->IsItemInSimpleErrorState()) @@ -2591,7 +2591,7 @@ void CFTPQueueItemDir::SetStateAndNotDoneSkippedFailed(int childItemsNotDone, in ChildItemsSkipped = childItemsSkipped; ChildItemsFailed = childItemsFailed; ChildItemsUINeeded = childItemsUINeeded; - if (GetItemState() == sqisWaiting) // if the item is ready to process, check whether + if (GetItemState() == sqisWaiting) // if the item is ready to process, check whether it needs to be delayed or must fail because of child items { // it needs to be delayed or must fail because of child items if (ChildItemsNotDone - ChildItemsSkipped - ChildItemsFailed - ChildItemsUINeeded > 0) SetStateInternal(sqisDelayed); diff --git a/src/plugins/ftp/operats3.cpp b/src/plugins/ftp/operats3.cpp index 0a7f91cd6..c8cd87963 100644 --- a/src/plugins/ftp/operats3.cpp +++ b/src/plugins/ftp/operats3.cpp @@ -124,7 +124,7 @@ CFTPWorker::CFTPWorker(CFTPOperation* oper, CFTPQueue* queue, const char* host, UploadType = utNone; UseDeleteForOverwrite = FALSE; - if (Config.EnableLogging && !Config.DisableLoggingOfWorkers) // without synchronization, not needed + if (Config.EnableLogging && !Config.DisableLoggingOfWorkers) // no synchronization needed { Logs.CreateLog(&LogUID, host, port, user, NULL, FALSE, TRUE); Oper->SendHeaderToLog(LogUID); @@ -788,7 +788,7 @@ BOOL CFTPWorker::InformAboutStop() ret = TRUE; } else - { // if a "data-connection" exists and we are not waiting for the server connection, we need to close the "data-connection" + { // if a "data-connection" exists and we are not waiting for the server connection, we need to close it ret = WorkerDataConState == wdcsOnlyAllocated || WorkerDataConState == wdcsTransferingData || WorkerDataConState == wdcsTransferFinished; } @@ -829,7 +829,7 @@ void CFTPWorker::CloseDataConnectionOrPostShouldStop() if (workerDataCon->IsConnected()) // close the "data connection"; the system will attempt a "graceful" shutdown { workerDataCon->CloseSocketEx(NULL); // shutdown (we do not learn the result) - postShouldStop = TRUE; // we must "get the worker moving" so it terminates (WORKER_DATACON_CLOSED will not arrive) + postShouldStop = TRUE; // we must wake the worker so it terminates (WORKER_DATACON_CLOSED will not arrive) } workerDataCon->FreeFlushData(); DeleteSocket(workerDataCon); @@ -839,7 +839,7 @@ void CFTPWorker::CloseDataConnectionOrPostShouldStop() if (workerUploadDataCon->IsConnected()) // close the "data connection"; the system will attempt a "graceful" shutdown { workerUploadDataCon->CloseSocketEx(NULL); // shutdown (we do not learn the result) - postShouldStop = TRUE; // we must "get the worker moving" so it terminates (WORKER_UPLDATACON_CLOSED will not arrive) + postShouldStop = TRUE; // we must wake the worker so it terminates (WORKER_UPLDATACON_CLOSED will not arrive) } workerUploadDataCon->FreeBufferedData(); DeleteSocket(workerUploadDataCon); @@ -995,7 +995,7 @@ void CFTPWorker::ForceClose() void CFTPWorker::ForceCloseDiskWork() { CALL_STACK_MESSAGE1("CFTPWorker::ForceCloseDiskWork()"); - // WARNING: may be called repeatedly (see calls from CFTPWorkersList::ForceCloseWorkers()) + // WARNING: this may be called repeatedly (see CFTPWorkersList::ForceCloseWorkers()) HANDLES(EnterCriticalSection(&WorkerCritSect)); if (DiskWorkIsUsed) { @@ -1079,7 +1079,7 @@ void CFTPWorker::ReleaseData(CUploadWaitingWorker** uploadFirstWaitingWorker) case fwssWorkDelDirWaitForRMDRes: case fwssWorkCopyMoveWaitForDELERes: { - // if we do not know how deleting the file/link/directory ended, invalidate the listing in the cache + // if we do not know how the file/link/directory deletion ended, invalidate the cached listing Oper->GetUserHostPort(userBuf, hostBuf, &port); UploadListingCache.ReportDelete(userBuf, hostBuf, port, CurItem->Path, Oper->GetFTPServerPathType(CurItem->Path), @@ -1129,7 +1129,7 @@ void CFTPWorker::ReleaseData(CUploadWaitingWorker** uploadFirstWaitingWorker) // except when STOR reports "cannot create target file name" (i.e. STOR reports an error and nothing was uploaded) we consider sending the STOR/APPE command as completion // forced actions: "overwrite", "resume", and "resume or overwrite" - if (CurItem->ForceAction != fqiaNone) // the forced action stops applying + if (CurItem->ForceAction != fqiaNone) // the forced action no longer applies Queue->UpdateForceAction(CurItem, fqiaNone); } break; @@ -1140,7 +1140,7 @@ void CFTPWorker::ReleaseData(CUploadWaitingWorker** uploadFirstWaitingWorker) { if (CurItem->Type == fqitUploadCopyFile || CurItem->Type == fqitUploadMoveFile) // "always true" { - // if we do not know how deleting the file/link/directory ended, invalidate the listing in the cache + // if we do not know how the file/link/directory deletion ended, invalidate the cached listing Oper->GetUserHostPort(userBuf, hostBuf, &port); CFTPQueueItemCopyOrMoveUpload* curItem = (CFTPQueueItemCopyOrMoveUpload*)CurItem; UploadListingCache.ReportDelete(userBuf, hostBuf, port, curItem->TgtPath, @@ -1156,7 +1156,7 @@ void CFTPWorker::ReleaseData(CUploadWaitingWorker** uploadFirstWaitingWorker) ((CFTPQueueItemCopyOrMoveUpload*)CurItem)->RenamedName != NULL) { if (State == fwsWorking && SubState == fwssWorkUploadWaitForSTORRes) - Queue->ChangeTgtNameToRenamedName((CFTPQueueItemCopyOrMoveUpload*)CurItem); // even if STOR has not yet run, it is still more accurate that the file was stored under the new name than under the original one - obvious for overwriting an existing file + Queue->ChangeTgtNameToRenamedName((CFTPQueueItemCopyOrMoveUpload*)CurItem); // even if STOR has not run yet, it is still more accurate that the file is being stored under the new name than under the original one; this is obvious when overwriting an existing file else Queue->UpdateRenamedName((CFTPQueueItemCopyOrMoveUpload*)CurItem, NULL); } @@ -1542,13 +1542,13 @@ BOOL CFTPWorker::Write(const char* buffer, int bytesToWrite, DWORD* error, BOOL* { if (error != NULL) *error = err; - break; // return the error + break; // return an error } } } } - if (ret) // successfully sent; 'len' is the number of sent bytes (the rest will be sent after FD_WRITE) + if (ret) // send succeeded; 'len' is the number of bytes sent (the rest will be sent after FD_WRITE) { if (allBytesWritten != NULL) *allBytesWritten = (len >= bytesToWrite); @@ -1581,7 +1581,7 @@ BOOL CFTPWorker::Write(const char* buffer, int bytesToWrite, DWORD* error, BOOL* } } } - else // not everything was sent yet -> incorrect use of Write + else // not everything has been sent yet -> incorrect use of Write { TRACE_E("Incorrect use of CFTPWorker::Write(): called again before waiting for fwseWriteDone event."); } @@ -1640,7 +1640,7 @@ void CFTPWorker::ReceiveHostByAddress(DWORD ip, int hostUID, int err) void CFTPWorker::ReceiveNetEvent(LPARAM lParam, int index) { CALL_STACK_MESSAGE3("CFTPWorker::ReceiveNetEvent(0x%IX, %d)", lParam, index); - DWORD eventError = WSAGETSELECTERROR(lParam); // extract error code of event + DWORD eventError = WSAGETSELECTERROR(lParam); // extract the event error code switch (WSAGETSELECTEVENT(lParam)) // extract event { case FD_CLOSE: // sometimes arrives before the last FD_READ, so we must first try FD_READ and if it succeeds, post FD_CLOSE again (another FD_READ may succeed before it) @@ -1674,7 +1674,7 @@ void CFTPWorker::ReceiveNetEvent(LPARAM lParam, int index) ReadBytesOffset = 0; } - if (ReadBytesAllocatedSize - ReadBytesCount < FTPWORKER_BYTESTOREADONSOCKET) // still a small 'ReadBytes' buffer + if (ReadBytesAllocatedSize - ReadBytesCount < FTPWORKER_BYTESTOREADONSOCKET) // the 'ReadBytes' buffer is still too small { int newSize = ReadBytesCount + FTPWORKER_BYTESTOREADONSOCKET + FTPWORKER_BYTESTOREADONSOCKETPREALLOC; @@ -1693,8 +1693,8 @@ void CFTPWorker::ReceiveNetEvent(LPARAM lParam, int index) } if (!lowMem) - { // read as many bytes as possible into the buffer; do not read cyclically so the data is processed sequentially - // (smaller buffers are enough); if there is still data to read we receive FD_READ again + { // read as many bytes as possible into the buffer; do not read cyclically, so the data is processed sequentially + // (smaller buffers are sufficient); if there is still data to read, we will receive FD_READ again if (!SSLConn) { int len = recv(Socket, ReadBytes + ReadBytesCount, ReadBytesAllocatedSize - ReadBytesCount, 0); @@ -1743,9 +1743,9 @@ void CFTPWorker::ReceiveNetEvent(LPARAM lParam, int index) } else { - // can happen: the main or operation-dialog thread manages to call CloseSocket() before FD_READ is delivered + // This can happen if the main or operation-dialog thread calls CloseSocket() before FD_READ is delivered // TRACE_E("Unexpected situation in CFTPWorker::ReceiveNetEvent(FD_READ): Socket is not connected."); - // we will not generate an event for this unexpected error (solution: user presses ESC) + // We will not generate an event for this unexpected error (workaround: the user presses ESC) } } else // FD_READ error report (documentation says only WSAENETDOWN) @@ -1766,7 +1766,7 @@ void CFTPWorker::ReceiveNetEvent(LPARAM lParam, int index) // now process FD_CLOSE if (WSAGETSELECTEVENT(lParam) == FD_CLOSE) { - if (sendFDCloseAgain) // FD_CLOSE acted instead of FD_READ => post FD_CLOSE again + if (sendFDCloseAgain) // FD_CLOSE arrived instead of FD_READ => post FD_CLOSE again { PostMessage(SocketsThread->GetHiddenWindow(), WM_APP_SOCKET_MIN + index, (WPARAM)GetSocket(), lParam); @@ -1852,7 +1852,7 @@ void CFTPWorker::ReceiveNetEvent(LPARAM lParam, int index) { BytesToWriteOffset = 0; BytesToWriteCount = 0; - break; // return the error + break; // report the error } } } @@ -1872,7 +1872,7 @@ void CFTPWorker::ReceiveNetEvent(LPARAM lParam, int index) } else { - // can happen: the main or operation-dialog thread manages to call CloseSocket() before FD_WRITE is delivered + // can happen: the main or operation-dialog thread calls CloseSocket() before FD_WRITE is delivered //TRACE_E("Unexpected situation in CFTPWorker::ReceiveNetEvent(FD_WRITE): Socket is not connected."); BytesToWriteCount = 0; // error -> reset the buffer BytesToWriteOffset = 0; @@ -1989,8 +1989,8 @@ void CFTPWorker::ReceiveTimer(DWORD id, void* param) // request another status update cycle clearStatusType = FALSE; - // since we are already in the CSocketsThread::CritSect section, this call - // is possible even from the CSocket::SocketCritSect and CFTPWorker::WorkerCritSect sections (no deadlock risk) + // since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no deadlock risk) SocketsThread->AddTimer(Msg, UID, GetTickCount() + WORKER_STATUSUPDATETIMEOUT, WORKER_STATUSUPDATETIMID, NULL); // ignore errors; at worst the status will not update } @@ -2081,8 +2081,8 @@ void CFTPWorker::ReceivePostMessage(DWORD id, void* param) case WORKER_DATACON_CONNECTED: { - // since we are already in the CSocketsThread::CritSect section, this call - // is possible even from the CSocket::SocketCritSect section (no deadlock risk) + // since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) if (WorkerDataCon != NULL && (int)(INT_PTR)param == WorkerDataCon->GetUID()) // message came from the current data connection (discard others immediately) HandleEvent(fweDataConConnectedToServer, NULL, 0, 0); // else // may arrive after WorkerDataCon is closed (if the LIST reply arrives immediately and the data connection is also immediately closed - short listing) @@ -2092,8 +2092,8 @@ void CFTPWorker::ReceivePostMessage(DWORD id, void* param) case WORKER_DATACON_CLOSED: { - // since we are already in the CSocketsThread::CritSect section, this call - // is possible even from the CSocket::SocketCritSect section (no deadlock risk) + // since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) if (WorkerDataCon != NULL && (int)(INT_PTR)param == WorkerDataCon->GetUID()) // message came from the current data connection (discard others immediately) HandleEvent(fweDataConConnectionClosed, NULL, 0, 0); // else // may arrive after WorkerDataCon is closed (if the LIST reply arrives immediately and the data connection is also immediately closed - short listing) @@ -2103,8 +2103,8 @@ void CFTPWorker::ReceivePostMessage(DWORD id, void* param) case WORKER_DATACON_FLUSHDATA: { - // since we are already in the CSocketsThread::CritSect section, this call - // is possible even from the CSocket::SocketCritSect section (no deadlock risk) + // since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) if (WorkerDataCon != NULL && (int)(INT_PTR)param == WorkerDataCon->GetUID()) // message came from the current data connection (discard others immediately) HandleEvent(fweDataConFlushData, NULL, 0, 0); // else // may arrive after WorkerDataCon has been closed @@ -2114,8 +2114,8 @@ void CFTPWorker::ReceivePostMessage(DWORD id, void* param) case WORKER_DATACON_LISTENINGFORCON: { - // since we are already in the CSocketsThread::CritSect section, this call - // is possible even from the CSocket::SocketCritSect section (no deadlock risk) + // since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) if (WorkerDataCon != NULL && (int)(INT_PTR)param == WorkerDataCon->GetUID()) // message came from the current data connection (discard others immediately) HandleEvent(fweDataConListeningForCon, NULL, 0, 0); else @@ -2125,8 +2125,8 @@ void CFTPWorker::ReceivePostMessage(DWORD id, void* param) case WORKER_UPLDATACON_LISTENINGFORCON: { - // since we are already in the CSocketsThread::CritSect section, this call - // is possible even from the CSocket::SocketCritSect section (no deadlock risk) + // since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) if (WorkerUploadDataCon != NULL && (int)(INT_PTR)param == WorkerUploadDataCon->GetUID()) // message came from the current data connection (discard others immediately) HandleEvent(fweUplDataConListeningForCon, NULL, 0, 0); else @@ -2136,9 +2136,9 @@ void CFTPWorker::ReceivePostMessage(DWORD id, void* param) case WORKER_UPLDATACON_CONNECTED: { - // since we are already in the CSocketsThread::CritSect section, this call - // is possible even from the CSocket::SocketCritSect section (no deadlock risk) - if (WorkerUploadDataCon != NULL && (int)(INT_PTR)param == WorkerUploadDataCon->GetUID()) // message came from the current upload data connection (discard others immediately) + // since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) + if (WorkerUploadDataCon != NULL && (int)(INT_PTR)param == WorkerUploadDataCon->GetUID()) // message from the current upload data connection (discard others immediately) HandleEvent(fweUplDataConConnectedToServer, NULL, 0, 0); // else // may arrive after WorkerUploadDataCon has been closed // TRACE_E("CFTPWorker::ReceivePostMessage(): received WORKER_UPLDATACON_CONNECTED for nonexistent data-connection!"); @@ -2147,9 +2147,9 @@ void CFTPWorker::ReceivePostMessage(DWORD id, void* param) case WORKER_UPLDATACON_CLOSED: { - // since we are already in the CSocketsThread::CritSect section, this call - // is possible even from the CSocket::SocketCritSect section (no deadlock risk) - if (WorkerUploadDataCon != NULL && (int)(INT_PTR)param == WorkerUploadDataCon->GetUID()) // message came from the current upload data connection (discard others immediately) + // since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) + if (WorkerUploadDataCon != NULL && (int)(INT_PTR)param == WorkerUploadDataCon->GetUID()) // message from the current upload data connection (discard others immediately) HandleEvent(fweUplDataConConnectionClosed, NULL, 0, 0); // else // may arrive after WorkerUploadDataCon has been closed // TRACE_E("CFTPWorker::ReceivePostMessage(): received WORKER_UPLDATACON_CLOSED for nonexistent data-connection!"); @@ -2158,9 +2158,9 @@ void CFTPWorker::ReceivePostMessage(DWORD id, void* param) case WORKER_UPLDATACON_PREPAREDATA: { - // since we are already in the CSocketsThread::CritSect section, this call - // is possible even from the CSocket::SocketCritSect section (no deadlock risk) - if (WorkerUploadDataCon != NULL && (int)(INT_PTR)param == WorkerUploadDataCon->GetUID()) // message came from the current upload data connection (discard others immediately) + // since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) + if (WorkerUploadDataCon != NULL && (int)(INT_PTR)param == WorkerUploadDataCon->GetUID()) // message from the current upload data connection (discard others immediately) HandleEvent(fweUplDataConPrepareData, NULL, 0, 0); // else // may arrive after WorkerUploadDataCon has been closed // TRACE_E("CFTPWorker::ReceivePostMessage(): received WORKER_UPLDATACON_PREPAREDATA for nonexistent data-connection!"); @@ -2192,7 +2192,7 @@ void CFTPWorker::ReadFTPErrorReplies() char* reply; int replySize; int replyCode; - while (ReadFTPReply(&reply, &replySize, &replyCode)) // as long as we have a server reply + while (ReadFTPReply(&reply, &replySize, &replyCode)) // as long as we have any server reply { // log any error messages from the server Logs.LogMessage(LogUID, reply, replySize, TRUE); if (ErrorDescr[0] == 0 && // we do not have an error description yet @@ -2267,7 +2267,7 @@ void CFTPWorker::HandleSocketEvent(CFTPWorkerSocketEvent event, DWORD data1, DWO { switch (event) { - case fwseNewBytesRead: // if it is an error, we want its text + case fwseNewBytesRead: // if it is an error, we want to know its text { ReadFTPErrorReplies(); break; @@ -2280,7 +2280,7 @@ void CFTPWorker::HandleSocketEvent(CFTPWorkerSocketEvent event, DWORD data1, DWO FTPGetErrorTextForLog(data1, errBuf, 300); Logs.LogMessage(LogUID, errBuf, -1, TRUE); } - if (ErrorDescr[0] == 0) // when closing the connection we must fill ErrorDescr (even with "unknown error") + if (ErrorDescr[0] == 0) // on connection close, we must populate ErrorDescr (even with "unknown error") { lstrcpyn(ErrorDescr, GetWorkerErrorTxt(data1, errBuf, 300), FTPWORKER_ERRDESCR_BUFSIZE); CorrectErrorDescr(); @@ -2304,7 +2304,7 @@ void CFTPWorker::HandleSocketEvent(CFTPWorkerSocketEvent event, DWORD data1, DWO int replyCode; BOOL firstRound = TRUE; while (BytesToWriteOffset == BytesToWriteCount && // test "write done" (we wait for the server reply only after the full command is sent) - ReadFTPReply(&reply, &replySize, &replyCode)) // as long as we have some server reply (one read may contain several at once) + ReadFTPReply(&reply, &replySize, &replyCode)) // as long as we have a server reply (one read may contain several at once) { if (!firstRound) HANDLES(EnterCriticalSection(&WorkerCritSect)); @@ -2319,8 +2319,8 @@ void CFTPWorker::HandleSocketEvent(CFTPWorkerSocketEvent event, DWORD data1, DWO HANDLES(LeaveCriticalSection(&WorkerCritSect)); if (FTP_DIGIT_1(replyCode) != FTP_D1_MAYBESUCCESS) // command reply { - // since we are already in the CSocketsThread::CritSect section, this call - // is possible even from the CSocket::SocketCritSect section (no deadlock risk) + // since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) SocketsThread->DeleteTimer(uid, WORKER_TIMEOUTTIMERID); // HandleEvent() will probably send another command, so delete the timer "in advance" HandleEvent(fweCmdReplyReceived, reply, replySize, replyCode); @@ -2364,13 +2364,13 @@ void CFTPWorker::HandleSocketEvent(CFTPWorkerSocketEvent event, DWORD data1, DWO BOOL trFinished; DWORD start; HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // since we are already in the CSocketsThread::CritSect section, this call - // is possible even from the CSocket::SocketCritSect section (no deadlock risk) + // since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) BOOL isTransfering = WorkerDataCon != NULL ? WorkerDataCon->IsTransfering(&trFinished) : WorkerUploadDataCon->IsTransfering(&trFinished); if (isTransfering) { // waiting for data, so this is not a timeout - // since we are already in the CSocketsThread::CritSect section, this call - // is possible even from the CSocket::SocketCritSect section (no deadlock risk) + // since we are already in CSocketsThread::CritSect, this call + // is possible even from CSocket::SocketCritSect (no deadlock risk) SocketsThread->AddTimer(Msg, UID, GetTickCount() + serverTimeout, WORKER_TIMEOUTTIMERID, NULL); // ignore the error; at worst the user will press Stop HANDLES(EnterCriticalSection(&WorkerCritSect)); @@ -2380,15 +2380,15 @@ void CFTPWorker::HandleSocketEvent(CFTPWorkerSocketEvent event, DWORD data1, DWO { if (trFinished) { - // the timeout is measured from closing the connection (moment when the server can react - it also learns - // about the connection closing) - // since we are already in the CSocketsThread::CritSect section, this call - // is possible even from the CSocket::SocketCritSect section (no deadlock risk) + // the timeout is measured from the moment the connection is closed (the moment the server can react and also learns + // that the connection was closed) + // since we are already in the CSocketsThread::CritSect critical section, this call + // is possible even from the CSocket::SocketCritSect critical section (no deadlock risk) start = WorkerDataCon != NULL ? WorkerDataCon->GetSocketCloseTime() : WorkerUploadDataCon->GetSocketCloseTime(); if ((GetTickCount() - start) < (DWORD)serverTimeout) // the timeout since closing the connection has not yet expired { - // since we are already in the CSocketsThread::CritSect section, this call - // is possible even from the CSocket::SocketCritSect section (no deadlock risk) + // since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) SocketsThread->AddTimer(Msg, UID, start + serverTimeout, WORKER_TIMEOUTTIMERID, NULL); // ignore the error; at worst the user will press Stop HANDLES(EnterCriticalSection(&WorkerCritSect)); diff --git a/src/plugins/ftp/operats4.cpp b/src/plugins/ftp/operats4.cpp index d8fbe5f38..b2df2f6a3 100644 --- a/src/plugins/ftp/operats4.cpp +++ b/src/plugins/ftp/operats4.cpp @@ -69,7 +69,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit HANDLES(LeaveCriticalSection(&WorkerCritSect)); // since we are already inside CSocketsThread::CritSect, this call // is also possible from CSocket::SocketCritSect (no risk of deadlock) - if (WorkerDataCon->IsConnected()) // close the data connection; the system will try a "graceful" + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system will attempt a "graceful" shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn the result) WorkerDataCon->FreeFlushData(); DeleteSocket(WorkerDataCon); @@ -135,7 +135,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit WorkerDataConState = wdcsTransferFinished; else { - if (WorkerDataConState != wdcsWaitingForConnection) // this also arrives when the data-connection connect fails + if (WorkerDataConState != wdcsWaitingForConnection) // also occurs when the data connection connect attempt fails TRACE_E("CFTPWorker::HandleEventInWorkingState(): fweDataConConnectionClosed: WorkerDataConState is not wdcsTransferingData!"); } } @@ -147,7 +147,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit { if (event == fweUplDataConConnectedToServer) { - if (ResumingFileOnServer) // APPE caused the data connection to open -> APPE is probably functional (implemented) + if (ResumingFileOnServer) // APPE opened the data connection -> APPE is probably supported (implemented) Oper->SetDataConWasOpenedForAppendCmd(TRUE); if (ShouldStop) { @@ -156,7 +156,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit HANDLES(LeaveCriticalSection(&WorkerCritSect)); // since we are already inside CSocketsThread::CritSect, this call // is also possible from CSocket::SocketCritSect (no risk of deadlock) - if (WorkerUploadDataCon->IsConnected()) // close the data connection; the system will try a "graceful" + if (WorkerUploadDataCon->IsConnected()) // close the "data connection"; the system will attempt a "graceful" shutdown WorkerUploadDataCon->CloseSocketEx(NULL); // shutdown (we will not learn the result) WorkerUploadDataCon->FreeBufferedData(); DeleteSocket(WorkerUploadDataCon); @@ -208,7 +208,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit WorkerDataConState = wdcsTransferFinished; else { - if (WorkerDataConState != wdcsWaitingForConnection) // also arrives when the data connection connect fails + if (WorkerDataConState != wdcsWaitingForConnection) // also occurs when the data connection fails to connect TRACE_E("CFTPWorker::HandleEventInWorkingState(): fweUplDataConConnectionClosed: WorkerDataConState is not wdcsTransferingData!"); } } @@ -247,7 +247,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit case fqitUploadCopyExploreDir: // upload: explore a directory for copying (CFTPQueueItemCopyMoveUploadExplore object) case fqitUploadMoveExploreDir: // upload: explore a directory for move (deletes the directory after completion) (CFTPQueueItemCopyMoveUploadExplore object) { - if (UploadDirGetTgtPathListing) // list the target path into the upload listing cache + if (UploadDirGetTgtPathListing) // cache the target path listing for upload { BOOL listingNotAccessible; HandleEventInWorkingState2(event, sendQuitCmd, postActivate, reportWorkerChange, buf, errBuf, host, @@ -263,7 +263,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit UploadListingCache.ListingFailed(userBuf, hostBuf, port, ((CFTPQueueItemCopyMoveUploadExplore*)CurItem)->TgtPath, pathType, listingNotAccessible, NULL, &listingOKErrorIgnored); - if (listingOKErrorIgnored && lookForNewWork) // a listing error is reported on the item; cancel this error + if (listingOKErrorIgnored && lookForNewWork) // a listing error is reported for the item; clear this error { lookForNewWork = FALSE; Queue->UpdateItemState(CurItem, sqisProcessing, ITEMPR_OK, NO_ERROR, NULL, Oper); @@ -294,7 +294,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit { switch (SubState) { - case fwssWorkStartWork: // determine which path we should switch to on the server and send CWD + case fwssWorkStartWork: // determine which path to switch to on the server and send CWD { // before resolving the link for change-attr we must reset the speed meter (the resolve speed // is not measured) - this results in "(unknown)" time-left being shown in the operation dialog @@ -307,7 +307,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit lstrcpyn(ftpPath, CurItem->Path, FTP_MAX_PATH); CFTPServerPathType type = Oper->GetFTPServerPathType(ftpPath); if (FTPPathAppend(type, ftpPath, FTP_MAX_PATH, CurItem->Name, TRUE)) - { // we have the path, send CWD to the examined directory on the server + { // we have the path; send CWD to the target directory on the server _snprintf_s(errText, _TRUNCATE, LoadStr(IDS_LOGMSGRESOLVINGLINK), ftpPath); Logs.LogMessage(LogUID, errText, -1, TRUE); @@ -327,7 +327,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit break; } - case fwssWorkResLnkWaitForCWDRes: // resolve-link: waiting for the "CWD" result (changing to the examined link - if it succeeds, it is a directory link) + case fwssWorkResLnkWaitForCWDRes: // resolve-link: waiting for the "CWD" result (changing to the link being examined; if it succeeds, it is a link to a directory) { switch (event) { @@ -363,7 +363,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit break; } - case fqitChAttrsResolveLink: // change attributes: detect whether this is a link to a directory (CFTPQueueItem object) + case fqitChAttrsResolveLink: // change attributes: determine whether this is a link to a directory (CFTPQueueItem object) { item = new CFTPQueueItem; if (item != NULL) @@ -488,9 +488,9 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit break; } - case fqitDeleteLink: // delete for a link (CFTPQueueItemDel object) - case fqitDeleteFile: // delete for a file (CFTPQueueItemDel object) - case fqitDeleteDir: // delete for a directory (CFTPQueueItemDir object) + case fqitDeleteLink: // delete a link (CFTPQueueItemDel object) + case fqitDeleteFile: // delete a file (CFTPQueueItemDel object) + case fqitDeleteDir: // delete a directory (CFTPQueueItemDir object) case fqitCopyFileOrFileLink: // copy a file or a link to a file (CFTPQueueItemCopyOrMove object) case fqitMoveFileOrFileLink: // move a file or a link to a file (CFTPQueueItemCopyOrMove object) case fqitMoveDeleteDir: // delete a directory after moving its contents (CFTPQueueItemDir object) @@ -604,9 +604,9 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit case fweCmdReplyReceived: { if (FTP_DIGIT_1(replyCode) == FTP_D1_SUCCESS) - { // we successfully changed the working path; because this path was "once" returned - // from the server in response to PWD, we assume that PWD would now return this path again - // and therefore we will not send it (optimization with hopefully low risk) + { // we successfully changed the working path; because this path was previously returned + // by the server in response to PWD, we assume that PWD would return it again now, + // so we will not send it (an optimization with hopefully low risk) HaveWorkingPath = TRUE; lstrcpyn(WorkingPath, CurItem->Path, FTP_MAX_PATH); SubState = fwssWorkSimpleCmdStartWork; @@ -640,8 +640,8 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit { switch (CurItem->Type) { - case fqitDeleteFile: // delete for a file (CFTPQueueItemDel object) - case fqitDeleteLink: // delete for a link (CFTPQueueItemDel object) + case fqitDeleteFile: // delete a file (CFTPQueueItemDel object) + case fqitDeleteLink: // delete a link (CFTPQueueItemDel object) case fqitMoveDeleteDirLink: // delete a link to a directory after moving its contents (CFTPQueueItemDir object) { PrepareFTPCommand(buf, 200 + FTP_MAX_PATH, errBuf, 50 + FTP_MAX_PATH, @@ -651,7 +651,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit break; } - case fqitDeleteDir: // delete for a directory (CFTPQueueItemDir object) + case fqitDeleteDir: // delete a directory (CFTPQueueItemDir object) case fqitMoveDeleteDir: // delete a directory after moving its contents (CFTPQueueItemDir object) { char vmsDirName[MAX_PATH + 10]; @@ -684,7 +684,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit break; } - case fwssWorkDelFileWaitForDELERes: // deleting a file/link: waiting for the "DELE" result (file/link deletion) + case fwssWorkDelFileWaitForDELERes: // deleting a file/link: waiting for the "DELE" result { switch (event) { @@ -735,7 +735,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit } } } - if (finished) // use only the final command in the operation for speed measurement (RMD may follow DELE; eliminate that here) + if (finished) // use only the last command in the operation for speed measurement (RMD may follow DELE; that is eliminated here) { // the server replied -> add theoretical bytes to the speed meter Oper->GetGlobalTransferSpeedMeter()->BytesReceived(SMPLCMD_APPROXBYTESIZE, GetTickCount()); @@ -743,7 +743,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit break; } - case fweCmdConClosed: // the connection closed/timed out (see ErrorDescr for details) -> try to restore it + case fweCmdConClosed: // the connection closed/timed out (see ErrorDescr for details) -> try to reestablish it { // if we do not know how the file/link deletion ended, invalidate the listing cache Oper->GetUserHostPort(userBuf, hostBuf, &port); @@ -808,7 +808,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit } case fwssWorkChAttrWaitForCHMODRes: // change attributes: waiting for the "SITE CHMOD" result (changing file/directory mode, likely Unix only) - case fwssWorkChAttrWaitForCHMODQuotedRes: // change attributes (name in quotes): waiting for the "SITE CHMOD" result (changing file/directory mode, likely Unix only) + case fwssWorkChAttrWaitForCHMODQuotedRes: // changing attributes (name in quotes): waiting for the "SITE CHMOD" result (changing the file/directory mode, probably Unix only) { switch (event) { @@ -826,7 +826,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit char* s = CurItem->Name; while (*s != 0 && *s > ' ') s++; - if (*s != 0 && SubState == fwssWorkChAttrWaitForCHMODRes) // the file/directory name contains white-spaces; try placing the name in quotes (only if we have not tried this yet) + if (*s != 0 && SubState == fwssWorkChAttrWaitForCHMODRes) // the file/directory name contains whitespace; try putting the name in quotes (only if we have not tried this yet) { if (ShouldStop) handleShouldStop = TRUE; // check whether the worker should stop @@ -860,7 +860,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit lookForNewWork = TRUE; } } - if (finished) // use only the final command in the operation for speed measurement (RMD may follow DELE; eliminate that here) + if (finished) // use only the final command in the operation for speed measurement (RMD may follow DELE; that is ignored here) { // the server replied -> add theoretical bytes to the speed meter Oper->GetGlobalTransferSpeedMeter()->BytesReceived(SMPLCMD_APPROXBYTESIZE, GetTickCount()); @@ -887,7 +887,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit case fqitUploadCopyFile: // upload: copy a file (CFTPQueueItemCopyOrMoveUpload object) case fqitUploadMoveFile: // upload: move a file (CFTPQueueItemCopyOrMoveUpload object) { - if (UploadDirGetTgtPathListing) // list the target path into the upload listing cache + if (UploadDirGetTgtPathListing) // cache the target path listing for upload { BOOL listingNotAccessible; HandleEventInWorkingState2(event, sendQuitCmd, postActivate, reportWorkerChange, buf, errBuf, host, @@ -903,7 +903,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit UploadListingCache.ListingFailed(userBuf, hostBuf, port, ((CFTPQueueItemCopyOrMoveUpload*)CurItem)->TgtPath, pathType, listingNotAccessible, NULL, &listingOKErrorIgnored); - if (listingOKErrorIgnored && lookForNewWork) // a listing error is reported on the item; cancel this error + if (listingOKErrorIgnored && lookForNewWork) // a listing error is reported on the item; clear this error { lookForNewWork = FALSE; Queue->UpdateItemState(CurItem, sqisProcessing, ITEMPR_OK, NO_ERROR, NULL, Oper); @@ -955,7 +955,7 @@ void CFTPWorker::HandleEventInWorkingState(CFTPWorkerEvent event, BOOL& sendQuit } else { - if (conClosedRetryItem) // the connection broke; end the operation on the item and try to perform the item again + if (conClosedRetryItem) // the connection broke; end the operation on this item and retry the item { CloseOpenedFile(TRUE, FALSE, NULL, NULL, FALSE, NULL); // this transfer failed; close the target file (if we are using one at all) CloseOpenedInFile(); // this transfer failed; close the source file (if we are using one at all) @@ -1051,7 +1051,7 @@ void CFTPWorker::HandleEvent(CFTPWorkerEvent event, char* reply, int replySize, { case fwsLookingForWork: { - if (ShouldStop) // we should stop the worker + if (ShouldStop) // stop the worker { if (SubState != fwssLookFWQuitSent && !SocketClosed) { @@ -1089,12 +1089,12 @@ void CFTPWorker::HandleEvent(CFTPWorkerEvent event, char* reply, int replySize, case fwsSleeping: { - if (ShouldStop) // we should stop the worker + if (ShouldStop) // stop the worker { if (SubState != fwssSleepingQuitSent && !SocketClosed) { SubState = fwssSleepingQuitSent; // prevent sending "QUIT" multiple times - sendQuitCmd = TRUE; // we must finish and have an open connection -> send the server the "QUIT" command (ignore the reply; it should lead to closing the connection and that is all we need now) + sendQuitCmd = TRUE; // we are shutting down and still have an open connection -> send the server the "QUIT" command (ignore the reply; it should close the connection, and that is all we need now) } } else @@ -1109,7 +1109,7 @@ void CFTPWorker::HandleEvent(CFTPWorkerEvent event, char* reply, int replySize, reportWorkerChange = TRUE; if (SocketClosed) - ConnectAttemptNumber = 0; // give the awakened worker without a connection a chance for a new connect + ConnectAttemptNumber = 0; // give the awakened worker without a connection a chance to make a new connection } } break; @@ -1139,7 +1139,7 @@ void CFTPWorker::HandleEvent(CFTPWorkerEvent event, char* reply, int replySize, } else // normal activity { - if (event == fweReconTimeout || event == fweWorkerShouldResume) // proceed to another connection attempt + if (event == fweReconTimeout || event == fweWorkerShouldResume) // proceed to the next connection attempt { State = fwsConnecting; // no need to call Oper->OperationStatusMaybeChanged(); it does not change the operation state (it is not paused and will not be after this change) SubState = fwssNone; @@ -1158,8 +1158,8 @@ void CFTPWorker::HandleEvent(CFTPWorkerEvent event, char* reply, int replySize, { ReturnCurItemToQueue(); // return the item to the queue HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // since we are already inside CSocketsThread::CritSect, this call - // is also possible from CSocket::SocketCritSect (no risk of deadlock) + // since we are already in CSocketsThread::CritSect, this call + // is also allowed from CSocket::SocketCritSect (no deadlock risk) Oper->PostNewWorkAvailable(TRUE); // inform any first sleeping worker that new work is available HANDLES(EnterCriticalSection(&WorkerCritSect)); } @@ -1216,7 +1216,7 @@ void CFTPWorker::HandleEvent(CFTPWorkerEvent event, char* reply, int replySize, { DWORD lastIdle, lastIdle2; BOOL isNotBusy = SalamanderGeneral->SalamanderIsNotBusy(&lastIdle); - if (isNotBusy || GetTickCount() - lastIdle < 2000) // high chance that Salamander reaches the "idle" state (the connection can be returned to the panel) + if (isNotBusy || GetTickCount() - lastIdle < 2000) // there is a high chance that Salamander will reach the "idle" state (the connection can then be returned to the panel) { HANDLES(LeaveCriticalSection(&WorkerCritSect)); @@ -1230,7 +1230,7 @@ void CFTPWorker::HandleEvent(CFTPWorkerEvent event, char* reply, int replySize, DWORD startTime = GetTickCount(); while (1) { - if (isNotBusy || startTime - lastIdle < 500 || // already idle or was idle half a second ago (it is very unlikely that e.g. a dialog is open -> the idle state should return soon) + if (isNotBusy || startTime - lastIdle < 500 || // already idle or was idle less than half a second ago (so it is very unlikely that, for example, a dialog is open, and the idle state should return soon) SalamanderGeneral->SalamanderIsNotBusy(&lastIdle2) || lastIdle2 != lastIdle) // strong chance the connection handover happens immediately (otherwise we prefer to close it via "QUIT") { if (ReturningConnections.Add(ctrlUID, this)) @@ -1268,7 +1268,7 @@ void CFTPWorker::HandleEvent(CFTPWorkerEvent event, char* reply, int replySize, PrepareFTPCommand(buf, 200 + FTP_MAX_PATH, errBuf, 50 + FTP_MAX_PATH, ftpcmdQuit, &cmdLen); // cannot report an error sendCmd = TRUE; } - else // the connection will be handed over; simulate closing the worker's socket (to end waiting for socket closure when stopping the worker) + else // the connection will be handed over; simulate closing the worker's socket (to stop waiting for socket closure when stopping the worker) { SocketClosed = TRUE; ErrorDescr[0] = 0; // this is not an error (and it should no longer be displayed anywhere) @@ -1305,9 +1305,9 @@ void CFTPWorker::HandleEvent(CFTPWorkerEvent event, char* reply, int replySize, } else { - // the socket most likely closed (FD_CLOSE will arrive eventually); if another error occurred, - // close the socket hard via CloseSocket() after 100 ms - wait to see which of the two - // variants happens (while trying to capture an error message and log it) + // the socket was most likely closed (FD_CLOSE will arrive eventually); if another error occurred, + // the socket will be forcibly closed via CloseSocket() after 100 ms - wait to see which of these two + // cases applies (while also trying to capture an error message and write it to the log) HANDLES(EnterCriticalSection(&WorkerCritSect)); CommandState = fwcsWaitForCmdError; CommandTransfersData = FALSE; @@ -1315,8 +1315,8 @@ void CFTPWorker::HandleEvent(CFTPWorkerEvent event, char* reply, int replySize, // ReadFTPErrorReplies(); // cannot be used (calls SkipFTPReply, which skips the reply processed in this method and causes an error after returning); if the socket has long been closed, read its errors right now (no socket events will occur; nothing would be read) HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // since we are already inside CSocketsThread::CritSect, this call - // is also possible from CSocket::SocketCritSect (no risk of deadlock) + // since we are already in CSocketsThread::CritSect, this call + // is also allowed from CSocket::SocketCritSect (no deadlock risk) SocketsThread->AddTimer(Msg, UID, GetTickCount() + 100, // give 0.1 seconds to possibly receive bytes from the socket (it may re-post FD_CLOSE, etc.) WORKER_CMDERRORTIMERID, NULL); // ignore errors; at worst the user will press Stop } diff --git a/src/plugins/ftp/operats5.cpp b/src/plugins/ftp/operats5.cpp index a52e4cd44..aaa67fc2f 100644 --- a/src/plugins/ftp/operats5.cpp +++ b/src/plugins/ftp/operats5.cpp @@ -54,7 +54,7 @@ BOOL CFTPWorkersList::InformWorkersAboutStop(int workerInd, CFTPWorker** victims if (*foundVictims < maxVictims) { CFTPWorker* worker = Workers[workerInd]; - if (worker->InformAboutStop()) // add them among the victims (CloseDataConnectionOrPostShouldStop() will be called on them later) + if (worker->InformAboutStop()) // add it to the victims (CloseDataConnectionOrPostShouldStop() will be called on it later) *(victims + (*foundVictims)++) = worker; } else @@ -67,7 +67,7 @@ BOOL CFTPWorkersList::InformWorkersAboutStop(int workerInd, CFTPWorker** victims while (*foundVictims < maxVictims && i < Workers.Count) { CFTPWorker* worker = Workers[i++]; - if (worker->InformAboutStop()) // add them among the victims (CloseDataConnectionOrPostShouldStop() will be called on them later) + if (worker->InformAboutStop()) // add it to the victims (CloseDataConnectionOrPostShouldStop() will be called on it later) *(victims + (*foundVictims)++) = worker; } ret = i < Workers.Count; @@ -90,7 +90,7 @@ BOOL CFTPWorkersList::InformWorkersAboutPause(int workerInd, CFTPWorker** victim if (*foundVictims < maxVictims) { CFTPWorker* worker = Workers[workerInd]; - if (worker->InformAboutPause(pause)) // add them among the victims (PostShouldPauseOrResume() will be called on them later) + if (worker->InformAboutPause(pause)) // add it to the victims (PostShouldPauseOrResume() will be called on it later) *(victims + (*foundVictims)++) = worker; } else @@ -103,7 +103,7 @@ BOOL CFTPWorkersList::InformWorkersAboutPause(int workerInd, CFTPWorker** victim while (*foundVictims < maxVictims && i < Workers.Count) { CFTPWorker* worker = Workers[i++]; - if (worker->InformAboutPause(pause)) // add them among the victims (PostShouldPauseOrResume() will be called on them later) + if (worker->InformAboutPause(pause)) // add it to the victims (PostShouldPauseOrResume() will be called on it later) *(victims + (*foundVictims)++) = worker; } ret = i < Workers.Count; @@ -161,7 +161,7 @@ BOOL CFTPWorkersList::ForceCloseWorkers(int workerInd, CFTPWorker** victims, worker->ForceCloseDiskWork(); if (*foundVictims < maxVictims) { - if (!worker->SocketClosedAndDataConDoesntExist()) // add them among the victims (ForceClose() will be called on them later) + if (!worker->SocketClosedAndDataConDoesntExist()) // add it to the victims (ForceClose() will be called on it later) *(victims + (*foundVictims)++) = worker; } else @@ -175,7 +175,7 @@ BOOL CFTPWorkersList::ForceCloseWorkers(int workerInd, CFTPWorker** victims, { CFTPWorker* worker = Workers[i++]; worker->ForceCloseDiskWork(); - if (!worker->SocketClosedAndDataConDoesntExist()) // add them among the victims (ForceClose() will be called on them later) + if (!worker->SocketClosedAndDataConDoesntExist()) // add it to the victims (ForceClose() will be called on it later) *(victims + (*foundVictims)++) = worker; } ret = i < Workers.Count; @@ -286,7 +286,7 @@ void CFTPWorkersList::GetListViewDataFor(int index, NMLVDISPINFO* lvdi, char* bu { Workers[index]->GetListViewData(itemData, buf, bufSize); } - else // for an invalid index (listview has not refreshed yet) we must return at least an empty item + else // for an invalid index (the list view has not refreshed yet), we must return at least an empty item { if (itemData->mask & LVIF_IMAGE) itemData->iImage = 0; // we have only one icon so far @@ -469,7 +469,7 @@ BOOL CFTPWorkersList::GiveWorkToSleepingConWorker(CFTPWorker* sourceWorker) { CALL_STACK_MESSAGE1("CFTPWorkersList::GiveWorkToSleepingConWorker()"); - // ATTENTION: we may already be inside CSocketsThread::CritSect (and CSocket::SocketCritSect) !!! + // WARNING: we may already be inside CSocketsThread::CritSect (and CSocket::SocketCritSect)!!! BOOL ret = FALSE; HANDLES(EnterCriticalSection(&WorkersListCritSect)); @@ -536,7 +536,7 @@ BOOL CFTPWorkersList::SearchWorkerWithNewError(int* index, DWORD lastErrorOccure HANDLES(EnterCriticalSection(&WorkersListCritSect)); BOOL res = FALSE; - if (LastFoundErrorOccurenceTime + 1 < lastErrorOccurenceTime + 1) // +1 is here because -1 is used as initialization values + if (LastFoundErrorOccurenceTime + 1 < lastErrorOccurenceTime + 1) // +1 is here because -1 is used as the initial value { // it makes sense to search int foundIndex = -1; DWORD foundErrorOccurenceTime = -1; @@ -545,7 +545,7 @@ BOOL CFTPWorkersList::SearchWorkerWithNewError(int* index, DWORD lastErrorOccure { CFTPWorker* worker = Workers[i]; DWORD workerErrorOccurenceTime = worker->GetErrorOccurenceTime(); - if (workerErrorOccurenceTime != -1 && // the worker contains an error (except for an error forced by the user while resolving login/password during reconnect wait) + if (workerErrorOccurenceTime != -1 && // the worker has an error (except for an error forced by the user while resolving the login/password during reconnect wait) workerErrorOccurenceTime >= LastFoundErrorOccurenceTime + 1 && // it's a "new" error (foundIndex == -1 || foundErrorOccurenceTime > workerErrorOccurenceTime)) // the first one found so far or the "oldest" (we handle errors in the order they occurred) { @@ -570,7 +570,7 @@ void CFTPWorkersList::PostNewWorkAvailable(BOOL onlyOneItem) { CALL_STACK_MESSAGE2("CFTPWorkersList::PostNewWorkAvailable(%d)", onlyOneItem); - // ATTENTION: we may already be inside CSocketsThread::CritSect (and CSocket::SocketCritSect) !!! + // WARNING: we may already be inside CSocketsThread::CritSect (and CSocket::SocketCritSect)!!! if (onlyOneItem) { @@ -610,7 +610,7 @@ void CFTPWorkersList::PostNewWorkAvailable(BOOL onlyOneItem) } HANDLES(LeaveCriticalSection(&WorkersListCritSect)); - if (worker != NULL) // if there is at least one "sleeping" worker, post a "wake-up" to them + if (worker != NULL) // if there is at least one "sleeping" worker, post a "wake-up" to it SocketsThread->PostSocketMessage(msg, uid, WORKER_WAKEUP, NULL); } else @@ -945,7 +945,7 @@ BOOL CFTPDiskThread::CancelWork(const CFTPDiskWork* work, BOOL* workIsInProgress ret = TRUE; if (i == 0) { - Work[0] = NULL; // the first item may currently be processed, cannot remove it from the array (it is rewritten to NULL to detect its cancellation) + Work[0] = NULL; // the first item may still be the one being processed, so it cannot be removed from the array (it is set to NULL to detect its cancellation) if (workIsInProgress != NULL) *workIsInProgress = WorkIsInProgress; } @@ -1118,7 +1118,7 @@ void DoCreateDir(CFTPDiskWork& localWork, char* fullName, BOOL& workDone, BOOL& } } } - else // cannot create dir + else // cannot create directory { switch (localWork.CannotCreateDir) { @@ -1147,7 +1147,7 @@ void DoCreateDir(CFTPDiskWork& localWork, char* fullName, BOOL& workDone, BOOL& } } - if (action == 1) // autorename (for already exists, cannot create, and force action) + if (action == 1) // autorename (already exists, cannot create, and force-action cases) { BOOL ok = FALSE; if (!isValid) @@ -1171,7 +1171,7 @@ void DoCreateDir(CFTPDiskWork& localWork, char* fullName, BOOL& workDone, BOOL& { if (firstRound && !isValid && nameLen < rest) // test the "validated" name memcpy(pathEnd, localWork.Name, nameLen + 1); - else // append numbering to the end of the name (directories have no extension) (e.g. "(2)") + trim if necessary so the name fits into the full path + else // append numbering to the end of the name (directories have no extension), e.g. "(2)", and trim it if necessary so the name fits in the full path { if (firstRound && (tooLongName || !isValid) || winErr == ERROR_FILE_EXISTS || winErr == ERROR_ALREADY_EXISTS) @@ -1211,7 +1211,7 @@ void DoCreateDir(CFTPDiskWork& localWork, char* fullName, BOOL& workDone, BOOL& } } else - break; // another attempt to create the directory makes no sense (it's not a name collision, syntax error, or overly long name), return an error + break; // another attempt to create the directory would be pointless (it is not a name collision, a syntax error, or an overly long name); return an error } // allocate the new name if (localWork.NewTgtName != NULL) @@ -1238,7 +1238,7 @@ void DoCreateDir(CFTPDiskWork& localWork, char* fullName, BOOL& workDone, BOOL& { workDone = TRUE; ok = TRUE; - break; // success, return OK + the new name + break; // success, return OK and the new name } firstRound = FALSE; } @@ -1542,7 +1542,7 @@ void DoCreateFile(CFTPDiskWork& localWork, char* fullName, BOOL& workDone, BOOL& char* s = localWork.Name + strlen(localWork.Name); while (--s >= localWork.Name) { - if (*s == ')') // searching from the end for " (number)" + if (*s == ')') // search from the end for " (number)" { char* end = s + 1; int num = 0; @@ -1595,7 +1595,7 @@ void DoCreateFile(CFTPDiskWork& localWork, char* fullName, BOOL& workDone, BOOL& memcpy(localWork.Name + off, suffix, suffixLen); memcpy(localWork.Name + off + suffixLen, nameBackup + extOffset, nameLen - extOffset + 1); } - else // the entire extension will not fit, shorten the name without respecting the extension + else // the entire extension will not fit, shorten the name without preserving the extension { memcpy(localWork.Name, nameBackup, rest - (suffixLen + 1)); memcpy(localWork.Name + rest - (suffixLen + 1), suffix, suffixLen + 1); @@ -1621,7 +1621,7 @@ void DoCreateFile(CFTPDiskWork& localWork, char* fullName, BOOL& workDone, BOOL& } } else - break; // another attempt to create the file makes no sense (it's not a name collision, syntax error, or overly long name), return an error + break; // another attempt to create the file makes no sense (it is not a name collision, invalid name syntax, or an overly long name), return an error } // allocate the new name if (localWork.NewTgtName != NULL) @@ -1673,7 +1673,7 @@ void DoCreateFile(CFTPDiskWork& localWork, char* fullName, BOOL& workDone, BOOL& break; } - case 2: // resume (for already exists, transfer failed, and force action) + if reduceFileSize==TRUE we also need to shrink the file + case 2: // resume (for the already exists, transfer failed, and force action cases); if reduceFileSize==TRUE, we also need to shrink the file case 3: // resume or overwrite (for already exists, transfer failed, and force action) { file = HANDLES_Q(CreateFile(fullName, @@ -1711,7 +1711,7 @@ void DoCreateFile(CFTPDiskWork& localWork, char* fullName, BOOL& workDone, BOOL& { DWORD resumeOverlap = Config.GetResumeOverlap(); if (resumeOverlap == 0) - resumeOverlap = 1; // at least by one byte (this threatens only if the user just changed it in configuration) + resumeOverlap = 1; // at least one byte (only possible if the user has just changed it in the configuration) if (size < CQuadWord(resumeOverlap, 0)) resumeOverlap = (DWORD)size.Value; size -= CQuadWord(resumeOverlap, 0); @@ -1750,7 +1750,7 @@ void DoCreateFile(CFTPDiskWork& localWork, char* fullName, BOOL& workDone, BOOL& if (ok) { - // workDone = TRUE; // when cancelling the operation we will not delete the file, it's a resume + // workDone = TRUE; // when cancelling the operation we will not delete the file; this is a resume localWork.OpenedFile = file; localWork.FileSize = size; localWork.CanOverwrite = (action == 3 /* resume or overwrite */); // FALSE = the file was resumed @@ -1759,7 +1759,7 @@ void DoCreateFile(CFTPDiskWork& localWork, char* fullName, BOOL& workDone, BOOL& break; // success, we are done } } - else // error when determining the file size, close the file and finish with an error + else // error determining the file size; close the file and fail { HANDLES(CloseHandle(file)); // no need to delete the file because it existed a moment ago (it likely hasn't disappeared => we did not create it) } @@ -1779,9 +1779,9 @@ void DoCreateFile(CFTPDiskWork& localWork, char* fullName, BOOL& workDone, BOOL& // break; // resume or overwrite - if resume fails we try overwrite as well } // case 3: // resume or overwrite - if resume fails we try overwrite as well - case 4: // overwrite (pri already exists, transfer failed i force action) + case 4: // overwrite (for already exists, transfer failed, and force action) { - if (action == 4) // check whether it happens to be read-only (only via the attribute), but only if we have not done so already + if (action == 4) // check whether it is read-only (via the attribute only), but only if we have not done so already { attr = SalamanderGeneral->SalGetFileAttributes(fullName); if (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_READONLY)) @@ -1858,12 +1858,12 @@ void DoCheckOrWriteToFile(CFTPDiskWork& localWork, BOOL& needCopyBack) { writeFile = FALSE; if (localWork.CheckFromOffset >= fileSize) - { // unexpected error: we are supposed to check file contents past the end of the file - the file probably changed recently (should not happen, it is opened "share-read-only") + { // unexpected error: we are supposed to check file contents beyond the end of the file; the file probably changed recently (should not happen, it is opened "share-read-only") localWork.State = sqisFailed; localWork.ProblemID = ITEMPR_RESUMETESTFAILED; needCopyBack = TRUE; } - else // set the seek position in the file + else // set the file pointer { CQuadWord curSeek = localWork.CheckFromOffset; curSeek.LoDWord = SetFilePointer(localWork.WorkFile, curSeek.LoDWord, (LONG*)&curSeek.HiDWord, FILE_BEGIN); @@ -1879,7 +1879,7 @@ void DoCheckOrWriteToFile(CFTPDiskWork& localWork, BOOL& needCopyBack) { char buf[4096]; // buffer for reading from disk int bytesToCheck = (localWork.WriteOrReadFromOffset - localWork.CheckFromOffset).LoDWord; // the size of the verified tail of the file is under 1GB, so this truncation is possible - if (bytesToCheck > localWork.ValidBytesInFlushDataBuffer) // optionally trim by the flush buffer size (we do not need to verify the entire segment at once) + if (bytesToCheck > localWork.ValidBytesInFlushDataBuffer) // optionally trim to the flush buffer size (we do not need to verify the entire segment at once) bytesToCheck = localWork.ValidBytesInFlushDataBuffer; while (bytesToCheck > 0) { @@ -1901,7 +1901,7 @@ void DoCheckOrWriteToFile(CFTPDiskWork& localWork, BOOL& needCopyBack) bytesToCheck -= check; flushBufOffset += check; } - else // the file contains something different than the flush buffer (resume: the file changed since last time) + else // the file contents differ from the flush buffer (resume: the file has changed since last time) { localWork.State = sqisFailed; localWork.ProblemID = ITEMPR_RESUMETESTFAILED; @@ -1924,7 +1924,7 @@ void DoCheckOrWriteToFile(CFTPDiskWork& localWork, BOOL& needCopyBack) localWork.ProblemID = ITEMPR_RESUMETESTFAILED; needCopyBack = TRUE; } - else // set the seek position in the file + else // set the file pointer { if (!skipSetSeekForWrite) { @@ -1957,7 +1957,7 @@ void DoCheckOrWriteToFile(CFTPDiskWork& localWork, BOOL& needCopyBack) { if (localWork.WriteOrReadFromOffset + CQuadWord(writtenBytes, 0) < fileSize) { // if the write finished before the end of the file, call SetEndOfFile (trim unwanted old data that should be overwritten) - SetEndOfFile(localWork.WorkFile); // we do not test success; it does not really matter + SetEndOfFile(localWork.WorkFile); // we do not check for success; it does not really matter } } } @@ -2033,7 +2033,7 @@ void DoListDirectory(CFTPDiskWork& localWork, BOOL& needCopyBack) if (search == INVALID_HANDLE_VALUE) { DWORD err = GetLastError(); - if (err != ERROR_FILE_NOT_FOUND && err != ERROR_NO_MORE_FILES) // this is an error - i.e. it's not just an empty listing + if (err != ERROR_FILE_NOT_FOUND && err != ERROR_NO_MORE_FILES) // this is an error, not just an empty listing { localWork.State = sqisFailed; localWork.ProblemID = ITEMPR_UPLOADCANNOTLISTSRCPATH; @@ -2137,7 +2137,7 @@ void DoDeleteDir(CFTPDiskWork& localWork, BOOL& needCopyBack) } } } - else // the path on disk is too long + else // disk path is too long { localWork.State = sqisFailed; localWork.ProblemID = ITEMPR_INVALIDPATHTODIR; @@ -2583,12 +2583,12 @@ CFTPDiskThread::Body() HANDLES(CloseHandle(localWork.OpenedFile)); localWork.OpenedFile = NULL; } - if (localWork.DiskListing != NULL) // on cancel deallocate the allocated listing + if (localWork.DiskListing != NULL) // on cancel, deallocate the listing { delete localWork.DiskListing; localWork.DiskListing = NULL; } - if (!doCancel) // inform the worker about the work results + if (!doCancel) // inform the worker of the work results { SocketsThread->PostSocketMessage(localWork.SocketMsg, localWork.SocketUID, localWork.MsgID, work); } @@ -2625,7 +2625,7 @@ CFTPDiskThread::Body() if (!DeleteFile(localWork.Name)) // the created file cannot have the read-only attribute TRACE_E("CFTPDiskThread::Body(): cancelling disk operation: unable to remove target file: " << localWork.Name); } - // break; // intentionally no break here! + // break; // no break here intentionally } case fdwtCheckOrWriteFile: { diff --git a/src/plugins/ftp/operats6.cpp b/src/plugins/ftp/operats6.cpp index 7bab4447e..2ecab0980 100644 --- a/src/plugins/ftp/operats6.cpp +++ b/src/plugins/ftp/operats6.cpp @@ -17,7 +17,7 @@ void CFTPWorker::HandleEventInPreparingState(CFTPWorkerEvent event, BOOL& sendQu if (SubState != fwssPrepQuitSent && SubState != fwssPrepWaitForDiskAfterQuitSent && !SocketClosed) { SubState = (SubState == fwssPrepWaitForDisk ? fwssPrepWaitForDiskAfterQuitSent : fwssPrepQuitSent); // so that we do not send "QUIT" more than once - sendQuitCmd = TRUE; // we are supposed to finish and the connection is open -> send the server the "QUIT" command (we ignore the reply, it should lead to closing the connection and nothing else matters now) + sendQuitCmd = TRUE; // we should terminate and the connection is open -> send the server the "QUIT" command (ignore the reply; it should close the connection, and nothing else matters now) } } else // normal activity @@ -32,7 +32,7 @@ void CFTPWorker::HandleEventInPreparingState(CFTPWorkerEvent event, BOOL& sendQu { case fqitCopyResolveLink: // copy: detect whether it is a link to a file or directory (object of class CFTPQueueItemCopyOrMove) case fqitMoveResolveLink: // move: detect whether it is a link to a file or directory (object of class CFTPQueueItemCopyOrMove) - break; // nothing to check + break; // nothing to verify case fqitCopyExploreDir: // explore a directory or a link to a directory for copying (object of class CFTPQueueItemCopyMoveExplore) case fqitMoveExploreDir: // explore a directory for moving (deletes the directory after completion) (object of class CFTPQueueItemCopyMoveExplore) @@ -51,7 +51,7 @@ void CFTPWorker::HandleEventInPreparingState(CFTPWorkerEvent event, BOOL& sendQu ((CFTPQueueItemCopyMoveExplore*)CurItem)->TgtPath, ((CFTPQueueItemCopyMoveExplore*)CurItem)->TgtName, CurItem->ForceAction, FALSE, NULL, NULL, NULL, 0, NULL); - if (CurItem->ForceAction != fqiaNone) // the forced action stops being valid here + if (CurItem->ForceAction != fqiaNone) // the forced action no longer applies here Queue->UpdateForceAction(CurItem, fqiaNone); if (FTPDiskThread->AddWork(&DiskWork)) { @@ -121,7 +121,7 @@ void CFTPWorker::HandleEventInPreparingState(CFTPWorkerEvent event, BOOL& sendQu switch (Oper->GetUploadCannotCreateDir()) { case CANNOTCREATENAME_AUTORENAME: - break; // autorename (when it happens) must deal even with a bad name + break; // autorename must also handle an invalid name when it gets to it case CANNOTCREATENAME_SKIP: { @@ -145,10 +145,10 @@ void CFTPWorker::HandleEventInPreparingState(CFTPWorkerEvent event, BOOL& sendQu } case fqitDeleteExploreDir: // explore directories for delete (note: links to directories are deleted as a whole, the operation's purpose is fulfilled and nothing "extra" is removed) (object of class CFTPQueueItemDelExplore) - case fqitDeleteLink: // delete for a link (object of class CFTPQueueItemDel) - case fqitDeleteFile: // delete for a file (object of class CFTPQueueItemDel) + case fqitDeleteLink: // delete a link (object of class CFTPQueueItemDel) + case fqitDeleteFile: // delete a file (object of class CFTPQueueItemDel) { - if (CurItem->Type == fqitDeleteExploreDir && ((CFTPQueueItemDelExplore*)CurItem)->IsHiddenDir || // if the directory/file/link is hidden, check what the user wants to do with it + if (CurItem->Type == fqitDeleteExploreDir && ((CFTPQueueItemDelExplore*)CurItem)->IsHiddenDir || // if the directory, file, or link is hidden, check what the user wants to do with it (CurItem->Type == fqitDeleteLink || CurItem->Type == fqitDeleteFile) && ((CFTPQueueItemDel*)CurItem)->IsHiddenFile) { @@ -208,7 +208,7 @@ void CFTPWorker::HandleEventInPreparingState(CFTPWorkerEvent event, BOOL& sendQu } } - case fqitDeleteDir: // delete for a directory (object of class CFTPQueueItemDir) + case fqitDeleteDir: // delete a directory (object of class CFTPQueueItemDir) case fqitChAttrsExploreDir: // explore directories for attribute changes (also adds an item for changing the directory attributes) (object of class CFTPQueueItemChAttrExplore) case fqitChAttrsResolveLink: // attribute change: determine whether it is a link to a directory (object of class CFTPQueueItem) case fqitChAttrsExploreDirLink: // explore a link to a directory for attribute changes (object of class CFTPQueueItem) @@ -242,7 +242,7 @@ void CFTPWorker::HandleEventInPreparingState(CFTPWorkerEvent event, BOOL& sendQu CurItem->ForceAction, strcmp(CurItem->Name, ((CFTPQueueItemCopyOrMove*)CurItem)->TgtName) != 0, NULL, NULL, NULL, 0, NULL); - if (CurItem->ForceAction != fqiaNone) // the forced action stops being valid here + if (CurItem->ForceAction != fqiaNone) // the forced action no longer applies here Queue->UpdateForceAction(CurItem, fqiaNone); if (FTPDiskThread->AddWork(&DiskWork)) { @@ -328,7 +328,7 @@ void CFTPWorker::HandleEventInPreparingState(CFTPWorkerEvent event, BOOL& sendQu switch (Oper->GetUploadCannotCreateFile()) { case CANNOTCREATENAME_AUTORENAME: - break; // autorename (when it happens) must deal even with a bad name + break; // autorename must handle even an invalid name case CANNOTCREATENAME_SKIP: { @@ -484,7 +484,7 @@ void CFTPWorker::HandleEventInPreparingState(CFTPWorkerEvent event, BOOL& sendQu case fqitChAttrsFile: // change file attributes (note: attributes cannot be changed on links) (object of class CFTPQueueItemChAttr) case fqitChAttrsDir: // change directory attributes (object of class CFTPQueueItemChAttrDir) { - if (CurItem->Type == fqitChAttrsFile && ((CFTPQueueItemChAttr*)CurItem)->AttrErr || // respond to the error "an unknown attribute should be preserved, which we cannot do" + if (CurItem->Type == fqitChAttrsFile && ((CFTPQueueItemChAttr*)CurItem)->AttrErr || // handle the error "an unknown attribute should be preserved, which we cannot do" CurItem->Type == fqitChAttrsDir && ((CFTPQueueItemChAttrDir*)CurItem)->AttrErr) { switch (Oper->GetUnknownAttrs()) @@ -533,7 +533,7 @@ void CFTPWorker::HandleEventInPreparingState(CFTPWorkerEvent event, BOOL& sendQu if (!wait) { - if (fail) // the item cannot be performed, it already has an error set, go find another item + if (fail) // the item cannot be processed; an error is already set, so find another item { CurItem = NULL; State = fwsLookingForWork; // no need to call Oper->OperationStatusMaybeChanged(), the operation state does not change (it is not paused and will not be after this change) @@ -577,7 +577,7 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ { run = FALSE; // when changed to TRUE, the loop runs again immediately BOOL closeSocket = FALSE; // TRUE = the worker's socket should be closed - if (ShouldStop) // we should terminate the worker (everything inside the loop due to 'closeSocket') + if (ShouldStop) // terminate the worker (everything is inside the loop because of 'closeSocket') { switch (SubState) { @@ -599,8 +599,8 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ case fwssConWaitForConRes: // close the connection and delete the WORKER_CONTIMEOUTTIMID timer { - // because we are already inside CSocketsThread::CritSect, this call is also possible - // from within CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no risk of dead-lock) + // since we are already in CSocketsThread::CritSect, this call is also possible + // from CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no deadlock risk) SocketsThread->DeleteTimer(UID, WORKER_CONTIMEOUTTIMID); closeSocket = TRUE; break; @@ -611,21 +611,21 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ case fwssConWaitForInitCmdRes: // close the connection and delete the WORKER_TIMEOUTTIMERID timer (it might no longer exist, but that does not matter) case fwssConWaitForSystRes: // close the connection and delete the WORKER_TIMEOUTTIMERID timer (it might no longer exist, but that does not matter) { - // because we are already inside CSocketsThread::CritSect, this call is also possible - // from within CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no risk of dead-lock) + // since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no deadlock risk) SocketsThread->DeleteTimer(UID, WORKER_TIMEOUTTIMERID); closeSocket = TRUE; break; } } } - else // normal activity + else // normal operation { switch (SubState) { case fwssNone: // determine whether we need to obtain the IP address { - if (ConnectAttemptNumber == 0) // for this worker it is the first attempt to establish a connection + if (ConnectAttemptNumber == 0) // this is the first connection attempt for this worker { ConnectAttemptNumber = 1; } @@ -643,7 +643,7 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ SubState = fwssNone; postActivate = TRUE; // post an activation for the next worker state reportWorkerChange = TRUE; - break; // end of executing the fwsConnecting state + break; // end of the fwsConnecting state } else ConnectAttemptNumber++; @@ -662,8 +662,8 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ } else // we only have a host name { - // because we are already inside CSocketsThread::CritSect, this call is also possible - // from within CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no risk of dead-lock) + // since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no deadlock risk) BOOL getHostByAddressRes = GetHostByAddress(host, ++IPRequestUID); RefreshCopiesOfUIDAndMsg(); // refresh the UID+Msg copies (they changed) if (!getHostByAddressRes) @@ -759,8 +759,8 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ ResetBuffersAndEvents(); // clear the buffers (discard old data) and initialize variables related to the connection DWORD error; - // because we are already inside CSocketsThread::CritSect, this call is also possible - // from within CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no risk of dead-lock) + // since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no deadlock risk) BOOL conRes = ConnectWithProxy(serverIP, port, proxyType, &error, host, hostPort, proxyUser, proxyPassword, hostIP); RefreshCopiesOfUIDAndMsg(); // refresh the UID+Msg copies (they changed) @@ -803,8 +803,8 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ // from within CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no risk of dead-lock) SocketsThread->DeleteTimer(UID, WORKER_CONTIMEOUTTIMID); - // set the worker state so it starts waiting for a command reply (even if we did not - // send any command, we wait for the server response) - set the timeout for receiving a command reply + // set the worker state to wait for a command reply (even though we did not + // send any command, we are waiting for the server response) and set the timeout for receiving it CommandState = fwcsWaitForLoginPrompt; int serverTimeout = Config.GetServerRepliesTimeout() * 1000; if (serverTimeout < 1000) @@ -815,7 +815,7 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ WORKER_TIMEOUTTIMERID, NULL); // ignore the error, at worst the user hits Stop SubState = fwssConWaitForPrompt; - // run = TRUE; // pointless (no event has occurred yet) + // run = TRUE; // no point yet (no event has occurred yet) break; } @@ -832,8 +832,8 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ case fweConTimeout: { - // because we are already inside CSocket::SocketCritSect, this call is also possible - // from within CFTPWorker::WorkerCritSect (no risk of dead-lock) + // because we are already in CSocket::SocketCritSect, this call is also allowed + // from CFTPWorker::WorkerCritSect (no deadlock risk) if (!GetProxyTimeoutDescr(ErrorDescr, FTPWORKER_ERRDESCR_BUFSIZE)) lstrcpyn(ErrorDescr, LoadStr(IDS_OPENCONTIMEOUT), FTPWORKER_ERRDESCR_BUFSIZE); CorrectErrorDescr(); @@ -878,13 +878,13 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ SubState = fwssConReconnect; run = TRUE; } - else // unexpected response, ignore it + else // unexpected reply, ignore it { TRACE_E("Unexpected reply: " << CopyStr(errBuf, 50 + FTP_MAX_PATH, reply, replySize)); } } } - else // not an FTP server + else // not an FTP server error { _snprintf_s(ErrorDescr, _TRUNCATE, LoadStr(IDS_NOTFTPSERVERERROR), CopyStr(errBuf, 50 + FTP_MAX_PATH, reply, replySize)); @@ -922,7 +922,7 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ SubState = fwssConWaitForAUTHCmdRes; break; - case fwssConSendPBSZ: // After AUTH TLS, but only if encrypting also data + case fwssConSendPBSZ: // After AUTH TLS, but only if data is also encrypted strcpy(buf, "PBSZ 0\r\n"); cmdLen = (int)strlen(buf); strcpy(errBuf, buf); // For logging purposes @@ -958,7 +958,7 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ { if (buf[0] == 0) // end of the script { - if (ProxyScriptLastCmdReply == -1) // the script does not contain any command that would be sent to the server - e.g. commands were skipped because they contain optional variables + if (ProxyScriptLastCmdReply == -1) // the script does not contain any command to send to the server, e.g. because commands were skipped due to optional variables { lstrcpyn(ErrorDescr, LoadStr(IDS_INCOMPLETEPRXSCR2), FTPWORKER_ERRDESCR_BUFSIZE); CorrectErrorDescr(); @@ -970,7 +970,7 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ { Logs.LogMessage(LogUID, LoadStr(IDS_LOGMSGLOGINSUCCESS), -1, TRUE); NextInitCmd = 0; // send the first init-ftp command - SubState = Oper->GetCompressData() ? fwssConSendMODEZ : fwssConSendInitCmds; // we are logged in, now send the init-ftp commands + SubState = Oper->GetCompressData() ? fwssConSendMODEZ : fwssConSendInitCmds; // we are logged in, now send the initial FTP commands run = TRUE; } else // FTP_DIGIT_1(ProxyScriptLastCmdReply) == FTP_D1_PARTIALSUCCESS // e.g. 331 User name okay, need password @@ -982,7 +982,7 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ } } } - else // there is another command to send + else // another command remains to be sent { sendCmd = TRUE; SubState = fwssConWaitForScriptCmdRes; @@ -1040,7 +1040,7 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ HANDLES(EnterCriticalSection(&WorkerCritSect)); if (ret) { - if (unverifiedCert != NULL) // close the connection and retry only after the user learns about the untrusted certificate and accepts it or ensures it becomes trusted (in the Solve Error dialog) + if (unverifiedCert != NULL) // close the connection and retry only after the user is informed about the untrusted certificate and either accepts it or makes it trusted (in the Solve Error dialog) { if (UnverifiedCertificate != NULL) UnverifiedCertificate->Release(); @@ -1095,7 +1095,7 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ closeSocket = TRUE; // close the connection (no point in continuing) - if (retryLoginWithoutAsking) // try again + if (retryLoginWithoutAsking) // retry { SubState = fwssConReconnect; run = TRUE; @@ -1177,8 +1177,8 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ { BOOL retryLoginWithoutAsking; if (FTP_DIGIT_1(replyCode) == FTP_D1_TRANSIENTERROR) - { // convenient handling of the "too many users" error - no questions, immediately retry - // this may be a problem: this code is accompanied by a message that requires changing the user/password + { // convenient handling of the "too many users" error - retry immediately without prompting +// possible issue: this code may be followed by a message that requires changing the user/password retryLoginWithoutAsking = TRUE; } else @@ -1189,7 +1189,7 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ CorrectErrorDescr(); closeSocket = TRUE; // close the connection (no point in continuing) - if (retryLoginWithoutAsking) // try again + if (retryLoginWithoutAsking) // retry { SubState = fwssConReconnect; run = TRUE; @@ -1266,7 +1266,7 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ if (sendCmd) // sending another init-ftp command { SubState = fwssConWaitForInitCmdRes; - // run = TRUE; // pointless (no event has occurred yet) + // run = TRUE; // no point yet (no event has occurred yet) } else // all init-ftp commands have been sent (or none exist) { @@ -1303,7 +1303,7 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ PrepareFTPCommand(buf, 200 + FTP_MAX_PATH, errBuf, 50 + FTP_MAX_PATH, ftpcmdSystem, &cmdLen); // cannot report an error sendCmd = TRUE; SubState = fwssConWaitForSystRes; - // run = TRUE; // pointless (no event has occurred yet) + // run = TRUE; // no point yet (no event has occurred yet) break; } @@ -1362,20 +1362,20 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ // wait for a reconnect ConnectAttemptNumber++; - // because we are already inside CSocketsThread::CritSect, this call is also possible - // from within CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no risk of dead-lock) + // since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no deadlock risk) SocketsThread->DeleteTimer(UID, WORKER_RECONTIMEOUTTIMID); // start a timer for the next connect attempt int delayBetweenConRetries = Config.GetDelayBetweenConRetries() * 1000; - // because we are already inside CSocketsThread::CritSect, this call is also possible - // from within CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no risk of dead-lock) + // since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no deadlock risk) SocketsThread->AddTimer(Msg, UID, GetTickCount() + delayBetweenConRetries, WORKER_RECONTIMEOUTTIMID, NULL); // ignore the error, at worst the user hits Stop State = fwsWaitingForReconnect; // NOTE: assumes ErrorDescr is set; no need to call Oper->OperationStatusMaybeChanged(), the operation state does not change (it is not paused and will not be after this change) SubState = fwssNone; - // postActivate = TRUE; // no reason, waiting for the timeout + // postActivate = TRUE; // no reason to do this, waiting for the timeout reportWorkerChange = TRUE; } } @@ -1387,8 +1387,8 @@ void CFTPWorker::HandleEventInConnectingState(CFTPWorkerEvent event, BOOL& sendQ { HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // because we are already inside CSocketsThread::CritSect, this call is also possible - // from within CSocket::SocketCritSect (no risk of dead-lock) + // because we are already in CSocketsThread::CritSect, this call is also allowed + // from CSocket::SocketCritSect (no deadlock risk) ForceClose(); HANDLES(EnterCriticalSection(&WorkerCritSect)); @@ -1472,7 +1472,7 @@ BOOL CFTPWorker::ParseListingToFTPQueue(TIndirectArray* ftpQueueI { CFTPQueueItemCopyMoveExplore* cmItem = (CFTPQueueItemCopyMoveExplore*)CurItem; lstrcpyn(targetPath, cmItem->TgtPath, MAX_PATH); - SalamanderGeneral->SalPathAppend(targetPath, cmItem->TgtName, MAX_PATH); // must succeed, the directory already exists on disk and its full name is at most PATH_MAX_PATH-1 characters + SalamanderGeneral->SalPathAppend(targetPath, cmItem->TgtName, MAX_PATH); // must succeed; the directory already exists on disk and its full name is at most MAX_PATH-1 characters } else targetPath[0] = 0; diff --git a/src/plugins/ftp/operats7.cpp b/src/plugins/ftp/operats7.cpp index 9fec2ffbf..817d18320 100644 --- a/src/plugins/ftp/operats7.cpp +++ b/src/plugins/ftp/operats7.cpp @@ -18,8 +18,8 @@ void CFTPWorker::OpenActDataCon(CFTPWorkerSubState waitForListen, char* errBuf, HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // Since we are already inside the CSocketsThread::CritSect section, these calls - // are possible even from the CSocket::SocketCritSect section (no risk of deadlock). + // Since we are already in CSocketsThread::CritSect, these calls + // are allowed even from CSocket::SocketCritSect (there is no risk of deadlock). GetLocalIP(&localIP, NULL); // it should hardly be able to return an error BOOL retOpenForListening = FALSE; BOOL listenError = TRUE; @@ -41,12 +41,12 @@ void CFTPWorker::OpenActDataCon(CFTPWorkerSubState waitForListen, char* errBuf, int serverTimeout = Config.GetServerRepliesTimeout() * 1000; if (serverTimeout < 1000) serverTimeout = 1000; // at least one second - // Since we are already inside the CSocketsThread::CritSect section, this call - // is possible even from the CSocket::SocketCritSect and CFTPWorker::WorkerCritSect sections (no risk of deadlock). + // Since we are already in CSocketsThread::CritSect, this call + // is possible even from CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (there is no risk of deadlock). SocketsThread->AddTimer(Msg, UID, GetTickCount() + serverTimeout, WORKER_LISTENTIMEOUTTIMID, NULL); // ignore error; at worst the user presses Stop } - else // failed to open a "listen" socket for receiving the data connection from + else // failed to open a "listen" socket for receiving the data connection from the server { // the server (a local operation that should almost never happen) or cannot open a connection to the proxy server if (WorkerDataCon != NULL) { @@ -112,7 +112,7 @@ void CFTPWorker::WaitForListen(CFTPWorkerEvent event, BOOL& handleShouldStop, ch HANDLES(LeaveCriticalSection(&WorkerCritSect)); // Since we are already inside the CSocketsThread::CritSect section, this call // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). - if (WorkerDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system will attempt a graceful shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) WorkerDataCon->FreeFlushData(); DeleteSocket(WorkerDataCon); @@ -155,7 +155,7 @@ void CFTPWorker::WaitForListen(CFTPWorkerEvent event, BOOL& handleShouldStop, ch sendCmd = TRUE; SubState = waitForPORTRes; } - else // error while opening the "listen" port on the proxy server - perform a retry... + else // error while opening the "listen" port on the proxy server - retry... { // Close the data connection. if (WorkerDataCon != NULL) @@ -163,7 +163,7 @@ void CFTPWorker::WaitForListen(CFTPWorkerEvent event, BOOL& handleShouldStop, ch HANDLES(LeaveCriticalSection(&WorkerCritSect)); // Since we are already inside the CSocketsThread::CritSect section, this call // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). - if (WorkerDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system will attempt a "graceful" shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) WorkerDataCon->FreeFlushData(); DeleteSocket(WorkerDataCon); @@ -196,7 +196,7 @@ void CFTPWorker::WaitForListen(CFTPWorkerEvent event, BOOL& handleShouldStop, ch errBuf[0] = 0; // Since we are already inside the CSocketsThread::CritSect section, this call // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). - if (WorkerDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system will attempt a graceful shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) WorkerDataCon->FreeFlushData(); DeleteSocket(WorkerDataCon); @@ -267,8 +267,8 @@ void CFTPWorker::WaitForPASVRes(CFTPWorkerEvent event, char* reply, int replySiz int logUID = LogUID; HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // Since we are already inside the CSocketsThread::CritSect section, these calls - // They can also be called from the CSocket::SocketCritSect section (no risk of deadlock). + // Since we are already in CSocketsThread::CritSect, these calls + // can also be made from CSocket::SocketCritSect (no deadlock risk). if (WorkerDataCon != NULL) { WorkerDataCon->SetPassive(ip, port, logUID); @@ -311,13 +311,13 @@ void CFTPWorker::WaitForPASVRes(CFTPWorkerEvent event, char* reply, int replySiz break; } - case fweCmdConClosed: // connection closed/timed out (description see ErrorDescr) -> try to restore it + case fweCmdConClosed: // connection closed/timed out (see ErrorDescr) -> try to restore it { if (WorkerDataCon != NULL) { HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // Since we are already inside the CSocketsThread::CritSect section, this call - // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). + // Since we are already in CSocketsThread::CritSect, this call + // can also be made from CSocket::SocketCritSect (no deadlock risk). DeleteSocket(WorkerDataCon); // no connection has been established yet; it will only be deallocated WorkerDataCon = NULL; HANDLES(EnterCriticalSection(&WorkerCritSect)); @@ -343,14 +343,14 @@ void CFTPWorker::WaitForPORTRes(CFTPWorkerEvent event, BOOL& nextLoop, BOOL& con break; } - case fweCmdConClosed: // connection closed/timed out (description see ErrorDescr) -> try to restore it + case fweCmdConClosed: // connection closed/timed out (see ErrorDescr for details) -> try to reestablish it { if (WorkerDataCon != NULL) { HANDLES(LeaveCriticalSection(&WorkerCritSect)); // Since we are already inside the CSocketsThread::CritSect section, this call // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). - if (WorkerDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system will attempt a graceful shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) WorkerDataCon->FreeFlushData(); DeleteSocket(WorkerDataCon); @@ -377,7 +377,7 @@ void CFTPWorker::SetTypeA(BOOL& handleShouldStop, char* errBuf, char* buf, int& HANDLES(LeaveCriticalSection(&WorkerCritSect)); // Since we are already inside the CSocketsThread::CritSect section, this call // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). - if (WorkerDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system will attempt a "graceful" shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) WorkerDataCon->FreeFlushData(); DeleteSocket(WorkerDataCon); @@ -413,7 +413,7 @@ void CFTPWorker::WaitForTYPERes(CFTPWorkerEvent event, int replyCode, BOOL& next // case fweCmdInfoReceived: // ignore "1xx" replies (they are only written to the log) case fweCmdReplyReceived: { - if (FTP_DIGIT_1(replyCode) == FTP_D1_SUCCESS) // success is returned (should be 200) + if (FTP_DIGIT_1(replyCode) == FTP_D1_SUCCESS) // a success reply was received (it should be 200) CurrentTransferMode = trMode; // the transfer mode was changed else CurrentTransferMode = ctrmUnknown; // unknown error; it may not matter at all, but we will not cache the data transfer mode @@ -430,7 +430,7 @@ void CFTPWorker::WaitForTYPERes(CFTPWorkerEvent event, int replyCode, BOOL& next HANDLES(LeaveCriticalSection(&WorkerCritSect)); // Since we are already inside the CSocketsThread::CritSect section, this call // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). - if (WorkerDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system will attempt a graceful shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) WorkerDataCon->FreeFlushData(); DeleteSocket(WorkerDataCon); @@ -452,7 +452,7 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui BOOL& conClosedRetryItem, BOOL& lookForNewWork, BOOL& handleShouldStop, BOOL* listingNotAccessible) { - // NOTE: this method is also used for listing the target path during upload (UploadDirGetTgtPathListing==TRUE)!!! + // NOTE: this method is also used to list the target path during upload (UploadDirGetTgtPathListing==TRUE). if (listingNotAccessible != NULL) *listingNotAccessible = FALSE; char* tgtPath = NULL; @@ -492,7 +492,7 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui lstrcpyn(ftpPath, CurItem->Path, FTP_MAX_PATH); CFTPServerPathType type = Oper->GetFTPServerPathType(ftpPath); if (UploadDirGetTgtPathListing || FTPPathAppend(type, ftpPath, FTP_MAX_PATH, CurItem->Name, TRUE)) - { // we have the path; send CWD to the server to enter the inspected directory + { // we have the path; send CWD to the server for the directory being explored _snprintf_s(errText, 200 + FTP_MAX_PATH, _TRUNCATE, LoadStr(IDS_LOGMSGLISTINGPATH), ftpPath); Logs.LogMessage(LogUID, errText, -1, TRUE); @@ -579,7 +579,7 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui else { if (UploadDirGetTgtPathListing || FTPGetDirectoryFromReply(reply, replySize, ftpPath, FTP_MAX_PATH)) - { // we have the working path; check whether a cycle (endless loop) is occurring + { // We have the working path; check whether a cycle (infinite loop) is occurring BOOL cycle = FALSE; if (!UploadDirGetTgtPathListing) { @@ -597,7 +597,7 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui cycle = TRUE; } } - // Check whether we have already visited this path, which would mean entering an endless loop. + // Check whether we have already visited this path, which would mean that we have entered an infinite loop. if (!cycle && Oper->IsAlreadyExploredPath(WorkingPath)) cycle = TRUE; } @@ -608,7 +608,7 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui Queue->UpdateItemState(CurItem, sqisFailed, ITEMPR_DIREXPLENDLESSLOOP, NO_ERROR, NULL, Oper); lookForNewWork = TRUE; } - else // everything is OK; allocate the data connection + else // everything is OK; allocate the data connection socket { if (WorkerDataCon != NULL) TRACE_E("Unexpected situation in CFTPWorker::HandleEventInWorkingState2(): WorkerDataCon is not NULL before starting data-connection!"); @@ -628,8 +628,8 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui if (WorkerDataCon != NULL) { HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // Since we are already inside the CSocketsThread::CritSect section, this call - // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) DeleteSocket(WorkerDataCon); // it will only be deallocated WorkerDataCon = NULL; HANDLES(EnterCriticalSection(&WorkerCritSect)); @@ -651,15 +651,15 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui WorkerDataConState = wdcsOnlyAllocated; HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // Since we are already inside the CSocketsThread::CritSect section, this call - // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) WorkerDataCon->SetPostMessagesToWorker(TRUE, Msg, UID, WORKER_DATACON_CONNECTED, WORKER_DATACON_CLOSED, -1 /* not needed for listings */, WORKER_DATACON_LISTENINGFORCON); WorkerDataCon->SetGlobalLastActivityTime(Oper->GetGlobalLastActivityTime()); // exploring directories for delete/change-attr and upload listing are not measured (the meter is used - // otherwise see SMPLCMD_APPROXBYTESIZE + upload: the meter is for upload, but this is download) + // differently, see SMPLCMD_APPROXBYTESIZE + upload: the meter is for upload, but this is download) if (CurItem->Type != fqitDeleteExploreDir && CurItem->Type != fqitChAttrsExploreDir && CurItem->Type != fqitChAttrsExploreDirLink && @@ -756,9 +756,9 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui if (WorkerDataCon != NULL) { HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // Since we are already inside the CSocketsThread::CritSect section, this call - // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). - if (WorkerDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system will attempt a "graceful" shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) DeleteSocket(WorkerDataCon); WorkerDataCon = NULL; @@ -791,8 +791,8 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui if (WorkerDataCon != NULL) { HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // Since we are already inside the CSocketsThread::CritSect section, this call - // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) WorkerDataCon->ActivateConnection(); HANDLES(EnterCriticalSection(&WorkerCritSect)); } @@ -835,9 +835,9 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); if (FTP_DIGIT_1(replyCode) != FTP_D1_SUCCESS || !WorkerDataCon->IsTransfering(&trFinished) && !trFinished) - { // the server returns a listing error or the connection was not established - // Since we are already inside the CSocketsThread::CritSect section, this call - // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). + { // the server returned a listing error or the connection was not established +// Since we are already in CSocketsThread::CritSect, this call +// is allowed even from CSocket::SocketCritSect (no deadlock risk) if (WorkerDataCon->IsConnected()) { // close the "data connection", the system will attempt a "graceful" WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) @@ -867,15 +867,15 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui if (WorkerDataCon != NULL) { HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // Since we are already inside the CSocketsThread::CritSect section, this call - // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). - if (WorkerDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system will attempt a "graceful" shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) HANDLES(EnterCriticalSection(&WorkerCritSect)); } } - // If we do not have to wait for the "data connection" to finish, proceed to processing the LIST command replyCode. + // If we do not have to wait for the data connection to finish, proceed to processing the LIST command reply code. SubState = waitForDataConFinish ? fwssWorkExplWaitForDataConFinish : fwssWorkExplProcessLISTRes; if (!waitForDataConFinish) nextLoop = TRUE; @@ -887,9 +887,9 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui if (WorkerDataCon != NULL) { HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // Since we are already inside the CSocketsThread::CritSect section, this call - // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). - if (WorkerDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system will attempt a "graceful" shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) DeleteSocket(WorkerDataCon); WorkerDataCon = NULL; @@ -910,8 +910,8 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui if (WorkerDataCon != NULL) { HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // Since we are already inside the CSocketsThread::CritSect section, this call - // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) con = WorkerDataCon->IsConnected(); HANDLES(EnterCriticalSection(&WorkerCritSect)); } @@ -935,9 +935,9 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui if (WorkerDataCon != NULL) { HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // Since we are already inside the CSocketsThread::CritSect section, this call - // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). - if (WorkerDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system will attempt a "graceful" shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) DeleteSocket(WorkerDataCon); WorkerDataCon = NULL; @@ -958,9 +958,9 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui BOOL lowMem, noDataTransTimeout; int sslErrorOccured; HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // Since we are already inside the CSocketsThread::CritSect section, this call - // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). - if (WorkerDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system will attempt a "graceful" shutdown { WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) TRACE_E("Unexpected situation in CFTPWorker::HandleEventInWorkingState2(): data connection has left opened!"); @@ -970,8 +970,8 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui errBuf[0] = 0; if (lowMem) // the "data connection" reports out-of-memory ("always false") { - // Since we are already inside the CSocketsThread::CritSect section, this call - // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). + // Since we are already inside CSocketsThread::CritSect, this call + // can also be made from CSocket::SocketCritSect (no deadlock risk). DeleteSocket(WorkerDataCon); WorkerDataCon = NULL; HANDLES(EnterCriticalSection(&WorkerCritSect)); @@ -984,11 +984,11 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui else { if (err != NO_ERROR && !IsConnected()) - { // the LIST reply did arrive, but while waiting for the transfer to finish through the data connection - // the connection was interrupted (both data connection and control connection) -> RETRY + { // the LIST reply arrived, but while waiting for the transfer to finish over the data connection +// both connections were interrupted (data connection and control connection) -> RETRY - // Since we are already inside the CSocketsThread::CritSect section, this call - // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) DeleteSocket(WorkerDataCon); WorkerDataCon = NULL; HANDLES(EnterCriticalSection(&WorkerCritSect)); @@ -1010,7 +1010,7 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui { // obtain the data from the "data connection" allocatedListing = WorkerDataCon->GiveData(&allocatedListingLen, &decomprErr); - if (decomprErr) // on decompression error discard the result and display the error + if (decomprErr) // on decompression error, discard the result and report the error { listingIsNotOK = TRUE; allocatedListingLen = 0; @@ -1018,8 +1018,8 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui allocatedListing = NULL; } } - // Since we are already inside the CSocketsThread::CritSect section, this call - // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) DeleteSocket(WorkerDataCon); WorkerDataCon = NULL; HANDLES(EnterCriticalSection(&WorkerCritSect)); @@ -1032,10 +1032,10 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui FTP_DIGIT_1(listCmdReplyCode) == FTP_D1_ERROR)) { HANDLES(LeaveCriticalSection(&WorkerCritSect)); - if (IsConnected()) // "Manually" close the control connection. + if (IsConnected()) // close the control connection manually { - // Since we are already inside the CSocketsThread::CritSect section, this call - // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) ForceClose(); // Sending QUIT would be cleaner, but a certificate change is very unlikely, so it is not worth bothering with that ;-) } HANDLES(EnterCriticalSection(&WorkerCritSect)); @@ -1066,11 +1066,11 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui (FTP_DIGIT_2(listCmdReplyCode) == FTP_D2_CONNECTION || FTP_DIGIT_2(listCmdReplyCode) != FTP_D2_CONNECTION && !isVMSFileNotFound) && ListCmdReplyText != NULL) - { // if we do not have a network error description from the server, use the system description + { // if we do not have an error description from the server, use the system description lstrcpyn(errText, ListCmdReplyText, 200 + FTP_MAX_PATH); } - if (errText[0] == 0 && errBuf[0] != 0) // try to take the error text from the proxy server + if (errText[0] == 0 && errBuf[0] != 0) // try to get the error text from the proxy server lstrcpyn(errText, errBuf, 200 + FTP_MAX_PATH); if (errText[0] == 0 && decomprErr) @@ -1133,14 +1133,14 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui Oper->GetListingServerType(listingServerType); BOOL err2 = allocatedListing == NULL; - if (UploadDirGetTgtPathListing) // upload listing: store the listing in the cache + if (UploadDirGetTgtPathListing) // upload listing: store the listing in cache { err2 |= welcomeReply == NULL || systReply == NULL; if (!err2) { unsigned short port; Oper->GetUserHostPort(userTmp, host, &port); - // The call UploadListingCache.ListingFinished() is possible only because we are in the CSocketsThread::CritSect section. + // UploadListingCache.ListingFinished() can be called only because we are in CSocketsThread::CritSect err2 = !UploadListingCache.ListingFinished(userTmp, host, port, tgtPath, pathType, allocatedListing, allocatedListingLen, listingDate, welcomeReply, systReply, @@ -1148,7 +1148,7 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui uploadFinished = !err2; } } - else // download + delete + change-attrs: parse the listing and add new items to the queue + else // download + delete + change attributes: parse the listing and add new items to the queue { BOOL isVMS = pathType == ftpsptOpenVMS; BOOL isAS400 = pathType == ftpsptAS400; @@ -1179,7 +1179,7 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui err2 |= ftpQueueItems == NULL || !HaveWorkingPath; if (!err2) { - if (listingServerType[0] != 0) // this is not autodetection; find listingServerType + if (listingServerType[0] != 0) // this is not autodetection; find the matching listingServerType { int i; for (i = 0; i < serverTypeListCount; i++) @@ -1201,7 +1201,7 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui { needSimpleListing = FALSE; // we parsed the listing successfully } - break; // we found the required server type; finish + break; // we found the required server type; stop } } if (i == serverTypeListCount) @@ -1308,7 +1308,7 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui Queue->UpdateItemState(CurItem, sqisFailed, ITEMPR_UNABLETOPARSELISTING, NO_ERROR, NULL, Oper); lookForNewWork = TRUE; } - else // log which parser handled it + else // log which parser parsed it { if (listingServerType[0] != 0) // "always true" { @@ -1373,7 +1373,7 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui case fqitChAttrsExploreDir: // explore directories for attribute changes (also adds an item for changing directory attributes) (object of class CFTPQueueItemChAttrExplore) { - if (selDirs) // relevant only when attributes should be set on the inspected directory + if (selDirs) // relevant only when attributes are to be set on the inspected directory { skip = FALSE; type = fqitChAttrsDir; @@ -1386,7 +1386,7 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui if (rights != NULL && GetAttrsFromUNIXRights(&actAttr, &attrDiff, rights)) { DWORD changeMask = (~attrAndMask | attrOrMask) & 0777; - if ((attrDiff & changeMask) == 0 && // we do not change any unknown attribute + if ((attrDiff & changeMask) == 0 && // we do not change any unknown attributes (actAttr & changeMask) == (((actAttr & attrAndMask) | attrOrMask) & changeMask)) // we do not change any known attribute { // nothing to do (no attribute change) skip = TRUE; @@ -1395,7 +1395,7 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui { if (((attrDiff & attrAndMask) & attrOrMask) != (attrDiff & attrAndMask)) { // problem: an unknown attribute needs to be preserved, which we cannot do - actAttr |= attrDiff; // put at least 'x' there when we do not know 's' or 't' or whatever is there now (see UNIX permissions) + actAttr |= attrDiff; // put at least 'x' there, since we cannot preserve the current 's' or 't' value or whatever is there now (see UNIX permissions) attrErr = TRUE; } actAttr = (actAttr & attrAndMask) | attrOrMask; @@ -1405,7 +1405,7 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui { actAttr = attrOrMask; // assume no permissions (actAttr==0) if (((~attrAndMask | attrOrMask) & 0777) != 0777) - { // problem: permissions are unknown and some attribute must be preserved (we do not know its value -> we cannot keep it) + { // problem: permissions are unknown and some attribute should be preserved (we do not know its value, so we cannot preserve it) attrErr = TRUE; } } @@ -1456,7 +1456,7 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui // case fqitChAttrsExploreDirLink: // explore a directory link for attribute changes (object of class CFTPQueueItem) } - BOOL parentItemAdded = FALSE; // TRUE = there is a "parent" item at the end of ftpQueueItems (for example deleting a directory (Delete and Move), changing directory attributes (Change Attrs)) + BOOL parentItemAdded = FALSE; // TRUE = ftpQueueItems ends with a "parent" item (for example when deleting a directory (Delete and Move) or changing directory attributes (Change Attrs)) int parentUID = CurItem->ParentUID; // parent UID for items created by expanding the directory if (item != NULL) { @@ -1484,7 +1484,7 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui } else { - if (!skip) // only if it is not skipping the item but a low-memory error + if (!skip) // only if this is not skipping the item but a low-memory error { TRACE_E(LOW_MEMORY); err2 = TRUE; @@ -1494,7 +1494,7 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui if (!err2) { // For items created by exploring the directory (does not apply to a possible "parent" item at the end of the array): - // set the parents and count items in the states "Skipped", "Failed", and those other than Done + // set the parents and count items in the "Skipped" and "Failed" states, and those not in "Done" int count = ftpQueueItems->Count - (parentItemAdded ? 1 : 0); int childItemsNotDone = 0; int childItemsSkipped = 0; @@ -1598,14 +1598,14 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui // Inform all potentially sleeping workers that new work has appeared. HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // Since we are already inside the CSocketsThread::CritSect section, this call - // It can also be called from the CSocket::SocketCritSect section (no risk of deadlock). + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect (no deadlock risk) Oper->PostNewWorkAvailable(FALSE); HANDLES(EnterCriticalSection(&WorkerCritSect)); } else { - err2 = TRUE; // out of memory -> write the error into the item + err2 = TRUE; // out of memory -> record the error in the item Queue->UnlockForMoreOperations(); } } @@ -1645,8 +1645,8 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui // If we are exploring directories for delete/change-attr or doing an upload listing, we must // reset the speed meter (explore speed and upload listing are not measured; this - // that moment can therefore be the start of measuring speed for delete/change-attr/upload operations), - // so that the time-left is shown correctly in the operation dialog. + // moment can therefore be the start of speed measurement for delete/change-attr/upload operations), + // so that the time left is shown correctly in the operation dialog if (delOrChangeAttrExpl || UploadDirGetTgtPathListing) { Oper->GetGlobalTransferSpeedMeter()->Clear(); @@ -1660,8 +1660,8 @@ void CFTPWorker::HandleEventInWorkingState2(CFTPWorkerEvent event, BOOL& sendQui postActivate = TRUE; // trigger to continue working reportWorkerChange = TRUE; // we need to hide any progress while fetching the listing - // Since we are already inside the CSocketsThread::CritSect section, this call - // It can also be called from the CSocket::SocketCritSect and CFTPWorker::WorkerCritSect sections (no risk of deadlock). + // Since we are already in CSocketsThread::CritSect, this call + // is allowed even from CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no deadlock risk). SocketsThread->DeleteTimer(UID, WORKER_STATUSUPDATETIMID); // cancel any timer from the previous work } break; diff --git a/src/plugins/ftp/operats8.cpp b/src/plugins/ftp/operats8.cpp index e284321b0..6b6d582e1 100644 --- a/src/plugins/ftp/operats8.cpp +++ b/src/plugins/ftp/operats8.cpp @@ -91,7 +91,7 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui char userBuf[USER_MAX_SIZE]; unsigned short portBuf; - // ensure flushing the data from the data connection to the disk thread and once the flush is complete + // ensure the data is flushed from the data connection to the disk thread, and once the flush is complete // return the buffer to the data connection (if it is already closed, just deallocate the buffer) if (!ShouldStop && WorkerDataCon != NULL && event == fweDataConFlushData || event == fweDiskWorkWriteFinished) @@ -102,8 +102,8 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui char* flushBuffer; int validBytesInFlushBuffer; BOOL deleteTgtFile; - // since we are already in the CSocketsThread::CritSect section, this call - // is also possible from the CSocket::SocketCritSect section (no dead-lock risk) + // since we are already in CSocketsThread::CritSect, this call + // is also possible from CSocket::SocketCritSect (no deadlock risk) BOOL haveFlushData = WorkerDataCon->GiveFlushData(&flushBuffer, &validBytesInFlushBuffer, &deleteTgtFile); HANDLES(EnterCriticalSection(&WorkerCritSect)); @@ -139,7 +139,7 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); // since we are already in the CSocketsThread::CritSect section, this call // is also possible from the CSocket::SocketCritSect section (no dead-lock risk) - if (WorkerDataCon->IsConnected()) // close the "data connection", the system tries to do a "graceful" + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system tries to perform a "graceful" shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) WorkerDataCon->FreeFlushData(); DeleteSocket(WorkerDataCon); @@ -180,7 +180,7 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); // since we are already in the CSocketsThread::CritSect section, this call // is also possible from the CSocket::SocketCritSect section (no dead-lock risk) - if (WorkerDataCon->IsConnected()) // close the "data connection", the system tries to do a "graceful" + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system will attempt a "graceful" shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) WorkerDataCon->FreeFlushData(); DeleteSocket(WorkerDataCon); @@ -219,8 +219,8 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui if (WorkerDataCon != NULL) // if the data connection exists, return the buffer for reuse { HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // since we are already in the CSocketsThread::CritSect section, this call - // is also possible from the CSocket::SocketCritSect section (no dead-lock risk) + // since we are already in CSocketsThread::CritSect, this call + // can also be made from CSocket::SocketCritSect (no deadlock risk) WorkerDataCon->FlushDataFinished(DiskWork.FlushDataBuffer, TRUE); if (!WorkerDataCon->IsConnected()) { @@ -267,7 +267,7 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); // since we are already in the CSocketsThread::CritSect section, this call // is also possible from the CSocket::SocketCritSect section (no dead-lock risk) - if (WorkerDataCon->IsConnected()) // close the "data connection", the system tries to do a "graceful" + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system will attempt a graceful shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) WorkerDataCon->FreeFlushData(); DeleteSocket(WorkerDataCon); @@ -353,8 +353,8 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui WorkerDataConState = wdcsOnlyAllocated; HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // since we are already in the CSocketsThread::CritSect section, this call - // is also possible from the CSocket::SocketCritSect section (no dead-lock risk) + // since we are already in CSocketsThread::CritSect, this call + // is also possible from CSocket::SocketCritSect (no deadlock risk) WorkerDataCon->SetPostMessagesToWorker(TRUE, Msg, UID, WORKER_DATACON_CONNECTED, WORKER_DATACON_CLOSED, @@ -439,7 +439,7 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); // since we are already in the CSocketsThread::CritSect section, this call // is also possible from the CSocket::SocketCritSect section (no dead-lock risk) - if (WorkerDataCon->IsConnected()) // close the "data connection", the system tries to do a "graceful" + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system tries to perform a "graceful" shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) WorkerDataCon->FreeFlushData(); DeleteSocket(WorkerDataCon); @@ -530,7 +530,7 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); // since we are already in the CSocketsThread::CritSect section, this call // is also possible from the CSocket::SocketCritSect section (no dead-lock risk) - if (WorkerDataCon->IsConnected()) // close the "data connection", the system tries to do a "graceful" + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system will try a "graceful" shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) WorkerDataCon->FreeFlushData(); DeleteSocket(WorkerDataCon); @@ -555,7 +555,7 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); // since we are already in the CSocketsThread::CritSect section, this call // is also possible from the CSocket::SocketCritSect section (no dead-lock risk) - if (WorkerDataCon->IsConnected()) // close the "data connection", the system tries to do a "graceful" + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system attempts a graceful shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) WorkerDataCon->FreeFlushData(); DeleteSocket(WorkerDataCon); @@ -589,7 +589,7 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); // since we are already in the CSocketsThread::CritSect section, this call // is also possible from the CSocket::SocketCritSect section (no dead-lock risk) - if (WorkerDataCon->IsConnected()) // close the "data connection", the system tries to do a "graceful" + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system attempts a graceful shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) WorkerDataCon->FreeFlushData(); DeleteSocket(WorkerDataCon); @@ -661,7 +661,7 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui if (!ResumingOpenedFile && // during resume some servers return the file size and others the remaining size to download (there is no way to tell which one it is, so they cannot be used) FTPGetDataSizeInfoFromSrvReply(size, reply, replySize)) { - // if (ResumingOpenedFile && ) // WARNING, NOT ALWAYS TRUE: during resume we do not receive the total file size, only the resumed part -> must add it to 'size' + // if (ResumingOpenedFile && ) // WARNING, NOT ALWAYS TRUE: when resuming, we do not receive the total file size, only the size of the resumed part -> must add the resumed offset to 'size' // size += OpenedFileResumedAtOffset; if (!curItem->SizeInBytes || curItem->Size != size) { // write the newly determined file size into the item (for overall progress + conversion of block/record/etc. sizes to bytes) @@ -696,9 +696,9 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); if (FTP_DIGIT_1(replyCode) != FTP_D1_SUCCESS) { // the server reports an error retrieving the file - // since we are already in the CSocketsThread::CritSect section, this call - // is also possible from the CSocket::SocketCritSect section (no dead-lock risk) - if (WorkerDataCon->IsConnected()) // close the "data connection", the system tries to do a "graceful" + // since we are already in CSocketsThread::CritSect, this call + // is also possible from CSocket::SocketCritSect (no deadlock risk) + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system attempts a graceful shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) } else @@ -708,11 +708,11 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui waitForDataConFinish = TRUE; if (!WorkerDataCon->IsTransfering(&trFinished) && !trFinished) { // connection has not been established - wait 5 seconds, then possibly report an error (if the connection still has not been established and ListCmdReplyCode is success) - // since we are already in the CSocketsThread::CritSect section, this call - // is also possible from the CSocket::SocketCritSect and CFTPWorker::WorkerCritSect sections (no dead-lock risk) + // since we are already in CSocketsThread::CritSect, this call + // can also be made from CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no deadlock risk) SocketsThread->DeleteTimer(UID, WORKER_DATACONSTARTTIMID); - // since we are already in the CSocketsThread::CritSect section, this call - // is also possible from the CSocket::SocketCritSect and CFTPWorker::WorkerCritSect sections (no dead-lock risk) + // since we are already in CSocketsThread::CritSect, this call + // is also possible from CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no deadlock risk) SocketsThread->AddTimer(Msg, UID, GetTickCount() + 20000, WORKER_DATACONSTARTTIMID, NULL); // ignore the error; at worst the user presses Stop } @@ -727,7 +727,7 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); // since we are already in the CSocketsThread::CritSect section, this call // is also possible from the CSocket::SocketCritSect section (no dead-lock risk) - if (WorkerDataCon->IsConnected()) // close the "data connection", the system tries to do a "graceful" + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system tries to perform a graceful shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) HANDLES(EnterCriticalSection(&WorkerCritSect)); } @@ -747,7 +747,7 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); // since we are already in the CSocketsThread::CritSect section, this call // is also possible from the CSocket::SocketCritSect section (no dead-lock risk) - if (WorkerDataCon->IsConnected()) // close the "data connection", the system tries to do a "graceful" + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system will try a graceful shutdown WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) WorkerDataCon->FreeFlushData(); DeleteSocket(WorkerDataCon); @@ -781,8 +781,8 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui { int retrReply = ListCmdReplyCode; HANDLES(LeaveCriticalSection(&WorkerCritSect)); - if (event == fweDataConStartTimeout) // if the connection still has not been established, there is no point in waiting longer + - { // if ListCmdReplyCode is success, retry the operation + if (event == fweDataConStartTimeout) // if the connection still has not been established, there is no point in waiting any longer + { // if ListCmdReplyCode indicates success, retry the operation BOOL trFinished; if (WorkerDataCon->IsConnected() && !WorkerDataCon->IsTransfering(&trFinished) && !trFinished) @@ -790,8 +790,8 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) if (FTP_DIGIT_1(retrReply) == FTP_D1_SUCCESS) // retry the operation (the server returned success, but the data connection did not even open, so something is wrong) { - // since we are already in the CSocketsThread::CritSect section, this call - // is also possible from the CSocket::SocketCritSect section (no dead-lock risk) + // since we are already in CSocketsThread::CritSect, this call + // can also be made from CSocket::SocketCritSect (no deadlock risk) WorkerDataCon->FreeFlushData(); DeleteSocket(WorkerDataCon); WorkerDataCon = NULL; @@ -814,21 +814,21 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui { nextLoopCopy = TRUE; SubState = fwssWorkCopyFinishFlushData; - // since we are already in the CSocketsThread::CritSect section, this call - // is also possible from the CSocket::SocketCritSect and CFTPWorker::WorkerCritSect sections (no dead-lock risk) + // since we are already in CSocketsThread::CritSect, this call + // is also possible from CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no deadlock risk) SocketsThread->DeleteTimer(UID, WORKER_DATACONSTARTTIMID); } break; } - case fwssWorkCopyFinishFlushData: // copy/move of a file: ensure the data flush from the data connection finishes (it is already closed) + case fwssWorkCopyFinishFlushData: // copy/move of a file: ensure data flushing from the data connection completes (it is already closed) { BOOL done = !DiskWorkIsUsed; // TRUE only if a data flush is not in progress if (done && WorkerDataCon != NULL) { HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // since we are already in the CSocketsThread::CritSect section, this call - // is also possible from the CSocket::SocketCritSect section (no dead-lock risk) + // since we are already in CSocketsThread::CritSect, this call + // can also be made from CSocket::SocketCritSect (no deadlock risk) done = WorkerDataCon->AreAllDataFlushed(FALSE); HANDLES(EnterCriticalSection(&WorkerCritSect)); } @@ -849,7 +849,7 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui } case fwssWorkCopyFinishFlushDataAfterQuitSent: - break; // copy/move of a file: after sending "QUIT" wait for the control connection to close and for the data flush to finish on disk + break; // copy/move of a file: after sending "QUIT", wait for the control connection to close and for the data flush to disk to finish case fwssWorkCopyProcessRETRRes: // copy/move of a file: process the result of "RETR" (after the "data connection" closed, data were flushed to disk, and the server response to "RETR" was received) { @@ -876,10 +876,10 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui //dataConDecomprMissingStreamEnd = WorkerDataCon->GetDecomprMissingStreamEnd(); if (!WorkerDataCon->GetProxyError(errBuf, 50 + FTP_MAX_PATH, NULL, 0, TRUE)) errBuf[0] = 0; - // since we are already in the CSocketsThread::CritSect section, this call - // is also possible from the CSocket::SocketCritSect section (no dead-lock risk) - // the data connection should be closed already, so closing it is probably redundant, but we play it safe... - if (WorkerDataCon->IsConnected()) // close the "data connection", the system tries to do a "graceful" + // since we are already in CSocketsThread::CritSect, this call + // is also possible from CSocket::SocketCritSect (no deadlock risk) + // the data connection should already be closed, so closing it is probably redundant, but keep the defensive close... + if (WorkerDataCon->IsConnected()) // close the "data connection"; the system attempts a graceful shutdown { WorkerDataCon->CloseSocketEx(NULL); // shutdown (we will not learn about the result) TRACE_E("Unexpected situation in CFTPWorker::HandleEventInWorkingState3(): data connection has left opened!"); @@ -905,8 +905,8 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui else { if (dataConError != NO_ERROR && !IsConnected()) - { // the response to RETR arrived, but while waiting for the data connection to finish - // the connection was interrupted (both the data and control connections) -> RETRY + { // the response to RETR arrived, but while waiting for the transfer over the data connection to finish + // both the data and control connections were interrupted -> RETRY conClosedRetryItem = TRUE; } else @@ -922,8 +922,8 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); if (IsConnected()) // "manually" close the control connection { - // since we are already in the CSocketsThread::CritSect section, this call - // is also possible from the CSocket::SocketCritSect section (no dead-lock risk) + // since we are already in CSocketsThread::CritSect, this call + // is also possible from CSocket::SocketCritSect (no deadlock risk) ForceClose(); // it would be cleaner to send QUIT, but a certificate change is very unlikely, so it is not worth the hassle :-) } HANDLES(EnterCriticalSection(&WorkerCritSect)); @@ -936,12 +936,12 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui (FTP_DIGIT_2(ListCmdReplyCode) == FTP_D2_CONNECTION || // mainly "426 data connection closed, transfer aborted" (whether it was the server admin or a connection issue is impossible to tell, so we prioritize a connection issue -> retry the download) FTP_DIGIT_2(ListCmdReplyCode) == FTP_D2_FILESYSTEM) && // "450 Transfer aborted. Link to file server lost." dataSSLErrorOccured != SSLCONERR_DONOTRETRY || // accept 426 and 450 only if they were not caused by an error: encryption failed, which is a permanent problem - dataConNoDataTransTimeout || // connection interrupted by us due to a no-data-transfer timeout (happens with "50%" network dropouts; the data connection stays open but the data transfer blocks, it can stay open for 14000 seconds, this should solve it) -> retry the download + dataConNoDataTransTimeout || // connection interrupted by us due to a no-data-transfer timeout (happens with "50%" network dropouts; the data connection stays open but the data transfer gets stuck, and it can stay open for 14000 seconds; this should handle it) -> retry the download dataSSLErrorOccured == SSLCONERR_CANRETRY)) // encryption failed, but it is not a permanent problem { SubState = fwssWorkCopyDelayedAutoRetry; // use a delayed auto-retry so that all unexpected server responses have time to arrive - // since we are already in the CSocketsThread::CritSect section, this call - // is also possible from the CSocket::SocketCritSect and CFTPWorker::WorkerCritSect sections (no dead-lock risk) + // since we are already in CSocketsThread::CritSect, this call + // can also be made from CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no deadlock risk) SocketsThread->AddTimer(Msg, UID, GetTickCount() + WORKER_DELAYEDAUTORETRYTIMEOUT, WORKER_DELAYEDAUTORETRYTIMID, NULL); // ignore the error; at worst the user presses Stop } @@ -960,11 +960,11 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui { errText[0] = 0; if (FTP_DIGIT_1(ListCmdReplyCode) != FTP_D1_SUCCESS && ListCmdReplyText != NULL) - { // if we do not have a network error description from the server, settle for the system description + { // if we do not have a network error description from the server, use the system description lstrcpyn(errText, ListCmdReplyText, 200 + FTP_MAX_PATH); } - if (errText[0] == 0 && errBuf[0] != 0) // try to take the error text from the proxy server + if (errText[0] == 0 && errBuf[0] != 0) // try to get the error text from the proxy server lstrcpyn(errText, errBuf, 200 + FTP_MAX_PATH); // if (errText[0] == 0 && dataConDecomprMissingStreamEnd) @@ -1146,7 +1146,7 @@ void CFTPWorker::HandleEventInWorkingState3(CFTPWorkerEvent event, BOOL& sendQui if (FTPDiskThread->CancelWork(&DiskWork, &workIsInProgress)) { if (workIsInProgress) - DiskWork.FlushDataBuffer = NULL; // the work is in progress; we cannot free the buffer with the data being written/tested and leave it to the disk-work thread (see the cancellation part) - we can write to DiskWork because after Cancel the disk thread must not access it anymore (for example it might no longer exist) + DiskWork.FlushDataBuffer = NULL; // the work is in progress; we cannot free the buffer with the data being written/tested, so we leave it to the disk-work thread (see the cancellation part) - we can write to DiskWork because after Cancel the disk thread must not access it anymore (for example, it might no longer exist) } // if we cancelled the work before it started, we must free the flush buffer, and // if the work is already finished, free the flush buffer here, because fweDiskWorkWriteFinished diff --git a/src/plugins/ftp/operats9.cpp b/src/plugins/ftp/operats9.cpp index 9995fa039..6fa50e225 100644 --- a/src/plugins/ftp/operats9.cpp +++ b/src/plugins/ftp/operats9.cpp @@ -403,7 +403,7 @@ BOOL CUploadListingsOnServer::AddOrUpdateListing(const char* path, CFTPServerPat listing->ListingState = ulsInProgressButObsolete; } } - else // error parsing the new listing or memory is low + else // error parsing the new listing, or low memory { if (listing->ListingState == ulsReady) { @@ -415,7 +415,7 @@ BOOL CUploadListingsOnServer::AddOrUpdateListing(const char* path, CFTPServerPat else { listing->ClearListingItems(); // discard the new listing - if (listing->ListingState == ulsInProgressButObsolete) // it is impossible to determine whether the transition to ulsInProgressButObsolete was preceded by an "unknown listing change", so go to the error state of the listing + if (listing->ListingState == ulsInProgressButObsolete) // it is impossible to determine whether the transition to ulsInProgressButObsolete was preceded by an "unknown listing change", so put the listing into an error state listing->ListingState = ulsInProgressButMayBeOutdated; } } @@ -521,7 +521,7 @@ BOOL CUploadListingsOnServer::FindPath(const char* path, CFTPServerPathType path #endif index = -1; int i; - for (i = 0; i < FOUND_PATH_IND_CACHE_SIZE; i++) // first try indexes that succeeded in the past + for (i = 0; i < FOUND_PATH_IND_CACHE_SIZE; i++) // first try indexes that were found in the past { int ind = FoundPathIndexes[i]; if (ind >= 0 && ind < Listing.Count && @@ -659,7 +659,7 @@ void CUploadListingsOnServer::ReportDelete(const char* workPath, CFTPServerPathT lstrcpyn(path, workPath, FTP_MAX_PATH); if (FTPPathAppend(pathType, path, FTP_MAX_PATH, name, TRUE)) { - if (FindPath(path, pathType, index)) // find the path in the cache (if it was a file, the path cannot be found) + if (FindPath(path, pathType, index)) // find the path in the cache (if this was a file, the path cannot be found) InvalidateListing(index); } } @@ -730,7 +730,7 @@ void CUploadListingsOnServer::InvalidateListing(int index) { if (listing->ListingState != ulsNotAccessible) { - if (listing->ListingState == ulsInProgressButObsolete) // discard the newer listing; it will no longer be useful + if (listing->ListingState == ulsInProgressButObsolete) // discard the newer listing; it is no longer useful listing->ClearListingItems(); if (listing->ListingState == ulsInProgress) // discard the accumulated changes; they are no longer useful listing->ClearListingChanges(); @@ -751,7 +751,7 @@ BOOL CUploadListingsOnServer::GetListing(const char* path, CFTPServerPathType pa if (FindPath(path, pathType, index)) { CUploadPathListing* listing = Listing[index]; - if (listing->ListingState == ulsNotAccessible) // the listing is "unobtainable" + if (listing->ListingState == ulsNotAccessible) // the listing is not accessible *notAccessible = TRUE; else { @@ -830,7 +830,7 @@ void CUploadListingsOnServer::ListingFailed(const char* path, CFTPServerPathType listing->ListingState == ulsInProgressButMayBeOutdated) { listing->InformWaitingWorkers(uploadFirstWaitingWorker); - if (listing->ListingState == ulsInProgressButObsolete) // we already have the listing, so we do not mind that the worker reports a listing error + if (listing->ListingState == ulsInProgressButObsolete) // we already have the listing, so a worker-reported listing error does not matter { listing->ListingState = ulsReady; if (listingOKErrorIgnored != NULL) @@ -876,11 +876,11 @@ BOOL CUploadListingsOnServer::ListingFinished(const char* path, CFTPServerPathTy listing->ListingState == ulsInProgressButMayBeOutdated) { listing->InformWaitingWorkers(NULL); - if (listing->ListingState == ulsInProgressButObsolete) // we already have a newer listing than this one, so ignore this listing (stay with the newer one) + if (listing->ListingState == ulsInProgressButObsolete) // we already have a newer listing than this one, so ignore this listing and keep the newer one listing->ListingState = ulsReady; else { - if (listing->ListingState == ulsInProgressButMayBeOutdated) // we know this listing is probably invalid (and we have no other), so remove the path from the cache (the listing will be downloaded again) + if (listing->ListingState == ulsInProgressButMayBeOutdated) // we know this listing is probably invalid (and we have no other), so remove the path from the cache; the listing will then be downloaded again { Listing.Delete(index); if (!Listing.IsGood()) @@ -903,7 +903,7 @@ BOOL CUploadListingsOnServer::ListingFinished(const char* path, CFTPServerPathTy } change = change->NextChange; } - if (change != NULL) // error while applying changes to the new listing - it can only be a lack of memory - temporary error - remove the path from the cache; the listing will be downloaded again later + if (change != NULL) // error while applying changes to the new listing; this can only be caused by low memory, so treat it as a temporary error, remove the path from the cache, and download the listing again later { Listing.Delete(index); if (!Listing.IsGood()) @@ -918,14 +918,14 @@ BOOL CUploadListingsOnServer::ListingFinished(const char* path, CFTPServerPathTy } else { - if (lowMem) // lack of memory = temporary error - remove the path from the cache; the listing will be downloaded again later + if (lowMem) // low memory = temporary error; remove the path from the cache, and the listing will be downloaded again later { Listing.Delete(index); if (!Listing.IsGood()) Listing.ResetState(); // Delete cannot fail; it only reports an error when shrinking the array ret = FALSE; } - else // parsing error of the new listing = permanent error - mark the listing for this path as "unobtainable" + else // parsing the new listing failed = permanent error - mark the listing for this path as "unobtainable" { listing->ListingState = ulsNotAccessible; listing->ClearListingChanges(); @@ -1279,7 +1279,7 @@ BOOL CUploadPathListing::ParseListing(const char* pathListing, int pathListingLe BOOL err = FALSE; CServerType* serverType = NULL; - if (listingServerType[0] != 0) // this is not autodetection; find listingServerType + if (listingServerType[0] != 0) // this is not autodetection; find the matching listingServerType { int i; for (i = 0; i < serverTypeListCount; i++) @@ -1296,11 +1296,11 @@ BOOL CUploadPathListing::ParseListing(const char* pathListing, int pathListingLe needSimpleListing = FALSE; // successfully parsed the listing if (err && lowMemory != NULL) *lowMemory = TRUE; - break; // found the requested server type, done + break; // found the requested server type, stop here } } if (i == serverTypeListCount) - listingServerType[0] = 0; // listingServerType does not exist -> perform autodetection + listingServerType[0] = 0; // listingServerType is missing -> perform autodetection } // autodetection - select the server type whose autodetection condition is satisfied @@ -1318,7 +1318,7 @@ BOOL CUploadPathListing::ParseListing(const char* pathListing, int pathListingLe { serverType->CompiledAutodetCond = CompileAutodetectCond(HandleNULLStr(serverType->AutodetectCond), NULL, NULL, NULL, NULL, 0); - if (serverType->CompiledAutodetCond == NULL) // can only be a memory shortage error + if (serverType->CompiledAutodetCond == NULL) // this can only be a low-memory error { err = TRUE; if (lowMemory != NULL) @@ -1342,7 +1342,7 @@ BOOL CUploadPathListing::ParseListing(const char* pathListing, int pathListingLe s++; lstrcpyn(listingServerType, s, SERVERTYPE_MAX_SIZE); } - needSimpleListing = err; // either successfully parsed the listing or ran into a memory shortage error, finish + needSimpleListing = err; // either the listing was parsed successfully, or an out-of-memory error occurred; stop here break; } } @@ -1356,7 +1356,7 @@ BOOL CUploadPathListing::ParseListing(const char* pathListing, int pathListingLe for (k = 0; k < serverTypeListCount; k++) { serverType = serverTypeList->At(k); - if (!serverType->ParserAlreadyTested) // only if we have not tried it yet + if (!serverType->ParserAlreadyTested) // only if we have not tested it yet { // serverType has been selected; try its parser on the listing // serverType->ParserAlreadyTested = TRUE; // unnecessary, not used later @@ -1371,7 +1371,7 @@ BOOL CUploadPathListing::ParseListing(const char* pathListing, int pathListingLe s++; lstrcpyn(listingServerType, s, SERVERTYPE_MAX_SIZE); } - needSimpleListing = err; // either successfully parsed the listing or ran into a memory shortage error, finish + needSimpleListing = err; // either successfully parsed the listing or encountered an out-of-memory error; stop here break; } } @@ -1438,7 +1438,7 @@ BOOL CUploadPathListing::ParseListingToArray(const char* pathListing, int pathLi const char* listingEnd = pathListing + pathListingLen; BOOL isDir = FALSE; - int rightsCol = dataIface->FindRightsColumn(); // index of the column with rights (used for link detection) + int rightsCol = dataIface->FindRightsColumn(); // index of the permissions column (used to detect links) parser->BeforeParsing(listing, listingEnd, pathListingDate.Year, pathListingDate.Month, pathListingDate.Day, FALSE); // initialize the parser @@ -1507,7 +1507,7 @@ void CUploadPathListing::ReportCreateDir(const char* newDir, BOOL* dirCreated, B case ulsReady: case ulsInProgressButObsolete: { - if (!FindItem(newDir, index)) // the name is free; it is possible to create the directory + if (!FindItem(newDir, index)) // the name is available; the directory can be created { if (InsertNewItem(index, ulitDirectory, newDir, UPLOADSIZE_UNKNOWN)) *dirCreated = TRUE; @@ -1596,7 +1596,7 @@ void CUploadPathListing::ReportStoreFile(const char* name, BOOL* lowMem) case ulsReady: case ulsInProgressButObsolete: { - if (!FindItem(name, index)) // the name is free; create the file + if (!FindItem(name, index)) // the name is available; create the file { if (!InsertNewItem(index, ulitFile, name, UPLOADSIZE_NEEDUPDATE)) *lowMem = TRUE; @@ -1641,7 +1641,7 @@ void CUploadPathListing::ReportFileUploaded(const char* name, const CQuadWord& f case ulsReady: case ulsInProgressButObsolete: { - if (FindItem(name, index)) // if it is a file, set its new size + if (FindItem(name, index)) // if the item exists, update its size if it is a file { CUploadListingItem* item = ListingItem[index]; if (item->ItemType == ulitFile) @@ -1694,7 +1694,7 @@ BOOL CUploadPathListing::CommitChange(CUploadListingChange* change) case ulctCreateDir: { - if (!FindItem(change->Name, index)) // the name is free; it is possible to create the directory + if (!FindItem(change->Name, index)) // the name is available; the directory can be created return InsertNewItem(index, ulitDirectory, change->Name, UPLOADSIZE_UNKNOWN); return TRUE; } @@ -1716,7 +1716,7 @@ BOOL CUploadPathListing::CommitChange(CUploadListingChange* change) case ulctFileUploaded: { - if (FindItem(change->Name, index)) // if it is a file, set its new size + if (FindItem(change->Name, index)) // if found, update its size if it is a file { CUploadListingItem* item = ListingItem[index]; if (item->ItemType == ulitFile) @@ -1760,7 +1760,7 @@ BOOL CUploadPathListing::AddWaitingWorker(int workerMsg, int workerUID) void CUploadPathListing::InformWaitingWorkers(CUploadWaitingWorker** uploadFirstWaitingWorker) { - if (uploadFirstWaitingWorker != NULL) // should add the waiting workers to the list + if (uploadFirstWaitingWorker != NULL) // add the waiting workers to the list { if (FirstWaitingWorker != NULL) { @@ -1779,7 +1779,7 @@ void CUploadPathListing::InformWaitingWorkers(CUploadWaitingWorker** uploadFirst CUploadWaitingWorker* worker = FirstWaitingWorker; while (worker != NULL) { - // because we are already in CSocketsThread::CritSect, this call is possible (no deadlock risk) + // because we are already in CSocketsThread::CritSect, this call is safe (no deadlock risk) SocketsThread->PostSocketMessage(worker->WorkerMsg, worker->WorkerUID, WORKER_TGTPATHLISTINGFINISHED, NULL); CUploadWaitingWorker* del = worker; diff --git a/src/plugins/ftp/operatsa.cpp b/src/plugins/ftp/operatsa.cpp index bc34c2681..4d6defe91 100644 --- a/src/plugins/ftp/operatsa.cpp +++ b/src/plugins/ftp/operatsa.cpp @@ -53,7 +53,7 @@ void CFTPWorker::HandleEventInWorkingState4(CFTPWorkerEvent event, BOOL& sendQui } else { - SubState = fwssWorkUploadWaitForListing; // we should wait until another worker finishes the listing + SubState = fwssWorkUploadWaitForListing; // wait until another worker finishes the listing reportWorkerChange = TRUE; // the worker displays the fwssWorkUploadWaitForListing state in the window, so it needs to be redrawn } } @@ -71,7 +71,7 @@ void CFTPWorker::HandleEventInWorkingState4(CFTPWorkerEvent event, BOOL& sendQui if (existingItem == NULL && nameValid) // no collision and the name is valid -> try to create the directory SubState = fwssWorkUploadCreateDir; else - { // if existingItem == NULL then (!nameValid==TRUE), so there is no need to test for existingItem != NULL + { // if existingItem == NULL, then !nameValid is TRUE, so there is no need to test existingItem != NULL if (!nameValid || existingItem->ItemType == ulitFile) // invalid name or a collision with a file -> "dir cannot be created" SubState = !nameValid ? fwssWorkUploadCantCreateDirInvName : fwssWorkUploadCantCreateDirFileEx; else @@ -106,7 +106,7 @@ void CFTPWorker::HandleEventInWorkingState4(CFTPWorkerEvent event, BOOL& sendQui handleShouldStop = TRUE; // check whether the worker should stop else { - if (event == fweTgtPathListingFinished) // the designated worker has finished, try to use the new listing + if (event == fweTgtPathListingFinished) // the designated worker has finished its work; try to use the new listing { SubState = fwssWorkStartWork; reportWorkerChange = TRUE; // the worker displays the fwssWorkUploadWaitForListing state in the window, so it needs to be redrawn @@ -121,7 +121,7 @@ void CFTPWorker::HandleEventInWorkingState4(CFTPWorkerEvent event, BOOL& sendQui lstrcpyn(ftpPath, curItem->TgtPath, FTP_MAX_PATH); CFTPServerPathType type = Oper->GetFTPServerPathType(ftpPath); if (FTPPathAppend(type, ftpPath, FTP_MAX_PATH, curItem->TgtName, TRUE)) - { // we have the path, send CWD to the examined directory on the server + { // we have the path; send CWD to the directory being examined on the server _snprintf_s(errText, 200 + FTP_MAX_PATH, _TRUNCATE, LoadStr(IDS_LOGMSGRESOLVINGLINK), ftpPath); Logs.LogMessage(LogUID, errText, -1, TRUE); @@ -141,7 +141,7 @@ void CFTPWorker::HandleEventInWorkingState4(CFTPWorkerEvent event, BOOL& sendQui break; } - case fwssWorkUploadResLnkWaitForCWDRes: // upload copy/move file: wait for the "CWD" result (changing into the examined link; if it succeeds, the link is a directory) + case fwssWorkUploadResLnkWaitForCWDRes: // upload copy/move file: wait for the "CWD" result (change to the tested link; if it succeeds, the link points to a directory) { switch (event) { @@ -291,7 +291,7 @@ void CFTPWorker::HandleEventInWorkingState4(CFTPWorkerEvent event, BOOL& sendQui case CANNOTCREATENAME_USERPROMPT: { Queue->UpdateItemState(CurItem, sqisUserInputNeeded, ITEMPR_UPLOADCANNOTCREATETGTDIR, NO_ERROR, - SalamanderGeneral->DupStr(errText) /* low memory = the error will be without details */, + SalamanderGeneral->DupStr(errText) /* low memory = the error will have no details */, Oper); lookForNewWork = TRUE; break; @@ -300,7 +300,7 @@ void CFTPWorker::HandleEventInWorkingState4(CFTPWorkerEvent event, BOOL& sendQui case CANNOTCREATENAME_SKIP: { Queue->UpdateItemState(CurItem, sqisSkipped, ITEMPR_UPLOADCANNOTCREATETGTDIR, NO_ERROR, - SalamanderGeneral->DupStr(errText) /* low memory = the error will be without details */, + SalamanderGeneral->DupStr(errText) /* low memory = the error will have no details */, Oper); lookForNewWork = TRUE; break; @@ -514,7 +514,7 @@ void CFTPWorker::HandleEventInWorkingState4(CFTPWorkerEvent event, BOOL& sendQui } else { - SubState = fwssWorkUploadWaitForListing; // we should wait until another worker finishes the listing + SubState = fwssWorkUploadWaitForListing; // wait until another worker finishes the listing reportWorkerChange = TRUE; // the worker displays the fwssWorkUploadWaitForListing state in the window, so it needs to be redrawn } break; @@ -638,7 +638,7 @@ void CFTPWorker::HandleEventInWorkingState4(CFTPWorkerEvent event, BOOL& sendQui lstrcpyn(ftpPath, curItem->TgtPath, FTP_MAX_PATH); CFTPServerPathType type = Oper->GetFTPServerPathType(ftpPath); if (FTPPathAppend(type, ftpPath, FTP_MAX_PATH, curItem->TgtName, TRUE)) - { // we have the path, send CWD to the examined directory on the server + { // we have the path; send CWD to the server for the directory being explored PrepareFTPCommand(buf, 200 + FTP_MAX_PATH, errBuf, 50 + FTP_MAX_PATH, ftpcmdChangeWorkingPath, &cmdLen, ftpPath); // cannot report an error sendCmd = TRUE; @@ -900,7 +900,7 @@ void CFTPWorker::HandleEventInWorkingState4(CFTPWorkerEvent event, BOOL& sendQui int count = ftpQueueItems->Count - (parentItemAdded ? 1 : 0); int childItemsNotDone = count; int i; - for (i = 0; i < count; i++) // set the parent for items created by the explore + for (i = 0; i < count; i++) // set the parent for items created by Explore { CFTPQueueItem* actItem = ftpQueueItems->At(i); actItem->ParentUID = parentUID; @@ -949,7 +949,7 @@ void CFTPWorker::HandleEventInWorkingState4(CFTPWorkerEvent event, BOOL& sendQui // notify all potentially sleeping workers that new work has appeared HANDLES(LeaveCriticalSection(&WorkerCritSect)); // since we are already in CSocketsThread::CritSect, this call is also possible - // from within CSocket::SocketCritSect (no deadlock threat) + // from CSocket::SocketCritSect (no deadlock risk) Oper->PostNewWorkAvailable(FALSE); HANDLES(EnterCriticalSection(&WorkerCritSect)); } diff --git a/src/plugins/ftp/operatsb.cpp b/src/plugins/ftp/operatsb.cpp index 062ad6527..a7e61b91f 100644 --- a/src/plugins/ftp/operatsb.cpp +++ b/src/plugins/ftp/operatsb.cpp @@ -82,12 +82,12 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui { HANDLES(LeaveCriticalSection(&WorkerCritSect)); char* flushBuffer; - // because we are already inside CSocketsThread::CritSect, this call is also possible - // from inside CSocket::SocketCritSect (no deadlock risk) + // since we are already in CSocketsThread::CritSect, this call + // is also possible from CSocket::SocketCritSect (no deadlock risk) BOOL haveBufferForData = WorkerUploadDataCon->GiveBufferForData(&flushBuffer); HANDLES(EnterCriticalSection(&WorkerCritSect)); - if (haveBufferForData) // we have 'flushBuffer'; it must be handed over to the disk thread, where it will be filled with file data (if there is an error we release it) + if (haveBufferForData) // we have 'flushBuffer'; it must be passed to the disk thread, where it will be filled with file data (if an error occurs, we release it) { if (DiskWorkIsUsed) TRACE_E("Unexpected situation in CFTPWorker::HandleEventInWorkingState5(): DiskWorkIsUsed may not be TRUE here!"); @@ -108,7 +108,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); // because we are already inside CSocketsThread::CritSect, this call is also possible // from inside CSocket::SocketCritSect (no deadlock risk) - if (WorkerUploadDataCon->IsConnected()) // close the data connection; the system will attempt a "graceful" + if (WorkerUploadDataCon->IsConnected()) // close the "data connection"; the system will attempt a "graceful" shutdown WorkerUploadDataCon->CloseSocketEx(NULL); // shutdown (we do not learn the result) WorkerUploadDataCon->FreeBufferedData(); DeleteSocket(WorkerUploadDataCon); @@ -140,8 +140,8 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); // because we are already inside CSocketsThread::CritSect, this call is also possible // from inside CSocket::SocketCritSect (no deadlock risk) - if (WorkerUploadDataCon->IsConnected()) // close the data connection; the system will attempt a "graceful" - WorkerUploadDataCon->CloseSocketEx(NULL); // shutdown (we do not learn the result) + if (WorkerUploadDataCon->IsConnected()) // close the data connection; the system will attempt a "graceful" shutdown + WorkerUploadDataCon->CloseSocketEx(NULL); // shutdown (result unavailable) WorkerUploadDataCon->FreeBufferedData(); DeleteSocket(WorkerUploadDataCon); WorkerUploadDataCon = NULL; @@ -152,7 +152,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui } else { - if (WorkerUploadDataCon != NULL) // if the data connection exists, pass the buffer into it for writing into the data connection + if (WorkerUploadDataCon != NULL) // if the data connection exists, pass it the buffer for writing { HANDLES(LeaveCriticalSection(&WorkerCritSect)); // because we are already inside CSocketsThread::CritSect, this call is also possible @@ -167,7 +167,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui } DiskWork.FlushDataBuffer = NULL; - // take over the new offset in the file (we cannot simply add it because text files convert all LF to CRLF) + // use the new file offset (we cannot just add it because text files convert all LF to CRLF) OpenedInFileCurOffset = DiskWork.WriteOrReadFromOffset; if (OpenedInFileCurOffset > OpenedInFileSize) OpenedInFileSize = OpenedInFileCurOffset; @@ -188,7 +188,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); // because we are already inside CSocketsThread::CritSect, this call is also possible // from inside CSocket::SocketCritSect (no deadlock risk) - if (WorkerUploadDataCon->IsConnected()) // close the data connection; the system will attempt a "graceful" + if (WorkerUploadDataCon->IsConnected()) // close the "data connection"; the system will attempt a "graceful" shutdown WorkerUploadDataCon->CloseSocketEx(NULL); // shutdown (we do not learn the result) WorkerUploadDataCon->FreeBufferedData(); DeleteSocket(WorkerUploadDataCon); @@ -229,7 +229,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui ¬Accessible, &getListing, curItem->TgtName, &existingItem, NULL)) { - if (listingInProgress) // listing is currently taking place or is about to happen + if (listingInProgress) // the listing is currently in progress or is about to start { if (getListing) // we are to obtain the listing and then notify any other waiting workers { @@ -238,7 +238,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui } else { - SubState = fwssWorkUploadWaitForListing; // we should wait until another worker finishes listing + SubState = fwssWorkUploadWaitForListing; // wait until another worker finishes the listing reportWorkerChange = TRUE; // the worker prints the fwssWorkUploadWaitForListing state to the window, so a redraw is needed } } @@ -252,7 +252,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui else // the listing is available; check for a possible file name collision { nextLoop = TRUE; - if (CurItem->ForceAction == fqiaUploadContinueAutorename) // continuing auto-rename (try another name + another STOR) + if (CurItem->ForceAction == fqiaUploadContinueAutorename) // continue auto-rename (try another name + another STOR) { UploadType = utAutorename; if (curItem->RenamedName != NULL) @@ -267,17 +267,17 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui else { BOOL nameValid = FTPMayBeValidNameComponent(curItem->TgtName, curItem->TgtPath, FALSE, pathType); - if (existingItem == NULL && nameValid) // no collision and a valid name -> attempt to create the directory + if (existingItem == NULL && nameValid) // no collision and a valid name -> attempt to create the file SubState = fwssWorkUploadNewFile; else - { // if existingItem == NULL, then (!nameValid==TRUE), so tests for existingItem != NULL are unnecessary + { // if existingItem == NULL, then !nameValid is TRUE, so checks for existingItem != NULL are unnecessary if (!nameValid || existingItem->ItemType == ulitDirectory) // invalid name or collision with a directory -> "file cannot be created" SubState = !nameValid ? fwssWorkUploadCantCreateFileInvName : fwssWorkUploadCantCreateFileDirEx; else { if (existingItem->ItemType == ulitFile) // collision with a file -> "file already exists" SubState = fwssWorkUploadFileExists; - else // (existingItem->ItemType == ulitLink): collision with a link -> determine what the link is (file/directory) + else // (existingItem->ItemType == ulitLink): collision with a link -> determine whether the link is a file or directory SubState = fwssWorkUploadResolveLink; } } @@ -307,7 +307,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui handleShouldStop = TRUE; // check whether the worker should stop else { - if (event == fweTgtPathListingFinished) // the designated worker has already finished, so try to use the new listing + if (event == fweTgtPathListingFinished) // the designated worker has finished its work, so try to use the new listing { SubState = fwssWorkStartWork; reportWorkerChange = TRUE; // the worker prints the fwssWorkUploadWaitForListing state to the window, so a redraw is needed @@ -333,7 +333,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui HaveWorkingPath = FALSE; // changing the current working path on the server } - else // path syntax error or the path would become too long + else // path syntax error or the resulting path would be too long { // error on the item; record this state into it Queue->UpdateItemState(CurItem, sqisFailed, ITEMPR_INVALIDPATHTOLINK, NO_ERROR, NULL, Oper); @@ -342,7 +342,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui break; } - case fwssWorkUploadResLnkWaitForCWDRes: // upload copy/move file: waiting for the result of "CWD" (changing into the examined link - if it succeeds, the link points to a directory) + case fwssWorkUploadResLnkWaitForCWDRes: // upload copy/move file: waiting for the result of "CWD" (changing to the link being examined - if it succeeds, the link points to a directory) { switch (event) { @@ -386,7 +386,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui case fwssWorkUploadCantCreateFileInvName: // upload copy/move file: handling the "target file cannot be created" error (invalid name) case fwssWorkUploadCantCreateFileDirEx: // upload copy/move file: handling the "target file cannot be created" error (name already used for a directory or a link to a directory) { - if (CurItem->ForceAction == fqiaUseAutorename) // forced auto-rename + if (CurItem->ForceAction == fqiaUseAutorename) // forced autorename { SubState = fwssWorkUploadAutorenameFile; nextLoop = TRUE; @@ -693,8 +693,8 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui { if (FTP_DIGIT_1(replyCode) == FTP_D1_SUCCESS) // the target path is set; start generating target directory names { // we have successfully changed the working path; since this path was once returned - // by the server in response to PWD, we assume PWD would return it again now, and therefore - // we will not send it (an optimization hopefully with very low risk) + // returned by the server in response to PWD; we assume PWD would return this path again now, and therefore + // we will not send it (an optimization with hopefully very low risk) HaveWorkingPath = TRUE; lstrcpyn(WorkingPath, curItem->TgtPath, FTP_MAX_PATH); @@ -774,10 +774,10 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui handleShouldStop = TRUE; // check whether the worker should stop else { - if (FTP_DIGIT_1(replyCode) == FTP_D1_SUCCESS) // success is returned (should be 200) + if (FTP_DIGIT_1(replyCode) == FTP_D1_SUCCESS) // a success reply was received (should be 200) CurrentTransferMode = (curItem->AsciiTransferMode ? ctrmASCII : ctrmBinary); // the transfer mode was changed else - CurrentTransferMode = ctrmUnknown; // unknown error; it may not matter, but we will not cache the transfer mode + CurrentTransferMode = ctrmUnknown; // unknown error; it may not matter, but we will not cache the data transfer mode nextLoop = TRUE; switch (UploadType) @@ -833,7 +833,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui // case fweCmdInfoReceived: // "1xx" replies are ignored (they are only written into the log) case fweCmdReplyReceived: { - if (FTP_DIGIT_1(replyCode) == FTP_D1_SUCCESS) // success is returned (should be 213) + if (FTP_DIGIT_1(replyCode) == FTP_D1_SUCCESS) // success response returned (should be 213) { if (ShouldStop) handleShouldStop = TRUE; // check whether the worker should stop @@ -901,7 +901,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui else { int resumeMinFileSize = Config.GetResumeMinFileSize(); - if ((unsigned __int64)resumeMinFileSize <= size) // resume makes sense (the portion of the file is larger than the minimum for resume) + if ((unsigned __int64)resumeMinFileSize <= size) // resume makes sense (the partial file is larger than the minimum size for resume) { ResumingFileOnServer = TRUE; OpenedInFileCurOffset.SetUI64(size); @@ -953,7 +953,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui case fwssWorkUploadGetFileSizeFromListing: // file upload: resume - the SIZE command failed (or is not implemented), determine the file size from the listing { - if (existingItem == NULL) // if it did not arrive here directly, retrieve target file information from the listing again + if (existingItem == NULL) // if it was not obtained directly, retrieve the target file information from the listing again { Oper->GetUserHostPort(userBuf, hostBuf, &portBuf); CFTPServerPathType pathType = Oper->GetFTPServerPathType(curItem->TgtPath); @@ -963,7 +963,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui ¬Accessible, &getListing, curItem->TgtName, &existingItem, NULL)) { - if (listingInProgress) // listing is currently taking place or is about to happen + if (listingInProgress) // the listing is currently in progress or is about to start { if (getListing) // we are to obtain the listing and then notify any other waiting workers { @@ -973,7 +973,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui } else { - SubState = fwssWorkUploadWaitForListing; // we should wait until another worker finishes listing + SubState = fwssWorkUploadWaitForListing; // wait until another worker finishes the listing reportWorkerChange = TRUE; // the worker prints the fwssWorkUploadWaitForListing state to the window, so a redraw is needed } break; @@ -1157,7 +1157,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui } else { - Queue->UpdateItemState(CurItem, sqisWaiting, ITEMPR_OK, NO_ERROR, NULL, Oper); // at least this worker will go look for new work, so some worker will surely handle this item (no need to post "new work available") + Queue->UpdateItemState(CurItem, sqisWaiting, ITEMPR_OK, NO_ERROR, NULL, Oper); // at least this worker will look for new work, so some worker will handle this item (no need to post "new work available") lookForNewWork = TRUE; } break; @@ -1170,18 +1170,18 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui BOOL notAccessible, getListing, listingInProgress, nameExists; int index = 0; UploadAutorenamePhase = curItem->AutorenamePhase; - int usedUploadAutorenamePhase = UploadAutorenamePhase; // in case of a name collision - the phase in which we should try to generate another name + int usedUploadAutorenamePhase = UploadAutorenamePhase; // in case of a name collision - the phase in which we should try generating another name while (1) { FTPGenerateNewName(&UploadAutorenamePhase, UploadAutorenameNewName, &index, curItem->TgtName, pathType, FALSE, strcmp(curItem->TgtName, curItem->Name) != 0); - // we have a new name; verify whether it collides with a name from the target path listing + // we have a new name; verify that it does not collide with any name in the target path listing if (UploadListingCache.GetListing(userBuf, hostBuf, portBuf, curItem->TgtPath, pathType, Msg, UID, &listingInProgress, ¬Accessible, &getListing, UploadAutorenameNewName, NULL, &nameExists)) { - if (listingInProgress) // listing is currently taking place or is about to happen + if (listingInProgress) // the listing is currently in progress or is about to start { if (getListing) // we are to obtain the listing and then notify any other waiting workers { @@ -1191,20 +1191,20 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui } else { - SubState = fwssWorkUploadWaitForListing; // we should wait until another worker finishes listing + SubState = fwssWorkUploadWaitForListing; // wait until another worker finishes the listing reportWorkerChange = TRUE; // the worker prints the fwssWorkUploadWaitForListing state to the window, so a redraw is needed } break; } else // the listing is already cached or marked as "unobtainable" { - if (notAccessible) // the listing is cached, but only as "unobtainable" (very unlikely; the listing was "ready" a moment ago) + if (notAccessible) // the listing is cached, but only as "unobtainable" (very unlikely; it was "ready" a moment ago) { Queue->UpdateItemState(CurItem, sqisFailed, ITEMPR_UPLOADCANNOTLISTTGTPATH, 0, NULL, Oper); lookForNewWork = TRUE; break; } - else // the listing is available; check for a potential file name collision + else // the listing is available; check for a possible file name collision { if (LockedFileUID != 0) TRACE_E("Unexpected situation in CFTPWorker::HandleEventInWorkingState5(): LockedFileUID != 0!"); @@ -1251,11 +1251,11 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui if (FTPOpenedFiles.OpenFile(userBuf, hostBuf, portBuf, curItem->TgtPath, Oper->GetFTPServerPathType(curItem->TgtPath), curItem->TgtName, &LockedFileUID, ffatWrite)) - { // the file on the server is not open yet; we can work with it + { // the file on the server is not open yet; we can still work with it SubState = fwssWorkUploadDelForOverwrite; nextLoop = TRUE; } - else // another operation is already in progress on this file; let the user try again later + else // another operation is already in progress on this file; the user should try again later { // error on the item; record this state into it Queue->UpdateItemState(CurItem, sqisFailed, ITEMPR_TGTFILEINUSE, NO_ERROR, NULL, Oper); @@ -1264,7 +1264,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui break; } - case fwssWorkUploadDelForOverwrite: // file upload: if overwrite should delete first, perform it here + case fwssWorkUploadDelForOverwrite: // file upload: if this is an overwrite and delete should be done first, perform the delete here { if (UseDeleteForOverwrite && UploadType == utOverwriteFile) { // the file is already locked for writing; deletion is just an intermediate step, no need to call FTPOpenedFiles.OpenFile() @@ -1424,8 +1424,8 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui int logUID = LogUID; HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // because we are already inside CSocketsThread::CritSect, these calls are also possible - // from inside CSocket::SocketCritSect (no deadlock risk) + // since we are already in CSocketsThread::CritSect, these calls + // are also possible from CSocket::SocketCritSect (no deadlock risk) if (WorkerUploadDataCon != NULL) { WorkerUploadDataCon->SetPassive(ip, port, logUID); @@ -1497,8 +1497,8 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); - // because we are already inside CSocketsThread::CritSect, these calls are also possible - // from inside CSocket::SocketCritSect (no deadlock risk) + // since we are already in CSocketsThread::CritSect, these calls + // are also possible from CSocket::SocketCritSect (no deadlock risk) GetLocalIP(&localIP, NULL); // should not even be able to return an error BOOL retOpenForListening = FALSE; BOOL listenError = TRUE; @@ -1526,12 +1526,12 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui int serverTimeout = Config.GetServerRepliesTimeout() * 1000; if (serverTimeout < 1000) serverTimeout = 1000; // at least one second - // because we are already in CSocketsThread::CritSect, this call is also - // possible from CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no deadlock risk) + // because we are already in CSocketsThread::CritSect, this call can also be made + // from CSocket::SocketCritSect and CFTPWorker::WorkerCritSect (no deadlock risk) SocketsThread->AddTimer(Msg, UID, GetTickCount() + serverTimeout, WORKER_LISTENTIMEOUTTIMID, NULL); // ignore the error; at worst the user will press Stop } - else // failed to open the "listen" socket to accept the data connection from + else // failed to open the "listen" socket to accept the data connection from the server { // the server (local operation, most likely never happens) or cannot open the connection to the proxy server if (WorkerUploadDataCon != NULL) { @@ -1550,7 +1550,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui Queue->UpdateItemState(CurItem, sqisFailed, ITEMPR_LISTENFAILURE, error, NULL, Oper); lookForNewWork = TRUE; } - else // unable to open the connection to the proxy server, perform a retry... + else // unable to open the connection to the proxy server, retry... { if (error != NO_ERROR) { @@ -1583,7 +1583,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui break; } - case fwssWorkUploadWaitForListen: // upload copy/move file: waiting for the "listen" port to open (opening the active data connection) - local or on the proxy server + case fwssWorkUploadWaitForListen: // upload file copy/move: waiting for the "listen" port to open (opening the active data connection), locally or on the proxy server { if (ShouldStop) { @@ -1596,7 +1596,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); // because we are already in CSocketsThread::CritSect, this call is also // possible from CSocket::SocketCritSect (no deadlock risk) - if (WorkerUploadDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + if (WorkerUploadDataCon->IsConnected()) // close the "data connection"; the system will attempt a graceful shutdown WorkerUploadDataCon->CloseSocketEx(NULL); // shutdown (we will not learn the result) DeleteSocket(WorkerUploadDataCon); WorkerUploadDataCon = NULL; @@ -1638,7 +1638,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui sendCmd = TRUE; SubState = fwssWorkUploadWaitForPORTRes; } - else // error when opening the "listen" port on the proxy server - perform a retry... + else // error opening the "listen" port on the proxy server - retry... { // close the data connection if (WorkerUploadDataCon != NULL) @@ -1646,7 +1646,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); // because we are already in CSocketsThread::CritSect, this call is also // possible from CSocket::SocketCritSect (no deadlock risk) - if (WorkerUploadDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + if (WorkerUploadDataCon->IsConnected()) // close the "data connection"; the system will attempt a graceful shutdown WorkerUploadDataCon->CloseSocketEx(NULL); // shutdown (we will not learn the result) DeleteSocket(WorkerUploadDataCon); WorkerUploadDataCon = NULL; @@ -1678,7 +1678,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui errBuf[0] = 0; // because we are already in CSocketsThread::CritSect, this call is also // possible from CSocket::SocketCritSect (no deadlock risk) - if (WorkerUploadDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + if (WorkerUploadDataCon->IsConnected()) // close the "data connection"; the system will attempt a graceful shutdown WorkerUploadDataCon->CloseSocketEx(NULL); // shutdown (we will not learn the result) DeleteSocket(WorkerUploadDataCon); WorkerUploadDataCon = NULL; @@ -1734,7 +1734,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); // because we are already in CSocketsThread::CritSect, this call is also // possible from CSocket::SocketCritSect (no deadlock risk) - if (WorkerUploadDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + if (WorkerUploadDataCon->IsConnected()) // close the "data connection"; the system will attempt a graceful shutdown WorkerUploadDataCon->CloseSocketEx(NULL); // shutdown (we will not learn the result) DeleteSocket(WorkerUploadDataCon); WorkerUploadDataCon = NULL; @@ -1760,7 +1760,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); // because we are already in CSocketsThread::CritSect, this call is also // possible from CSocket::SocketCritSect (no deadlock risk) - if (WorkerUploadDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + if (WorkerUploadDataCon->IsConnected()) // close the "data connection"; the system will attempt a "graceful" shutdown WorkerUploadDataCon->CloseSocketEx(NULL); // shutdown (we will not learn the result) DeleteSocket(WorkerUploadDataCon); WorkerUploadDataCon = NULL; @@ -1810,7 +1810,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui break; } - case fwssWorkUploadActivateDataCon: // upload copy/move file: activate the data connection (right after sending the STOR command) + case fwssWorkUploadActivateDataCon: // file upload during copy/move: activate the data connection (right after sending the STOR command) { if (!Oper->GetEncryptDataConnection() && (WorkerUploadDataCon != NULL)) { // FIXME: 2009.01.29: I believe ActivateConnection can be called later @@ -1827,7 +1827,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui break; } - case fwssWorkUploadWaitForSTORRes: // upload copy/move file: waiting for the "STOR/APPE" result (waiting for the upload to finish) + case fwssWorkUploadWaitForSTORRes: // upload copy/move of a file: waiting for the "STOR/APPE" result (waiting for the file upload to finish) { switch (event) { @@ -1885,7 +1885,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui errBuf[0] = 0; // because we are already in CSocketsThread::CritSect, this call is also // possible from CSocket::SocketCritSect (no deadlock risk) - if (WorkerUploadDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + if (WorkerUploadDataCon->IsConnected()) // close the "data connection"; the system will attempt a graceful shutdown WorkerUploadDataCon->CloseSocketEx(NULL); // shutdown (we will not learn the result) WorkerUploadDataCon->FreeBufferedData(); DeleteSocket(WorkerUploadDataCon); @@ -1898,8 +1898,8 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui BOOL canUseRenamedName = TRUE; BOOL canClearForceAction = TRUE; if (!ShouldStop && PrepareDataError == pderASCIIForBinaryFile) - { // when a binary file is detected in ASCII mode, ensure the target file is deleted - // the file is already locked for writing, deletion is only an intermediate step, no need to call FTPOpenedFiles.OpenFile() + { // when a binary file is detected in ASCII mode, delete the target file + // the file is already locked for writing; deletion is only an intermediate step, so FTPOpenedFiles.OpenFile() need not be called PrepareFTPCommand(buf, 200 + FTP_MAX_PATH, errBuf, 50 + FTP_MAX_PATH, ftpcmdDeleteFile, &cmdLen, UploadType == utAutorename ? curItem->RenamedName : curItem->TgtName); // cannot report an error @@ -1923,7 +1923,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui // close the source file on disk CloseOpenedInFile(); - // mark the file as already transferred (in case deleting the source file fails during Move we need to distinguish this situation) + // mark the file as already transferred (for a Move, we must distinguish this case if deleting the source file fails) Queue->UpdateTgtFileState(curItem, UPLOADTGTFILESTATE_TRANSFERRED); if (uploadRealSize != UPLOADSIZE_UNKNOWN && curItem->Size != uploadRealSize) @@ -1942,7 +1942,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui FTP_DIGIT_1(replyCode) == FTP_D1_ERROR)) { HANDLES(LeaveCriticalSection(&WorkerCritSect)); - if (IsConnected()) // "manually" close the control connection + if (IsConnected()) // close the control connection manually { // because we are already in CSocketsThread::CritSect, this call is also // possible from CSocket::SocketCritSect (no deadlock risk) @@ -1955,10 +1955,10 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui { if ((!ResumingFileOnServer || Oper->GetDataConWasOpenedForAppendCmd()) && // proftpd (Linux) repeatedly returns 45x (append disabled, enabled somewhere in the config), warftpd repeatedly returns 42x (some write error) -- in any case we cannot keep trying APPE endlessly (however if APPE opened the data connection, perform auto-retry because APPE works 99.9% of the time) FTP_DIGIT_1(replyCode) == FTP_D1_TRANSIENTERROR && - (FTP_DIGIT_2(replyCode) == FTP_D2_CONNECTION || // mainly "426 data connection closed, transfer aborted" (I cannot tell whether it was caused by the server admin or a connection failure, so priority goes to assuming a connection issue -> retry the upload) + (FTP_DIGIT_2(replyCode) == FTP_D2_CONNECTION || // mainly "426 data connection closed, transfer aborted" (it is not possible to tell whether this was caused by the server admin or by a connection failure, so it is treated as a connection problem first -> retry the upload) FTP_DIGIT_2(replyCode) == FTP_D2_FILESYSTEM) && // "450 Transfer aborted. Link to file server lost." dataSSLErrorOccured != SSLCONERR_DONOTRETRY || // take 426 and 450 only if they were not caused by: failed to encrypt the connection, which is a permanent problem - dataConNoDataTransTimeout || // connection interrupted by us due to the no-data-transfer timeout (happens during "50%" network outages, the data connection stays up but data transfer stalls, can remain open for 14000 seconds, this should address it) -> retry the upload attempt + dataConNoDataTransTimeout || // connection interrupted by us due to the no-data-transfer timeout (this happens during "50%" network outages: the data connection stays up, but data transfer stalls and can remain open for 14000 seconds; this should handle that) -> retry the upload attempt dataSSLErrorOccured == SSLCONERR_CANRETRY) // failed to encrypt the connection, but it is not a permanent problem { SubState = fwssWorkCopyDelayedAutoRetry; // use delayed auto-retry so all unexpected replies from the server can arrive @@ -1993,7 +1993,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui canUseRenamedName = FALSE; // keep TgtName as the original (forget RenamedName; another name will be generated by the next FTPGenerateNewName phase) Queue->UpdateItemState(CurItem, sqisWaiting, ITEMPR_OK, NO_ERROR, NULL, Oper); // at least this worker will look for new work, so some worker will take care of this item (no need to post "new work available") } - else // we no longer know what other name could be created, so report an error + else // we no longer know what other name can be generated, so report an error { CopyStr(errText, 200 + FTP_MAX_PATH, reply, replySize); Queue->UpdateItemState(CurItem, sqisFailed, ITEMPR_UPLOADFILEAUTORENFAILED, NO_ERROR, @@ -2063,7 +2063,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui } else { - if (ResumingFileOnServer && UploadType == utResumeOrOverwriteFile && // resume failed, try overwrite instead + if (ResumingFileOnServer && UploadType == utResumeOrOverwriteFile && // resume failed, try overwriting instead dataSSLErrorOccured == SSLCONERR_NOERROR) { Logs.LogMessage(LogUID, LoadStr(IDS_LOGMSGUPLRESUMEERR), -1, TRUE); @@ -2080,11 +2080,11 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui { errText[0] = 0; if (FTP_DIGIT_1(replyCode) != FTP_D1_SUCCESS) - { // if we have no description of the network error from the server, fall back to the system description + { // if we do not have a network error description from the server, use the system description CopyStr(errText, 200 + FTP_MAX_PATH, reply, replySize); } - if (errText[0] == 0 && errBuf[0] != 0) // try to use the error text from the proxy server + if (errText[0] == 0 && errBuf[0] != 0) // try to get the error text from the proxy server lstrcpyn(errText, errBuf, 200 + FTP_MAX_PATH); } @@ -2108,9 +2108,9 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui if (CurItem->ForceAction != fqiaNone && canClearForceAction) // the forced action no longer applies Queue->UpdateForceAction(CurItem, fqiaNone); - // autorename: record the new name in the item - even if STOR failed, it is still more accurate that the file - // was stored under the new name than under the original one - for example when overwriting an existing file this is obvious - // NOTE: no need to call Oper->ReportItemChange(CurItem->UID), because RenamedName is used + // autorename: record the new name in the item - even if STOR returns an error, it is still more accurate that the file + // was stored under the new name than under the original one - for example, when overwriting an existing file + // NOTE: there is no need to call Oper->ReportItemChange(CurItem->UID), because RenamedName is used // before TgtName (so the new name has already been displayed) if (uploadTypeIsAutorename && canUseRenamedName) Queue->ChangeTgtNameToRenamedName(curItem); @@ -2120,15 +2120,15 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui case fweCmdConClosed: // the connection closed/timed out (see ErrorDescr for details) -> try to restore it { if (UploadType == utAutorename) - Queue->ChangeTgtNameToRenamedName(curItem); // even if STOR failed, it is still more accurate that the file was stored under the new name than the original one - for example when overwriting an existing file this is obvious + Queue->ChangeTgtNameToRenamedName(curItem); // even if STOR failed, it is still more accurate to say that the file was stored under the new name than under the original name; for example, when overwriting an existing file, this is obvious // the result of the STOR command is unknown, invalidate the listing Oper->GetUserHostPort(userBuf, hostBuf, &portBuf); UploadListingCache.ReportFileUploaded(userBuf, hostBuf, portBuf, curItem->TgtPath, Oper->GetFTPServerPathType(curItem->TgtPath), curItem->TgtName, UPLOADSIZE_UNKNOWN, TRUE); - // except for the case when STOR reports the "cannot create target file name" error (which is when STOR reports - // some error + nothing was uploaded) we consider sending the STOR/APPE command to complete + // except when STOR reports the "cannot create target file name" error (that is, when STOR reports + // an error and nothing was uploaded), we consider sending the STOR/APPE command to complete // the forced actions: "overwrite", "resume", and "resume or overwrite" if (CurItem->ForceAction != fqiaNone) // the forced action no longer applies Queue->UpdateForceAction(CurItem, fqiaNone); @@ -2138,7 +2138,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui HANDLES(LeaveCriticalSection(&WorkerCritSect)); // because we are already in CSocketsThread::CritSect, this call is also // possible from CSocket::SocketCritSect (no deadlock risk) - if (WorkerUploadDataCon->IsConnected()) // close the "data connection", the system will attempt a "graceful" + if (WorkerUploadDataCon->IsConnected()) // close the "data connection"; the system will attempt a graceful shutdown WorkerUploadDataCon->CloseSocketEx(NULL); // shutdown (we will not learn the result) WorkerUploadDataCon->FreeBufferedData(); DeleteSocket(WorkerUploadDataCon); @@ -2227,7 +2227,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui lookForNewWork = TRUE; } } - else // Copy - nothing more to handle, done + else // Copy - nothing else to do, done { SubState = fwssWorkUploadCopyDone; nextLoop = TRUE; @@ -2271,7 +2271,7 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui break; } - case fwssWorkUploadCopyDone: // upload copy/move file: finished, move on to the next item + case fwssWorkUploadCopyDone: // upload copy/move: finished, move on to the next item { // the item was completed successfully, store this state in it Queue->UpdateItemState(CurItem, sqisDone, ITEMPR_OK, NO_ERROR, NULL, Oper); @@ -2297,11 +2297,11 @@ void CFTPWorker::HandleEventInWorkingState5(CFTPWorkerEvent event, BOOL& sendQui if (FTPDiskThread->CancelWork(&DiskWork, &workIsInProgress)) { if (workIsInProgress) - DiskWork.FlushDataBuffer = NULL; // work is in progress; we cannot free the buffer with read data, leave it to the disk-work thread (see the cancellation section) - we can write to DiskWork because after Cancel the disk thread must no longer access it (it might not even exist) + DiskWork.FlushDataBuffer = NULL; // work is in progress; we cannot free the buffer containing the read data, so leave it to the disk-work thread (see the cancellation section) - we can write to DiskWork because after Cancel the disk thread must no longer access it (it might not even exist) } // if we cancelled the work before it started, we must release the flush buffer, and - // if the work has already finished, release the flush buffer here because fweDiskWorkReadFinished - // it will be delivered elsewhere (where it will be ignored) + // if the work has already finished, release the flush buffer here because fweDiskWorkReadFinished + // will arrive elsewhere (where it will be ignored) if (DiskWork.FlushDataBuffer != NULL) { free(DiskWork.FlushDataBuffer); diff --git a/src/plugins/ftp/parser.h b/src/plugins/ftp/parser.h index 020e99a87..9cd2747b4 100644 --- a/src/plugins/ftp/parser.h +++ b/src/plugins/ftp/parser.h @@ -4,9 +4,9 @@ #pragma once -// skips the identifier name (function, state variable, or column name), +// skips an identifier (function, state variable, or column name), // returns TRUE if at least one character was skipped (the identifier has at least one -// character); otherwise returns the 'emptyErrID' error in 'errorResID' +// character); otherwise stores the 'emptyErrID' error in 'errorResID' BOOL SkipIdentifier(const char*& s, const char* end, int* errorResID, int emptyErrID); // @@ -43,7 +43,7 @@ enum CFTPParserBinaryOperators enum CFTPParserParameterType { pptNone, // uninitialized - pptColumnID, // column identifier (-3==is_link, -2==is_hidden, -1==is_dir, from 0 it is an index in the 'columns' array) + pptColumnID, // column identifier (-3==is_link, -2==is_hidden, -1==is_dir, from 0 onward it is an index in the 'columns' array) pptBoolean, // boolean (true==1, false==0) pptString, // string pptNumber, // signed int64 (unsigned int64 is unnecessary) @@ -242,7 +242,7 @@ class CFTPParserFunction protected: CFTPParserFunctionCode Function; - TIndirectArray Parameters; // list of all rule functions + TIndirectArray Parameters; // list of all function parameters public: CFTPParserFunction(CFTPParserFunctionCode func) : Parameters(1, 1) { Function = func; } @@ -323,8 +323,8 @@ class CFTPParserRule BOOL IsGood() { return Functions.IsGood(); } // returns TRUE if the function in the rule was compiled successfully (up to the ')' symbol); - // on error returns FALSE and sets 'errorResID' (number of the string describing - // the error - stored in resources) or 'lowMem' (TRUE = low memory) + // on failure returns FALSE and sets 'errorResID' (resource ID of the string describing + // the error) or 'lowMem' (TRUE = low memory) BOOL CompileNewFunction(CFTPParserFunctionCode func, const char*& rules, const char* rulesEnd, TIndirectArray* columns, int* errorResID, BOOL* lowMem, BOOL* colAssigned); @@ -352,12 +352,12 @@ class CFTPParserRule // // bits for the date column index in 'emptyCol' (see CFTPParser::GetNextItemFromListing) -#define DATE_MASK_DAY 0x02 // the date has the day set (starting at 0x02 because TRUE = 0x01) +#define DATE_MASK_DAY 0x02 // day is set in the date (starting at 0x02 because TRUE = 0x01) #define DATE_MASK_MONTH 0x04 // the date has the month set #define DATE_MASK_YEAR 0x08 // the date has the year set #define DATE_MASK_DATE 0x0E // the date is set completely #define DATE_MASK_YEARCORRECTIONNEEDED 0x10 // the year in the date still needs to be corrected (used with "year_or_time") -#define DATE_MASK_TIME 0x100 // the time is set completely (it is a different column, it could be 0x02, but we use 0x10 for easier error detection) +#define DATE_MASK_TIME 0x100 // the time is fully set (it is a different column, 0x02 could be used, but 0x10 is used for easier error detection) // constants for CFTPParser::AllowedLanguagesMask #define PARSER_LANG_ALL 0xFFFF @@ -381,7 +381,7 @@ class CFTPParser const char* LastNonEmptyEnd; // end of the last non-empty line const char* ListingBeg; // beginning of the listing BOOL ListingIncomplete; // TRUE if the listing is incomplete - BOOL SkipThisLineItIsIncomlete; // TRUE only if the rule processing detected that the listing is incomplete - skip the trailing part of the listing processed by this rule + BOOL SkipThisLineItIsIncomlete; // TRUE only if rule processing detected that the listing is incomplete - the trailing part of the listing processed by this rule is skipped DWORD AllowedLanguagesMask; // allowed languages for functions month_3 and month_txt (bit combination of PARSER_LANG_XXX constants) - purpose: to avoid mixing languages when detecting months public: @@ -492,20 +492,20 @@ class CFTPAutodetCondNode }; // allocates the parser and creates its structure according to the 'rules' string (parsing rules); -// 'columns' are defined columns; on error returns NULL; returns TRUE in 'lowMem' (if not NULL) -// if the error was caused by lack of memory; returns the offset of a syntactic or semantic error -// inside 'rules' in 'errorPos' (if not NULL) (-1=unknown error position), and at the same time -// returns the number of the string describing the error in 'errorResID' (if not NULL) +// 'columns' are the defined columns; on error returns NULL; returns TRUE in 'lowMem' (if not NULL) +// if the error was caused by lack of memory; returns the offset of a syntax or semantic error +// in 'rules' in 'errorPos' (if not NULL) (-1=unknown error position), and also returns +// the ID of the string describing the error in 'errorResID' (if not NULL) // (stored in resources; -1=no error description) CFTPParser* CompileParsingRules(const char* rules, TIndirectArray* columns, int* errorPos, int* errorResID, BOOL* lowMem); // loads the autodetection condition from the 'cond' string and stores it in an allocated tree, // whose root it returns; on error returns NULL; returns TRUE in 'lowMem' (if not NULL) if the error -// was caused by lack of memory; returns the offset of a syntactic error inside 'cond' (-1=unknown error position) -// in 'errorPos' (if not NULL); simultaneously returns the number of the string describing the error in 'errorResID' -// (if not NULL) (stored in resources; -1=no error description) and returns a textual error description in the -// 'errBuf'+'errBufSize' buffer (has higher priority than 'errorResID') +// was caused by lack of memory; returns the offset of a syntax error inside 'cond' (-1=unknown error position) +// in 'errorPos' (if not NULL); also returns the ID of the string describing the error in 'errorResID' +// (if not NULL) (stored in resources; -1=no error description) and returns a textual error description in +// the buffer specified by 'errBuf' and 'errBufSize' (has higher priority than 'errorResID') CFTPAutodetCondNode* CompileAutodetectCond(const char* cond, int* errorPos, int* errorResID, BOOL* lowMem, char* errBuf, int errBufSize); diff --git a/src/plugins/ftp/parser1.cpp b/src/plugins/ftp/parser1.cpp index de72d63d6..ee199f0d0 100644 --- a/src/plugins/ftp/parser1.cpp +++ b/src/plugins/ftp/parser1.cpp @@ -205,7 +205,7 @@ BOOL CFTPParser::CompileNewRule(const char*& rules, const char* rulesEnd, int* errorResID, BOOL* lowMem, BOOL* colAssigned) { CALL_STACK_MESSAGE1("CFTPParser::CompileNewRule()"); - rules++; // we know '*' arrived, skip it + rules++; // we know there is a '*', skip it CFTPParserRule* ruleObj = new CFTPParserRule; if (ruleObj == NULL) { @@ -242,7 +242,7 @@ BOOL CFTPParser::CompileNewRule(const char*& rules, const char* rulesEnd, return FALSE; } rules++; - return TRUE; // with this, the rule is compiled + return TRUE; // the rule is compiled at this point } else // a function has to start here { @@ -409,7 +409,7 @@ BOOL CFTPParserRule::CompileNewFunction(CFTPParserFunctionCode func, const char* int* errorResID, BOOL* lowMem, BOOL* colAssigned) { DEBUG_SLOW_CALL_STACK_MESSAGE2("CFTPParserRule::CompileNewFunction(%d)", (int)func); - rules++; // we know '(' arrived, skip it + rules++; // we know there is a '(', skip it CFTPParserFunction* funcObj = new CFTPParserFunction(func); if (funcObj == NULL) { @@ -457,7 +457,7 @@ BOOL CFTPParserRule::CompileNewFunction(CFTPParserFunctionCode func, const char* // also check the types and counts of parameters used by the compiled function if (!funcObj->CheckParameters(columns, errorResID, colAssigned)) return FALSE; - return TRUE; // with this, the function is compiled + return TRUE; // the function is compiled at this point } else // a parameter has to start here { @@ -1500,7 +1500,7 @@ CFTPParserParameter::GetFuncParType(TIndirectArray* columns) } else { - if (Type == pptColumnID) // for a column, determine the type according to the column's value type + if (Type == pptColumnID) // for a column, determine the type according to the type of values in the column { if (ColumnIndex >= 0 && ColumnIndex < columns->Count) { @@ -1754,12 +1754,12 @@ BOOL CFTPParserParameter::GetBoolean(CFileData* file, BOOL* isDir, case pboSubStrIsNotInString: { BOOL found = FALSE; - if (lBeg < lEnd) // non-empty sample to search for + if (lBeg < lEnd) // non-empty pattern to search for { const char* s = rBeg; while (s < rEnd) { - if (LowerCase[*lBeg] == LowerCase[*s]) // does the first letter of the pattern match + if (LowerCase[*lBeg] == LowerCase[*s]) // the first letter of the pattern matches { // searching for 'lBeg' in 's' (using the simplest algorithm - O(m*n), but almost O(1) in real cases) const char* m = lBeg + 1; const char* t = s + 1; diff --git a/src/plugins/ftp/parser2.cpp b/src/plugins/ftp/parser2.cpp index 82d6560be..ab26da31a 100644 --- a/src/plugins/ftp/parser2.cpp +++ b/src/plugins/ftp/parser2.cpp @@ -190,7 +190,7 @@ void FillEmptyValues(BOOL& err, CFileData* file, BOOL isDir, } } } - else // the date is incomplete -> take the empty value + else // the date is incomplete -> use an empty value { lastWriteDate.wYear = stVal.wYear; lastWriteDate.wMonth = stVal.wMonth; @@ -300,7 +300,7 @@ BOOL CFTPParser::GetNextItemFromListing(CFileData* file, BOOL* isDir, if (!err) { - // for each column the 'emptyCol' array contains TRUE until some value is assigned + // for each column, the 'emptyCol' array contains TRUE until a value is assigned to that column int i; for (i = 0; i < columns->Count; i++) emptyCol[i] = TRUE; @@ -318,7 +318,7 @@ BOOL CFTPParser::GetNextItemFromListing(CFileData* file, BOOL* isDir, BOOL brk = FALSE; if (Rules[j]->UseRule(file, isDir, dataIface, columns, &s, listingEnd, this, &err, emptyCol)) { - if (SkipThisLineItIsIncomlete || // an incomplete listing was detected - skip the processed trailing part of the listing + if (SkipThisLineItIsIncomlete || // an incomplete listing was detected - skip the trailing part of the listing being processed !emptyCol[0]) break; // the rule succeeded - a file or directory was read - proceed to process the data brk = TRUE; // the rule succeeded - skip the line - continue parsing the next line @@ -682,7 +682,7 @@ BOOL AssignStringToColumn(int col, TIndirectArray* columns, cons } } -// returns the number of the month whose name is encoded by three letters; if it is an unknown +// returns the number of the month whose name is encoded as three letters; if it is an unknown // month code, returns -1 int GetMonthFromThreeLetters(const char* month, const char* monthStr) { @@ -769,8 +769,8 @@ int GetMonthFromThreeLettersAllLangs(const char* month, DWORD* allowedLanguagesM } } -// returns the number of the month whose name is encoded by text; if it is an unknown -// month code, returns -1 +// returns the number of the month whose name is encoded in the text; if the +// month code is unknown, returns -1 int GetMonthFromText(const char** month, const char* monthEnd, const char* monthStr) { const char* s = *month; @@ -1327,7 +1327,7 @@ BOOL CFTPParserFunction::UseFunction(CFileData* file, BOOL* isDir, { while (s < listingEnd && *s != '\r' && *s != '\n') { - if (LowerCase[*str] == LowerCase[*s]) // the first letter of the searched pattern matches + if (LowerCase[*str] == LowerCase[*s]) // the first letter of the pattern matches { // search for 'str' in 's' (using the simplest algorithm - O(m*n), but almost O(1) in real cases) const char* m = str + 1; const char* t = s + 1; @@ -1363,7 +1363,7 @@ BOOL CFTPParserFunction::UseFunction(CFileData* file, BOOL* isDir, } } else - ret = FALSE; // should never happen (NULL only on low-memory, which does not reach here) + ret = FALSE; // should never happen (NULL only under low-memory conditions, and that cannot happen here) if (needDealloc && str != NULL) free((void*)str); } diff --git a/src/plugins/ftp/parser3.cpp b/src/plugins/ftp/parser3.cpp index 96ddf7aba..371eca620 100644 --- a/src/plugins/ftp/parser3.cpp +++ b/src/plugins/ftp/parser3.cpp @@ -33,8 +33,8 @@ class CFTPAutodetCondLexAn CFTPAutodetCondLexElement ActElem; // current symbol (lexNone = it is still necessary to find the symbol) - int* ErrorResID; // if not NULL, stores the id of the string in resources that describes the error - BOOL* LowMem; // if not NULL, stores TRUE for an error caused by lack of memory + int* ErrorResID; // if not NULL, stores the ID of the string resource that describes the error + BOOL* LowMem; // if not NULL, stores TRUE if the error was caused by lack of memory char* ErrBuf; // buffer of size ErrBufSize for the textual description of the error (higher priority than ErrorResID) int ErrBufSize; // size of the ErrBuf buffer (0 = NULL buffer) @@ -221,7 +221,7 @@ CFTPAutodetCondLexAn::GetActualElement() break; } if (*s == '\r' || *s == '\n') - break; // the string cannot contain EOL directly (use escape sequences '\r' and '\n') + break; // the string cannot contain a literal EOL (use escape sequences '\r' and '\n') if (*s == '\\' && s + 1 < end) // escape sequence { s++; @@ -236,7 +236,7 @@ CFTPAutodetCondLexAn::GetActualElement() } s++; } - if (strEndFound) // string is OK + if (strEndFound) // string is valid { const char* orgStrBeg = strBeg; char* str = (char*)malloc((s - strBeg) - esc + 1); @@ -461,7 +461,7 @@ CFTPAutodetCondNode* CompileAutodetectCond(const char* cond, int* errorPos, int* if (lexAn.GetActualElement() != lexEOS) // non-empty condition -> start parsing { CFTPAutodetCondNode* node = FTP_AC_ExpOr(lexAn); - if (node != NULL && lexAn.GetActualElement() != lexEOS) // if the entire string is not parsed, it is an error (the "empty" rule from the grammar is "unpacked" here) + if (node != NULL && lexAn.GetActualElement() != lexEOS) // if the entire string is not parsed, it is an error (the "empty" grammar rule is expanded here) { lexAn.SetErrorResID(IDS_STPAR_ERR_UNEXPSYM); delete node; @@ -495,7 +495,7 @@ CFTPAutodetCondNode* CompileAutodetectCond(const char* cond, int* errorPos, int* // // allocates a new node for an operator; 'type' can only be 'acntOr' or 'acntAnd'; -// 'left'+'right' are operands; returns the allocated node; on lack of memory +// 'left'+'right' are operands; returns the allocated node; if memory is insufficient, // deallocates 'left' and 'right' and returns NULL CFTPAutodetCondNode* CreateNewACOperNode(CFTPAutodetCondLexAn& lexAn, CFTPAutodetCondNodeType type, CFTPAutodetCondNode* left, CFTPAutodetCondNode* right) @@ -517,8 +517,8 @@ CFTPAutodetCondNode* CreateNewACOperNode(CFTPAutodetCondLexAn& lexAn, CFTPAutode return node; } -// allocates a new node for negation; 'operand' is the operand of negation; returns the allocated -// node; on lack of memory deallocates 'operand' and returns NULL +// allocates a new node for negation; 'operand' is the negation operand; returns the allocated +// node; if memory is insufficient, deallocates 'operand' and returns NULL CFTPAutodetCondNode* CreateNewACNotNode(CFTPAutodetCondLexAn& lexAn, CFTPAutodetCondNode* operand) { CFTPAutodetCondNode* node = new CFTPAutodetCondNode; @@ -535,8 +535,8 @@ CFTPAutodetCondNode* CreateNewACNotNode(CFTPAutodetCondLexAn& lexAn, CFTPAutodet return node; } -// allocates a new node for a function loaded from 'lexAn'; returns the allocated node or -// NULL when memory is insufficient +// allocates a new node for a function read from 'lexAn'; returns the allocated node or +// NULL if memory is insufficient CFTPAutodetCondNode* CreateNewACFuncNode(CFTPAutodetCondLexAn& lexAn) { CFTPAutodetCondNode* node = new CFTPAutodetCondNode; diff --git a/src/plugins/ftp/servers/beta.txt b/src/plugins/ftp/servers/beta.txt index 83c834d37..a37fcee8a 100644 --- a/src/plugins/ftp/servers/beta.txt +++ b/src/plugins/ftp/servers/beta.txt @@ -1,172 +1,177 @@ +CommentsTranslationProject: TRANSLATED + This file contains a report about bug fixes and new features -in Altap Salamander. Plus sign means new feature addition, -minus sign means a bug fix. +in Altap Salamander. A plus sign means a new feature, +a minus sign means a bug fix. -FTP released with Altap Salamanderem 2.52: (08/28/2009) --MODE Z: nektere servery (napr. Serv-U 7 a 8) neukoncuji stream komprimovanych - dat, ukazovali jsme to jako chybu po kazdem prenosu, ted uz to ignorujeme --pri kopirovani bookmarky v Connect/Bookmark dialogu se nekopirovalo nastaveni - MODE Z (jen je-li zaple) --pridani bookmarky z panelu chybne inicializovalo pouzity proxy server (rozjely - se default hodnoty ve volani metody AddServer(), chybela hodnota 0 pro - 'encryptedPasswordSize') +FTP released with Altap Salamander 2.52: (08/28/2009) +-MODE Z: some servers (e.g. Serv-U 7 and 8) do not terminate the compressed-data + stream, we used to report that as an error after every transfer, now we ignore it +-when copying a bookmark in the Connect/Bookmark dialog, the MODE Z setting + was not copied (only when enabled) +-adding a bookmark from the panel initialized the selected proxy server incorrectly + (the default values in the AddServer() call shifted, the value 0 for + 'encryptedPasswordSize' was missing) -FTP released with Altap Salamanderem 2.52 beta 2: (08/21/2009) --cache listingu a prohlizenych souboru ze serveru se maze pred pripojenim na - server, pokud neni stejny server pripojen do druheho panelu nebo neni mezi - odpojenymi FS (tedy po zavreni vsech FTP spojeni v panelu a novem otevreni - FTP spojeni se uz neukazuji cachovana data) --podpora komprese datoveho spojeni (MODE Z) --drag&drop bez modifikatoru (ani Shift, ani Ctrl) z FTP v panelu do Explorera - na disk s TEMP adresarem nabizel necekane Move misto Copy, viz +FTP released with Altap Salamander 2.52 beta 2: (08/21/2009) +-the cache of listings and viewed files from the server is cleared before connecting + to the server, unless the same server is connected in the other panel or remains + among disconnected file systems (that is, after closing all FTP connections in the + panel and opening a new FTP connection, cached data is no longer shown) +-support for data-connection compression (MODE Z) +-drag&drop without modifiers (neither Shift nor Ctrl) from FTP in the panel to Explorer + on a disk with a TEMP directory unexpectedly offered Move instead of Copy, see https://forum.altap.cz/viewtopic.php?f=7&t=3303 --cache listingu rozlisuje prikazy, kterymi byl listing ziskan (drive se chybne - pouzivaly vysledky z cache i po zmene listovaciho prikazu) --automaticke aktivovani logu v Logs okne nefungovalo dobre pri pripojeni FTP do - neaktivniho panelu (kliknuti na Drive bare neaktivniho panelu) a pri neuspesnem - pripojeni (v Logs okne zustaval log neuspesneho spojeni misto navratu k logu - v aktivnim panelu) --dialogy ukazane behem provadeni FTP prikazu nad panelem se nechovaly jako modalni, - kliknuti do okna Salamandera je neaktivovalo --pod Vistou nefungovalo kliknuti mysi na zaviraci krizek wait okenek nad panelem --podpora FTPS (FTP over TLS/SSL) --provadel se refresh panelu v neaktivnim Salamanderovi i napr. pri uploadu, pri - dotazu na prepis existujiciho souboru na serveru, v panelu se tedy zobrazoval - dotaz na reconnect (connectiona je z panelu pujcena do operace) - staronove se - refresh provadi az pri aktivaci hl. okna nebo po dokonceni operace (a tedy - vraceni connectiony do panelu) +-the listing cache distinguishes the commands used to obtain the listing (previously + cached results were incorrectly reused even after the listing command changed) +-automatic log activation in the Logs window did not work correctly when FTP was + connected in the inactive panel (clicking the drive bar of the inactive panel) and + after an unsuccessful connection attempt (the log of the failed connection stayed + in the Logs window instead of returning to the log of the active panel) +-dialogs shown above the panel while an FTP command was running did not behave as + modal dialogs, clicking the Salamander window did not activate them +-on Vista, clicking the close button on wait windows above the panel did not work +-support for FTPS (FTP over TLS/SSL) +-the panel was refreshed in inactive Salamander even, for example, during upload; when + prompted to overwrite an existing file on the server, the panel then showed a reconnect + prompt (the connection is borrowed from the panel for the operation) - refresh is now + once again performed only when the main window is activated or after the operation + completes (and the connection is returned to the panel) -FTP released with Altap Salamanderem 2.52 beta 1: (01/29/2009) -+pri chybe Error Storing File to Server je nove mozne rucne prejmenovat soubor (tato - chyba se plete s chybou Error Creating Target File, staci aby byl server zbytecne - aktivni a navazal data connectionu jeste pred tim, nez zkusi otevrit soubor na - disku, coz dela napr. ftp.shutterstock.com) --zrusena hlaska "No path is accessible on this FTP server.", zbytecny pruzeni lidi, - nove provedeme tise disconnect bez dotazu (tyhle hlasce totiz vzdycky predchazi - dotaz na reconnect) --pri otevreni maximalizovaneho progress dialogu (k tomu dojde kdyz je maximalizovany - pri predchozim zavreni) se vzdy vypinal checkbox "Close this dialog when operation - finishes" --neumeli jsme pracovat s URL, ktere v uzivatelskem jmene obsahuji backslash, - napr.: ftp://corp\tomas.kopal@destft01.corp.alpine.eu/ --pri zadani spatneho cisla portu (neni cislo nebo je mimo 1 az 65535) hlasime - chybu (predtim se ignorovalo) +FTP released with Altap Salamander 2.52 beta 1: (01/29/2009) ++when the Error Storing File to Server error occurs, it is now possible to rename the + file manually (this error is confused with Error Creating Target File; it is enough + for the server to be unnecessarily active and establish the data connection before + trying to open the file on disk, which is what ftp.shutterstock.com does, for example) +-removed the "No path is accessible on this FTP server." message; it needlessly annoyed + users, now we silently disconnect without prompting (this message is always preceded + by a reconnect prompt anyway) +-when opening a maximized progress dialog (which happens when it was maximized when it + was last closed), the "Close this dialog when operation finishes" checkbox was always + cleared +-we could not handle URLs whose username contains a backslash, + e.g.: ftp://corp\tomas.kopal@destft01.corp.alpine.eu/ +-when an invalid port number is entered (not a number or outside the range 1 to 65535), + an error is reported (previously it was ignored) -FTP released with Altap Salamanderem 2.5 RC3: (04/13/2007) --upload: vypadek data-connectiony pokud control-connectiona zustala OK, - se behem Resume (appendu) vyhodnocoval, jako ze Resume neni mozny, tedy - pri "Resume or Overwrite" dochazelo k automatickemu prechodu na Overwrite -+obohacene hlaseni do Logu: hlasime duvody selhani Resume, automaticky - prechod na Overwrite a par dalsich zajimavych udalosti --SOCKS 4A/5: preferuji posilani IP adresy pred posilanim jmene adresy obsahujici IP - (nektere proxy servery neumi preklad string_IP->IP) +FTP released with Altap Salamander 2.5 RC3: (04/13/2007) +-upload: if the data connection dropped while the control connection stayed OK, + during Resume (append) it was evaluated as if Resume were impossible, so + "Resume or Overwrite" automatically fell back to Overwrite ++enhanced log reporting: we report the reasons for Resume failure, the automatic + fallback to Overwrite, and several other interesting events +-SOCKS 4A/5: prefer sending an IP address over sending a host name that contains an IP + address (some proxy servers cannot translate string_IP -> IP) -FTP released with Servant Salamanderem 2.5 RC2: (10/27/2006) -+new option in context menu and plugin's menu: List Hidden Files and Directories - (uses "LIST -a" for listing hidden files and dirs on Unix FTP servers) +FTP released with Servant Salamander 2.5 RC2: (10/27/2006) ++new option in the context menu and plugin menu: List Hidden Files and Directories + (uses "LIST -a" for listing hidden files and directories on Unix FTP servers) -FTP released with Servant Salamanderem 2.5 RC1: (04/27/2006) -+kontextove menu na souborech/adresarich v panelu -+Solve Error dialogy: zmena checkboxu na "Remember choice and do not show - this dialog again for operations with the same error" + vyhozeni comboboxu - "If this error occurs again" (ekvivalent vyber v comboboxu se nove dela na - zaklade tlacitka, ktere si user zvoli) -+Solve Error "file already exists" dialog: pridano tlacitko "Overwrite All" - (snazsi nez zapnout checkbox "Remember choice..." a kliknout na Overwrite) -+UNIX parsery: user+group muzou obsahovat mezery, v tomto pripade je jen - preskocime (nelze rozsoudit co je user a co groupa) -+parsery listingu: pridana funkce skip_to_number() - preskoci vse az k - nejblizsi dekadicke cislici -+parsery listingu: datum s rokem 1601 se automaticky predelava na rok 1602 - (stejne je to nesmyslna hodnota, s rokem 1601 je problem pri prevodu na UTC) -+IBM iSeries/i5, AS/400: pri downloadu z cesty /QSYS.LIB se automaticky - orezava .FILE cast jmena (A.FILE/A.MBR -> A.MBR + A.FILE/B.MBR -> A.B.MBR), - pri uploadu se naopak automaticky pridava .FILE cast jmena -+parser listingu pro IBM iSeries/i5, AS/400 -+pridan skryty prikaz Disconnect do menu (slouzi jen pro definici hot-key), - lidi si stezovali, ze chteji disconnect na jedinou klavesu (ne F12, Enter) +FTP released with Servant Salamander 2.5 RC1: (04/27/2006) ++context menu for files/directories in the panel ++Solve Error dialogs: changed the checkbox to "Remember choice and do not show + this dialog again for operations with the same error" and removed the combo box + "If this error occurs again" (the equivalent choice in the combo box is now made + based on the button selected by the user) ++Solve Error "file already exists" dialog: added the "Overwrite All" button + (easier than enabling the "Remember choice..." checkbox and clicking Overwrite) ++UNIX parsers: user and group may contain spaces; in that case we simply skip them + (it is impossible to tell what is the user and what is the group) ++listing parsers: added the skip_to_number() function - skips everything up to the + nearest decimal digit ++listing parsers: a date with year 1601 is automatically changed to 1602 + (it is a nonsense value anyway; year 1601 causes trouble when converting to UTC) ++IBM iSeries/i5, AS/400: when downloading from the /QSYS.LIB path, the .FILE part + of the name is automatically trimmed (A.FILE/A.MBR -> A.MBR + A.FILE/B.MBR -> A.B.MBR), + when uploading, the .FILE part of the name is added automatically instead ++listing parser for IBM iSeries/i5, AS/400 ++added a hidden Disconnect command to the menu (used only for defining a hotkey), + people complained that they wanted Disconnect on a single key (not F12, Enter) -FTP released with Servant Salamanderem 2.5 beta 11: (01/27/2006) -+pri prepisu souboru (download i upload) je fokus na Overwrite tlacitku -+dokoncena podpora pro HTTP 1.1 proxy servery -+dokoncena podpora pro SOCKS4A a SOCKS5 proxy servery -+parser listingu: doplneny svedske a norske nazvy mesicu --pri neaktualnim listingu v cilovem panelu s FTP dochazelo pri uploadu adresaru - ke hlaseni nesmyslnych chyb typu "dir already exists" nebo "dir not found" - (ted se pri takoveto chybe nejprve zkontroluje jestli listing neni prevzaty - z panelu a pripadne se listing automaticky refreshne) --odstranen deadlock (projevoval se dost zridka) pri downloadu souboru pro viewer -+dokoncena podpora pro SOCKS4 proxy servery --uploady pod XP na lokalni siti ve specialnich pripadech bezely pouze 160KB/s, - XP se v techto pripadech nejak nevyporadaji se zapisem dat na socket po 32KB, - doplnil jsem detekci tohoto zpomaleni a zapisuji po mensich blocich (16KB) --pod VM-Ware v XP se pri prenosech kolem 1MB/s nehybal progress - message queue - byla preplnena a tedy nedochazelo k dorucovani WM_TIMER (ted se WM_TIMER pri - velke zatezi generuje umele, aby pouzite timery aspon trochu fungovaly) -+moznost potlacit warning "connection has been lost" (nektere usery nezajima, ze - panel nema otevrene spojeni) -+zmena default hodnoty: upload-transfer-failed-on-created-file = Resume or Overwrite - (misto Overwrite) - ukazalo se, ze lepsi bude risknout chybu Resume (dost - nepravdepodobne), nez pouzivat jen Overwrite (u delsich uploadu se bez Resume - proste neda zit) -+zmena default hodnoty: logovani spojeni pouzivanych pro operace je ted - defaultne zapnute (rezie je minimalni, odpada vysvetlovani "jak logovani zapnout" - kazdemu, kdo ma nejaky problem s FTP) -+v pluginovem menu se pouziva prikaz SALCMD_DISCONNECT - propagace klavesy - F12 pro Disconnect -+heuristika pro ziskani jmena OS z odpovedi na SYST prikaz (nebere - tupe prvni slovo, jak rika RCF o FTP, ale hleda postupne po slovech - znamy typ OS - ted funguje i napr. nemecky preklad: "215 Betriebssystem OS/2") --na zaklade bugreportu od usera vime, ze nejen pri uploadech delsich - nez 1,5 hodiny dochazi k tomu, ze server neodpovi na STOR prikaz - nove jsem - dopsal podporu pro kontrolu velikosti souboru uploadleho v ASCII rezimu - (testuje velikost na shodu s CRLF- nebo LF-velikosti, neni to 100%, - muze hlasit "shodu" i pri nekompletnim souboru, je-li zkracen presne - o tolik znaku, kolik ma radek + ma CRLF konce radek) --v dialogu Add/Edit Proxy Server se pri otevreni vzdy nastavil defaultni - port podle typu proxy serveru (premazalo se nastaveni usera) -+po dokonceni operace na FTP serveru se provede ihned refresh panelu (neceka - se na aktivaci panelu - pokud si uzivatel odskocil do jineho programu, vrati - se do panelu s aktualnim listingem) --pri presunu souboru mezi FTP a sitovou cestou dochazelo ke zbytecnym ztratam - spojeni (operace neumela predat spojeni zpet do panelu, takze si panel zadal - o otevreni noveho spojeni a puvodni spojeni se zahazovalo) --Add Bookmark z kontextoveho menu v panelu nefungovala korektne (mela posunute - parametry) -+podpora pro dalsi mainframe: Tandem +FTP released with Servant Salamander 2.5 beta 11: (01/27/2006) ++when overwriting a file (download and upload), focus is on the Overwrite button ++completed support for HTTP 1.1 proxy servers ++completed support for SOCKS4A and SOCKS5 proxy servers ++listing parser: added Swedish and Norwegian month names +-if the listing in the target FTP panel was stale, uploading a directory caused + meaningless errors such as "dir already exists" or "dir not found" + (now, on such an error, we first check whether the listing was taken from the + panel and refresh it automatically if necessary) +-removed a deadlock (it manifested rather rarely) during download of a file for the viewer ++completed support for SOCKS4 proxy servers +-on XP in a local network, uploads ran at only 160KB/s in special cases, + apparently XP could not cope with writing data to the socket in 32KB chunks in + those cases, I added detection of this slowdown and now write in smaller blocks + (16KB) +-on XP under VMware, at transfer speeds around 1MB/s the progress indicator did not + move - the message queue was full and WM_TIMER messages were therefore not being + delivered (now WM_TIMER is generated artificially under heavy load so the timers in + use work at least somewhat) ++ability to suppress the "connection has been lost" warning (some users do not care + that the panel has no open connection) ++changed default value: upload-transfer-failed-on-created-file = Resume or Overwrite + (instead of Overwrite) - it turned out that it is better to risk a Resume error + (quite unlikely) than to use only Overwrite (for longer uploads, living without + Resume is simply not possible) ++changed default value: logging for connections used by operations is now enabled by + default (overhead is minimal, there is no need to explain "how to enable logging" + to everyone who has some FTP problem) ++the plugin menu uses the SALCMD_DISCONNECT command - propagating the F12 key for + Disconnect ++heuristic for obtaining the OS name from the response to the SYST command (it does + not take the first word blindly, as the FTP RFC says, but searches word by word + for a known OS type - now it also works for, for example, the German translation: + "215 Betriebssystem OS/2") +-based on a bug report from a user, we know that not only uploads longer than + 1.5 hours can cause the server not to respond to the STOR command - I added + support for checking the size of a file uploaded in ASCII mode + (it tests whether the size matches the CRLF or LF size, it is not 100% reliable, + it may report a "match" even for an incomplete file if it is truncated by exactly + as many characters as there are lines and it uses CRLF line endings) +-in the Add/Edit Proxy Server dialog, the default port according to the proxy + server type was always set when the dialog opened (overwriting the user's setting) ++after an operation on the FTP server finishes, the panel is refreshed immediately + (it does not wait for the panel to be activated - if the user switched to another + program, they return to the panel with an up-to-date listing) +-moving files between FTP and a network path caused unnecessary connection losses + (the operation could not hand the connection back to the panel, so the panel + requested a new connection and the original one was discarded) +-Add Bookmark from the panel context menu did not work correctly (its parameters + were shifted) ++support for another mainframe: Tandem -FTP released with Servant Salamanderem 2.5 beta 10a: (09/30/2005) --pri automatickem reconnectu v panelu se nezobrazoval duvod reconnectu - (napr. "connection lost"), ale prazdny text +FTP released with Servant Salamander 2.5 beta 10a: (09/30/2005) +-during automatic reconnect in the panel, the reason for reconnect was not shown + (e.g. "connection lost"), only an empty text -FTP released with Servant Salamanderem 2.5 beta 10: (09/27/2005) -+podpora pro FTP proxy servery (proxy na portu 21, proti klasickemu FTP jen - upravena sekvence login prikazu) --pri delsich uploadech/downloadech nez 1,5 hodiny dochazi k tomu, ze server - neodpovi na STOR/RETR prikaz - doted to znamenalo fail a tedy treba i nove - tahani celeho souboru - nove se dela test velikosti / Resume --uprava parseru VMS1-4 podle novejsi verze listingu prazdneho adresare z - cs.felk.cvut.cz (misto chyby vraci listing s jednim radkem +FTP released with Servant Salamander 2.5 beta 10: (09/27/2005) ++support for FTP proxy servers (proxy on port 21; compared to classic FTP, only + the login command sequence is modified) +-during uploads/downloads longer than 1.5 hours, the server may fail to respond + to the STOR/RETR command - until now that meant failure and thus, for example, + downloading the whole file again - now size checking / Resume is used +-adjusted the VMS1-4 parser according to a newer empty-directory listing from + cs.felk.cvut.cz (instead of an error it returns a listing with one line "Total of 0 files, 0/0 blocks") -+dopsano Skip tlacitko v operacnim dialogu -+dopsana Pause tlacitka v operacnim dialogu -+podpora pro IBM AIX v nemecke verzi (proti stavajicimu parseru ma prohozene - sloupce mesic a den) + PWD odpovedi maji nestandardni format -+Solve Error dialogy uz nevypinaji checkbox "Close this dialog when operation - finishes" (po vyreseni chyb se okno operace samo zavre) -+View, Quick Rename, Delete, Copy/Move from server (download): dopsane zamykani - pouzivanych souboru na serveru (prevence kolizi) -+Quick Rename se pta na prepis existujiciho souboru (da se potlacit v konfiguraci - na Confirmations) -+nove umi i prepis souboru jineho usera na unixovych FTP serverch (pokud - overwrite hlasi chybu, provede se nejdrive delete souboru a pak teprve zapis) -+Solve Error dialogy maji az pet tlacitek (pribylo Resume a Overwrite), - zbytek funkci je stale v kontextovem menu na Retry buttonu --pokud username obsahoval '@', nefungoval upload a mnohe dalsi veci (ted uz - snad username muze obsahovat cokoliv i ':', '/' a '\\') --pri maximalizovanem dialogu operace se Solve Error dialogy otevirali az po - deseti sekundovem cekani + "close when finished" se sam cistil (maximalizace - se chovala jako userova akce v dialogu) --Microsoft IIS (Windows NT) parser nove umi preskocit adresare a soubory beze - jmena (jen mezery v nazvu) ++added a Skip button to the operation dialog ++added Pause buttons to the operation dialog ++support for IBM AIX in the German version (compared to the existing parser, it has + swapped month and day columns) and PWD responses have a nonstandard format ++Solve Error dialogs no longer clear the "Close this dialog when operation finishes" + checkbox (after errors are resolved, the operation window closes itself) ++View, Quick Rename, Delete, Copy/Move from server (download): added locking of + files used on the server (collision prevention) ++Quick Rename asks before overwriting an existing file (can be suppressed in the + Confirmations configuration) ++it can now overwrite files owned by another user on Unix FTP servers too (if + overwrite reports an error, the file is deleted first and only then written) ++Solve Error dialogs can have up to five buttons (Resume and Overwrite were added), + the rest of the functionality remains in the context menu on the Retry button +-if the username contained '@', upload and many other things did not work (now the + username can hopefully contain anything, including ':', '/' and '\\') +-when the operation dialog was maximized, Solve Error dialogs opened only after a + ten-second wait and "close when finished" cleared itself (maximizing was treated + as a user action in the dialog) +-Microsoft IIS (Windows NT) parser can now skip directories and files without names + (only spaces in the name) diff --git a/src/plugins/ftp/servers/listings_digest.txt b/src/plugins/ftp/servers/listings_digest.txt index d546a2f2f..f68c37e9d 100644 --- a/src/plugins/ftp/servers/listings_digest.txt +++ b/src/plugins/ftp/servers/listings_digest.txt @@ -1,7 +1,7 @@ -------------------------------------------------------------------------- -------------------------------------------------------------------------- -------------------------------------------------------------------------- -IBM AS/400 (Valentn Lacko , Gary Kuznitz ) +IBM AS/400 (Valentín Lacko , Gary Kuznitz ) -------------------------------------------------------------------------- Autodetect: syst_contains(" OS/400 ") @@ -46,7 +46,7 @@ Autodetect: syst_contains(" OS/400 ") # skip empty lines anywhere * skip_white_spaces(); ---- CESKE datumy ------------------------------------------------------- +--- CZECH dates -------------------------------------------------------- QPGMR 475136 29.09.09 17:08:12 *FILE VBR 205 03.02.06 11:26:55 *DOC O0000579.TXT QSYS *MEM /QSYS.LIB/QACJINFO.FILE/QACJINFO.MBR @@ -97,7 +97,7 @@ Autodetect: syst_contains(" OS/400 ") # skip empty lines anywhere * skip_white_spaces(); ---- ANGLICKE datumy ---------------------------------------------------- +--- ENGLISH dates ------------------------------------------------------ QPGMR 475136 09/29/09 17:08:12 *FILE QSYS 45056 11/04/99 19:50:02 *FILE /QSYS.LIB/QACJINFO.FILE QSYS *MEM /QSYS.LIB/QACJINFO.FILE/QACJINFO.MBR @@ -116,7 +116,7 @@ QDFTOWN 2147483647 12/31/69 16:00:00 *DDIR QOPT/ -------------------------------------------------------------------------- -------------------------------------------------------------------------- -------------------------------------------------------------------------- -VxWorks: pomuze Eran Gluska +VxWorks: helped by Eran Gluska -------------------------------------------------------------------------- Autodetect: welcome_contains(" VxWorks ") @@ -162,7 +162,7 @@ Autodetect: welcome_contains(" VxWorks ") -------------------------------------------------------------------------- -------------------------------------------------------------------------- -------------------------------------------------------------------------- -OS/2: pomuze Krzysztof Bytnerowicz +OS/2: helped by Krzysztof Bytnerowicz -------------------------------------------------------------------------- # parse lines with files and directories * skip_white_spaces(), positive_number(), white_spaces(1), all(, 9), @@ -223,9 +223,9 @@ drwxr-xr-x folder 3 Mar 22 10:06 Upcoming Events_files -------------------------------------------------------------------------- -------------------------------------------------------------------------- -------------------------------------------------------------------------- -IBM z/VM (CMS): (jmena souboru jsou ze dvou casti - nutne doplnit '.' => napr. - soubor "WELCOME.README") -help: Format: Fixed (F) or Variable (V) + "DIR" pro adresar +IBM z/VM (CMS): (file names are made of two parts - a '.' must be inserted, e.g. + file "WELCOME.README") +help: Format: Fixed (F) or Variable (V) + "DIR" for a directory lrecl = file's logical record length -------------------------------------------------------------------------- # parse lines with directories @@ -253,7 +253,7 @@ VMNNTP DIR - - - 2002-08-27 14:59:51 - WELCNVT EXEC V 72 9 1 1999-09-20 17:16:18 - WELCOME EREADME F 80 21 1 1999-12-27 16:19:00 - WELCOME README V 82 21 1 1999-12-27 16:19:04 - ----------- DRUHA VARIANTA: "DISK" oznacuje adresar (pro oznaceni adresare se nepouziva DIR) +---------- SECOND VARIANT: "DISK" marks a directory (DIR is not used to mark directories) # parse lines with directories * word(), all_to(" DISK"), assign(, true), white_spaces(), word(), white_spaces(), number(), white_spaces(), @@ -271,12 +271,12 @@ WELCOME README V 82 21 1 1999-12-27 16:19:04 - # skip empty lines anywhere * skip_white_spaces(); ----------- NEMAME PRISTUP, test casem -------------------------------- +---------- NO ACCESS, test case -------------------------------------- README FIRST F 80 37 1 1/22/91 11:22:50 ANONYM RFC1118 TXT V 73 1347 16 10/09/89 9:51:07 ANONYM ROOTS-L DISK F 80 5 1 8/31/90 14:22:14 ANONYM WRITERS DISK F 80 8 1 12/18/90 16:51:15 ANONYM --------------- TRETI VARIANTA ------------------------------------------ +-------------- THIRD VARIANT ------------------------------------------- Autodetect: syst_contains("z/VM") # parse lines with directories @@ -301,7 +301,7 @@ Autodetect: syst_contains("z/VM") # skip empty lines anywhere * skip_white_spaces(); ----------- NEMAME PRISTUP, test casem -------------------------------- +---------- NO ACCESS, test case -------------------------------------- Filename FileType Fm Format Lrecl Records Blocks Date Time LASTING GLOBALV A1 V 41 21 1 9/16/91 15:10:32 J43401 NETLOG A0 V 77 1 1 9/12/91 12:36:04 @@ -317,13 +317,13 @@ AUTHORS A1 DIR - - - 9/20/99 10:31:11 -------------------------------------------------------------------------- -------------------------------------------------------------------------- -------------------------------------------------------------------------- -MVS: pomuze Michael Knigge nebo +MVS: helped by Michael Knigge or Krzysztof Bytnerowicz help: Ext = Extents, Dsorg = Data Set Organization (PO = partitioned organized - (library, brat jako archiv=soubor), PS = physical sequential (obycejny file)), + (library, treat as archive=file), PS = physical sequential (ordinary file)), Dsname = Data Set Name, Recfm=Record Format, Lrecl=Logical Record Length, BlkSz=Physical Block Length -"Pseudo Directory" se objevuje jen, pokud je zapnuty pseudo-directory mode FTP serveru +"Pseudo Directory" appears only when pseudo-directory mode is enabled on the FTP server -------------------------------------------------------------------------- Autodetect: syst_contains(" MVS ") @@ -436,7 +436,7 @@ TSO61A Error determining attributes CSNM18.BKP.XE61 VGSA03 Tape BOOL.IMF.SA03.SVCDUMP PATH CAPRI.CSD.PATHA ------------ DRUHA VARIANTA LISTINGU (jiny datum) -------------------- +----------- SECOND LISTING VARIANT (different date) ------------------ Autodetect: syst_contains(" MVS ") # data sets @@ -530,8 +530,8 @@ MVXE61 Not Mounted CSNM2.BKP.XE61 VGSA03 Tape BOOL.IMF.SA03.SVCDUMP PATH CAPRI.CSD.PATHA ------------------------- TRETI VARIANTA LISTINGU --------------------- -help: Init=Initial Size, Id=User, Mod=???? (zeptat se Michaela !!!) +------------------------ THIRD LISTING VARIANT ----------------------- +help: Init=Initial Size, Id=User, Mod=???? (ask Michael!!!) -------------------------------------------------------------------------- Autodetect: syst_contains(" MVS ") @@ -560,7 +560,7 @@ OMCSIRAU 01.01 1992/06/03 1992/06/03 14:46 349 349 0 ASEPMD OMCSIRBF ASCIITAB 01.00 1998/06/08 1998/06/08 13:32 526 526 0 VEA0013 ------------------------- CTVRTA VARIANTA LISTINGU (jiny datum) ------- +------------------------ FOURTH LISTING VARIANT (different date) ----- Autodetect: syst_contains(" MVS ") # members @@ -590,7 +590,7 @@ GREETING 01:00 12/08/93 12/09/93 6:19 12 12 0 MVS OMCSIRBF GREE 01:00 12/08/93 12/09/93 6:19 12 12 0 MVS ------------------------- PATA VARIANTA LISTINGU (chybi created) ----- +------------------------ FIFTH LISTING VARIANT (created missing) ---- Autodetect: syst_contains(" MVS ") # members @@ -619,7 +619,7 @@ NAME VV.MM CHANGED SIZE INIT MOD ID OMCSIRBF #PDEX 01.00 95/09/29 16:29 47 47 0 USER01 ------------------------- SESTA VARIANTA LISTINGU ------------------------- +------------------------ SIXTH LISTING VARIANT ----------------------- Autodetect: syst_contains(" MVS ") #datasets @@ -657,7 +657,7 @@ BIB1 0010F8 000124 DC 24 24 -------------------------------------------------------------------------- -------------------------------------------------------------------------- VMS: (ubvms.cc.buffalo.edu) --------------- PRVNI VARIANTA ------------------------------------------ +-------------- FIRST VARIANT ------------------------------------------- Autodetect: syst_contains(" VMS ") # parse lines with directories @@ -741,8 +741,8 @@ PLILP28D.DIR;1 1 3-APR-1997 17:51 [UCX$NOBO,UCX$NOBODY (RWED,RWED Total of 7 blocks in 7 files. ------------------------- DRUHA VARIANTA - CS.FELK.CVUT.CZ --------------------- -(petr.DIR;2 je soubor - aspon VMS na CS se k nemu tak chova) +------------------------ SECOND VARIANT - CS.FELK.CVUT.CZ --------------------- +(petr.DIR;2 is a file - at least VMS at CS behaves that way) ------------------------------------------------------------------------------- Autodetect: syst_contains(" VMS ") @@ -831,7 +831,7 @@ PLILP28D.DIR;1 1/3 3-APR-1997 17:51:01 [UCX$NOBO,UCX$NOBODY Total of 527 files, 22268/24048 blocks ------------------------- TRETI VARIANTA - web (byty/bloky) --------------------- +------------------------ THIRD VARIANT - web (bytes/blocks) -------------------- Autodetect: syst_contains(" VMS ") # parse lines with directories @@ -893,7 +893,7 @@ TMP.DIR;1 9-OCT-1991 10:29:53 512/1 (RWE,RE,RE,RWE) EA95_0PS.GZ;1 No privilege for attempted operation EA95_0PSD.DIR;1 No privilege for attempted operation ------ CTVRTA VARIANTA - ftp.process.com (cas na ms, chybi prava a bloky) ----- +----- FOURTH VARIANT - ftp.process.com (time in ms, rights and blocks missing) ---- Autodetect: syst_contains(" VMS ") # parse lines with directories @@ -998,7 +998,7 @@ total 0 d [RWCEAFMS] Patera 512 Jun 24 13:59 Windows NT 5.0 Workstation Profile.03.17 - [RWCEAFMS] Patera 124275 Mar 24 2000 pv193cz.zip -------------- DRUHA VARIANTA - Hellsoft (kod parseru viz vyse) ----------- +------------- SECOND VARIANT - Hellsoft (parser code see above) ---------- -------------- listing -------------- -[RWCEMFA] 1 xpatera1 1140 Jun 22 2001 euro50.pcx @@ -1013,10 +1013,10 @@ d[R----F-] 1 supervis 512 Nov 30 08:02 limpouch -------------------------------------------------------------------------- -------------------------------------------------------------------------- -------------------------------------------------------------------------- -UNIX: PRVNI VARIANTA (IBM AIX, Filezilla a dalsi) +UNIX: FIRST VARIANT (IBM AIX, Filezilla, and others) -------------------------------------------------------------------------- -(odlisnost od druhe varianty: maji dve mezery po roce pred jmenem) -(ma prioritu, protoze pravdepodobnejsi jsou jmena bez mezer na zacatku) +(difference from the second variant: they have two spaces after the year before the name) +(has priority because names without leading spaces are more likely) Autodetect: not syst_contains("z/VM ") and not syst_contains("OS/2 ") and not syst_contains(" MACOS ") and not syst_contains("Windows_NT") @@ -1154,9 +1154,9 @@ lrwx------ 1 root name root 0 Oct 16 14:08 cwd lrwx------ 1 solin name users 0 Oct 16 14:15 cwd -> /proc/20493 pr--r--r-- 1 root name root 0 Oct 16 14:08 maps ------------------------- DRUHA VARIANTA - ProFTPD a dalsi ---------- -(funguje korektne pro servery, ktere maji po roce pred jmenem jedinou mezeru; -prvni varianta parseru totiz nekorektne orezava prvni mezeru ve jmene) +------------------------ SECOND VARIANT - ProFTPD and others -------- +(works correctly for servers that have a single space after the year before the name; +the first parser variant incorrectly trims the first space in the name) Autodetect: not syst_contains("z/VM ") and not syst_contains("OS/2 ") and not syst_contains(" MACOS ") and not syst_contains("Windows_NT") @@ -1252,7 +1252,7 @@ lrwx------ 1 root name root 0 Oct 16 14:08 cwd lrwx------ 1 solin name users 0 Oct 16 14:15 cwd -> /proc/20493 pr--r--r-- 1 root name root 0 Oct 16 14:08 maps ------------------------- TRETI VARIANTA - Sun (nejen) --------------------- +------------------------ THIRD VARIANT - Sun (and others) ---------------- Autodetect: (not welcome_contains(" NW ") or not welcome_contains(" HellSoft.")) and not syst_contains("z/VM ") and not syst_contains("OS/2 ") and not syst_contains(" MACOS ") and not syst_contains("Windows_NT") @@ -1327,7 +1327,7 @@ drwxr-x--- 2 other name 2048 Apr 7 1999 advpanel lrwxrwxrwx 1 other name 7 Mar 22 2000 bin -> usr/bin lrwxrwxrwx 1 other name 7 Jul 29 18:06 ccm -> pub/ccm ------------------------- CTVRTA VARIANTA - HP-UNIX (nemecky) -------------- +------------------------ FOURTH VARIANT - HP-UNIX (German) --------------- Autodetect: not syst_contains("z/VM ") and not syst_contains("OS/2 ") and not syst_contains(" MACOS ") and not syst_contains("Windows_NT") @@ -1388,15 +1388,15 @@ Autodetect: not syst_contains("z/VM ") and not syst_contains("OS/2 ") and insgesamt 611176 drwxrwxr-x 5 ftp ftp 4096 4. Jan., 14:00 . drwxrwxr-x 3 ftp ftp 4096 4. Jan., 14:00 .. -lrwxrwxrwx 1 solin users 4 23. Mrz 2004 file_link -> file +lrwxrwxrwx 1 solin users 4 23. März 2004 file_link -> file crw-r----- 1 root disk 27, 24 5. Feb. 2004 zqft0 brw-rw---- 1 root disk 13, 121 19. Mai 2004 xdb57 lrwx------ 1 root root 0 24. Juni 2004 cwd -rw-rw-rw- 1 catusr catia 81 4. Jan., 14:00 CATDXF.in -rwxrwxrwx 1 catusr catia 100403 5. Feb. 2004 CATOLER.out --rwxr-xr-x 1 catusr catia 545 23. Mrz 2004 catcust +-rwxr-xr-x 1 catusr catia 545 23. März 2004 catcust -rwxr-xr-x 1 catusr catia 545 14. Apr. 2004 Acrobat_Reader --rw-rw-r-- 1 catusr catia 1640480 19. Mai 2004 11-59D_323326_BM_V00_ROB_SCHNELLWECHSELKUPPLUNG_VKR30_40___030702_PJW.model +-rw-rw-r-- 1 catusr catia 1640480 19. Mai 2004 11-59D_323326_BM_V00_ROB_SCHNELLWECHSELKUPPLUNG_VKR±30_40___030702_PJW.model -rw-r----- 1 catusr catia 60640 24. Juni 2004 PECIATKA_STN.model -rwxrwxrwx 1 catusr catia 2558 2. Juli 2003 MECENV.dcls -rw-rw-r-- 1 catusr catia 2916 18. Aug., 09:06 USRENV_1.dcls @@ -1406,15 +1406,15 @@ drwxr--r-- 2 catusr catia 96 31. Okt. 2003 CATSettings -rw-r----- 1 catusr catia 11417 30. Dez., 11:10 ema_KG_update_rollmenu.dcls drwxrwxr-x 5 ftp name ftp 4096 4. Jan., 14:00 . drwxrwxr-x 3 ftp name ftp 4096 4. Jan., 14:00 .. -lrwxrwxrwx 1 solin name users 4 23. Mrz 2004 file_link -> file +lrwxrwxrwx 1 solin name users 4 23. März 2004 file_link -> file crw-r----- 1 root name disk 27, 24 5. Feb. 2004 zqft0 brw-rw---- 1 root name disk 13, 121 19. Mai 2004 xdb57 lrwx------ 1 root name root 0 24. Juni 2004 cwd -rw-rw-rw- 1 cat usr catia 81 4. Jan., 14:00 CATDXF.in -rwxrwxrwx 1 cat usr catia 100403 5. Feb. 2004 CATOLER.out --rwxr-xr-x 1 cat usr catia 545 23. Mrz 2004 catcust +-rwxr-xr-x 1 cat usr catia 545 23. März 2004 catcust -rwxr-xr-x 1 cat usr catia 545 14. Apr. 2004 Acrobat_Reader --rw-rw-r-- 1 cat usr catia 1640480 19. Mai 2004 11-59D_323326_BM_V00_ROB_SCHNELLWECHSELKUPPLUNG_VKR30_40___030702_PJW.model +-rw-rw-r-- 1 cat usr catia 1640480 19. Mai 2004 11-59D_323326_BM_V00_ROB_SCHNELLWECHSELKUPPLUNG_VKR±30_40___030702_PJW.model -rw-r----- 1 cat usr catia 60640 24. Juni 2004 PECIATKA_STN.model -rwxrwxrwx 1 cat usr catia 2558 2. Juli 2003 MECENV.dcls -rw-rw-r-- 1 cat usr catia 2916 18. Aug., 09:06 USRENV_1.dcls @@ -1423,8 +1423,8 @@ drwxr--r-- 2 cat usr catia 96 31. Okt. 2003 CATSettings -rw-rw-rw- 1 cat usr catia 358 19. Nov., 11:12 DXFCAT.out -rw-r----- 1 cat usr catia 11417 30. Dez., 11:10 ema_KG_update_rollmenu.dcls ------------------------- PATA VARIANTA - nemecky AIX ---------- -(kopie prvni varianty UNIX parseru, jen maji prohozeny mesic a den) +------------------------ FIFTH VARIANT - German AIX ----------------- +(copy of the first UNIX parser variant, only the month and day are swapped) Autodetect: not syst_contains("z/VM ") and not syst_contains("OS/2 ") and not syst_contains(" MACOS ") and not syst_contains("Windows_NT") @@ -1521,7 +1521,7 @@ Autodetect: not syst_contains("z/VM ") and not syst_contains("OS/2 ") and # skip empty lines anywhere * skip_white_spaces(); ------------ (pouzity testovaci listing s anglickyma mesicema) ---------------- +----------- (test listing with English month names used) -------------------- total 80 lrwxrwxrwx 1 biaf iplus 11 14 Dec 2004 BIAF_Wetter -> biaf_wetter drwxrwxr-x 5 ftp ftp 4096 2 Aug 13:39 . @@ -1563,8 +1563,8 @@ lrwx------ 1 root name root 0 16 Oct 14:08 cwd lrwx------ 1 solin name users 0 16 Oct 14:15 cwd -> /proc/20493 pr--r--r-- 1 root name root 0 16 Oct 14:08 maps ------------------------- SESTA VARIANTA - MOXA (inetutils, Linux 2.6.9-MoXaRt) ---------- -(chybi casy + datumy) +------------------------ SIXTH VARIANT - MOXA (inetutils, Linux 2.6.9-MoXaRt) ---------- +(times and dates are missing) Autodetect: not syst_contains("z/VM ") and not syst_contains("OS/2 ") and not syst_contains(" MACOS ") and not syst_contains("Windows_NT") @@ -1745,8 +1745,8 @@ pk_cal.fil 532 -------------------------------------------------------------------------- -PC-NFSD: (WinCmd) - delene nazvy/pripony souboru, carky ve velikosti, - adresarum chybi velikost, a.m./p.m. v casech +PC-NFSD: (WinCmd) - split file names/extensions, commas in sizes, + directories have no size, a.m./p.m. in times -------------------------------------------------------------------------- prog1 exe 2,563,136 06-10-99 10:00a temp 01-27-97 3:41p @@ -1755,7 +1755,7 @@ temp 01-27-97 3:41p -------------------------------------------------------------------------- -VOS (Stratus): (WinCmd) - adresare maji o sloupec mene +VOS (Stratus): (WinCmd) - directories have one fewer column -------------------------------------------------------------------------- w 10 seq 99-04-20 11:15:42 abbreviations m 4 99-07-02 10:11:25 arsffs32 diff --git a/src/plugins/ftp/servers/parsing.txt b/src/plugins/ftp/servers/parsing.txt index fb3c805a3..bcec0ee19 100644 --- a/src/plugins/ftp/servers/parsing.txt +++ b/src/plugins/ftp/servers/parsing.txt @@ -1,478 +1,500 @@ -Popis formatu pravidel pro parsovani: -===================================== - -Komentar zacina znakem '#' a je ukoncen koncem radky. - -Vsechny pravidla zacinaji znakem '*' a konci znakem ';'. Pocet -pravidel neni omezen. Pravidlo se sklada z funkci vzajemne -oddelenych znakem ','. - -Funkce se sklada ze jmena, znaku '(', seznamu parametru a -znaku ')'. - -Seznam jmen funkci je uveden dale v dokumentu. - -V seznamu parametru funkce jsou jednotlive parametry vzajemne -oddelene znakem ','. Parametry jsou vyrazy. - -Vyraz tvori identifikator sloupce, stavova promenna, konstanta -nebo jedna binarni operace. Binarni operace se zapisuje -v klasicke notaci (prvni_operand operacni_znak druhy_operand) -a jako operandy se pouzivaji identifikatory sloupcu, stavove -promenne nebo konstanty. - -Seznam stavovych promennych je uveden dale v dokumentu. - -Seznam operacnich znaku je uveden dale v dokumentu. - -Konstanty jsou typu retezec, cislo nebo boolean. - -Retezec je ohranicen znaky '"', retezec nemuze presahovat -konec radky, escape-sekvence jsou uvozeny znakem '\': pro -znak '"' je to "\"", pro znak '\' je to "\\", pro znak -tabelator je to "\t", pro znaky konce radku CR+LF je to -dvojice "\r" a "\n". Nezname escape-sekvence se hlasi jako -chyby. - -Cislo se zapisuje desitkove bez jakychkoliv oddelovacu. -Zaporne cislo zacina znakem '-'. Kladne cislo zacina -znakem '+' (muze byt vynechan). - -Boolean je "true" nebo "false" (psano bez uvozovek). - -Uzivatel definuje sloupce. Kazdy sloupec ma jmeno identifikatoru, -typ hodnot, prazdnou hodnotu a jmeno a popis pro zobrazeni -v panelu. Identifikator se pouziva pri prirazovani hodnot -do sloupcu. Kazda polozka muze mit ve sloupci prirazenou -prave jednu hodnotu. Pokud nedoslo k prirazeni zadne hodnoty, -pouziva se ve sloupci uzivatelem definovana prazdna hodnota. -Dale se u sloupcu definuje, jestli se maji zobrazovat v panelu. -Zobrazeni nelze vypnout u sloupcu typu "Name" a "Extension". - -Identifikator sloupce zacina znakem '<', obsahuje jmeno -identifikatoru zadane uzivatelem a konci znakem '>'. - -Existuji nasledujici typy sloupcu: -- Name - (retezec) prave jeden sloupec tohoto typu je povinny, - nemuze byt schovany, definice prazdne hodnoty u nej nema smysl, - parser do nej musi u kazdeho souboru a adresare priradit, - pokud k prirazeni nedojde, nevznika parsovanim podle aktualniho - pravidla zadny soubor ani adresar - pouziva se pro preskok - prazdnych radek a dalsich nepodstatnych casti listingu, - prirazeni prazdneho retezce do tohoto sloupce se povazuje - za chybu parsovani, -- Extension - generuje se na zaklade hodnoty ve sloupci typu - "Name", nemuze byt schovany, definice prazdne hodnoty u nej - nema smysl, -- Size - (cislo - unsigned int64), u adresaru je hodnota vzdy 0 - a v panelu se zobrazuje "DIR", defaultni prazdna hodnota je 0, -- Date - (datum) - datum musi byt platny (jinak je nahrazen hodnotou - 1.1.1602), defaultni prazdna hodnota je 1.1.1602, -- Time - (cas) - defaultni prazdna hodnota je 0:00:00, -- Type - generuje se na zaklade hodnoty ve sloupci typu "Name", - definice prazdne hodnoty u nej nema smysl, -- Any Text - (retezec) - defaultni prazdna hodnota je "", -- Any Date - (datum) - datum musi byt platny (jinak je nahrazen - hodnotou 1.1.1602), defaultni prazdna hodnota je "", -- Any Time - (cas) - defaultni prazdna hodnota je "", -- Any Number - (cislo - signed int64) - defaultni prazdna hodnota - je "". - -Navic existuji tri sloupce s identifikatory "", "" -a "". Do vsech tri se prirazuji hodnoty typu boolean a rikaji -o polozce jestli je "soubor" nebo "adresar", jestli "je skryta" nebo -"neni skryta" a jestli "je link" nebo "neni link". Prirazeni do techto -sloupcu neni povinne, jejich prazdne hodnoty jsou "soubor", -"neni skryta" a "neni link". - - -Popis formatu podminky pro autodetekci: -======================================= - -Jde o logicky vyraz. Operatory ve vyrazu jsou (od nejvyssi -priority): NOT, AND a OR. NOT (logicka negace) je unarni, AND -(logicky soucin) a OR (logicky soucet) jsou binarni. Ve vyrazu -je dale mozne pouzivat zavorky (vymezeni podvyrazu). Jako operandy -se pouzivaji nasledujici funkce: - -- syst_contains(retezec) - nabyva hodnoty TRUE pokud se v odpovedi - serveru na prikaz SYST (get type of operating system) vyskytuje - zadany retezec, - -- welcome_contains(retezec) - nabyva hodnoty TRUE pokud se v prvni - odpovedi serveru (hned po navazani spojeni) vyskytuje zadany - retezec, - -- reg_exp_in_syst(retezec_regularniho_vyrazu) - nabyva hodnoty TRUE - pokud se v odpovedi serveru na prikaz SYST (get type of operating - system) vyskytuje retezec odpovidajici zadanemu regularnimu - vyrazu, - -- reg_exp_in_welcome(retezec_regularniho_vyrazu) - nabyva hodnoty TRUE - pokud se v prvni odpovedi serveru (hned po navazani spojeni) - vyskytuje retezec odpovidajici zadanemu regularnimu vyrazu. - +CommentsTranslationProject: TRANSLATED -Ziskani listingu pri pevne danem typu serveru: -============================================== - -Spusti se parsovani textu listingu. Pokud parsovani dopadne dobre, -pouziji se ziskane vysledky a algoritmus se ukonci. Pri neuspechu -parsovani se zobrazi text listingu bez uprav v panelu. - -Pred umistenim listingu do panelu jeste probehne odstraneni adresare -"." (je-li ve vysledcich parsovani) a u korenove cesty take -adresare ".." (je-li ve vysledcich parsovani). Pokud v listingu -zustava adresar "..", je vzdy viditelny (ignoruje se hodnota ve -sloupci ""). - - -Popis autodetekce typu serveru: +Description of the rule parsing format: ======================================= -Postupne se prochazeji vsechny definovane typy serveru. U kazdeho se -vyhodnoti "autodetect condition". Pokud tato podminka neni splnena, -pokracuje se v prochazeni dalsim typem serveru. Pri splneni podminky -se spusti parsovani textu listingu. Pokud parsovani dopadne dobre, -pouziji se ziskane vysledky a algoritmus se ukonci. Pokud nastane pri -parsovani chyba, pokracuje se v prochazeni dalsim typem serveru. - -Pokud se timto zpusobem projdou vsechny typy serveru bez uspechu, -pokracuje se postupnym prochazenim tech typu serveru, u kterych -nebyla splnena "autodetect condition". U nich se spousti parsovani -textu listingu. Stejne jako v predeslem pripade se algoritmus ukonci -v okamziku, kdy parsovani probehne bez chyby. - -Pokud zadny parser z definovanych typu serveru neuspeje pri parsovani -textu listingu, zobrazi se text listingu bez uprav v panelu. - -Autodetekce probehne timto zpusobem jen u listingu prvni cesty -na serveru. Pro dalsi listingy ze serveru se zkusi pouzit stejny -typ serveru jako pro predchozi listing (aby napr. prazdne listingy -meli "spravne" sloupce v panelu, atp.). Jen pokud nastane pri -parsovani timto typem serveru chyba, spusti se znovu proces -autodetekce typu serveru. - -Pred umistenim listingu do panelu jeste probehne odstraneni adresare -"." (je-li ve vysledcich parsovani) a u korenove cesty take -adresare ".." (je-li ve vysledcich parsovani). Pokud v listingu -zustava adresar "..", je vzdy viditelny (ignoruje se hodnota ve -sloupci ""). - - -Popis prubehu parsovani: -======================== - -Za uspech parseru se povazuje to, kdyz se podari pouzitim definovanych -pravidel projit cely text listingu. - -Pro popis algoritmu zavedeme pojem "ukazovatko", ktery oznacuje -pozici v textu listingu. +A comment starts with the '#' character and ends at the end of the line. + +All rules start with the '*' character and end with ';'. The number of +rules is unlimited. A rule consists of functions separated by ','. + +A function consists of a name, the '(' character, a list of +parameters, and the ')' character. + +The list of function names is given later in this document. + +In a function parameter list, individual parameters are separated by +','. Parameters are expressions. + +An expression consists of a column identifier, a state variable, a +constant, or one binary operation. A binary operation is written in the +usual notation (first_operand operator second_operand), and its +operands are column identifiers, state variables, or constants. + +The list of state variables is given later in this document. + +The list of operator symbols is given later in this document. -Pravidla se skladaji z funkci. Pravidlo muze byt pouzito jen tehdy, -kdyz se vsechny jeho funkce vyhodnoti jako uspesne, do sloupce typu -"Name" nebyl prirazen prazdny retezec (tedy bud byl prirazen -neprazdny retezec nebo k prirazeni vubec nedoslo) a ukazovatko -skonci na konci nektere radky textu listingu. Po pouziti pravidla -se ukazovatko automaticky presouva na zacatek nasledujici radky -textu listingu. - -Funkce krome vyhodnoceni sve uspesnosti a posunu ukazovatka jeste -muze prirazovat hodnotu do sloupce nebo tuto hodnotu muze menit. - -Parser muze mit definovanou celou radu pravidel. Vyber pravidla, -ktere se ma v dany okamzik parsovani pouzit, se vzdy provadi -v poradi jejich definice. Jinymi slovy, vzdy se pouzije prvni -pouzitelne pravidlo. - -Text listingu muze byt nekompletni z duvodu preruseni jeho nacitani -at jiz na zadost uzivatele nebo pro chybu spojeni se serverem. -Nekompletni text listingu je upraveny tak, ze obsahuje jen kompletni -radky textu (zbytek je oriznuty). - -Parsovani nekompletnich textu listingu je reseno na urovni pouzivani -pravidel. V jednodussim pripade se ukazovatko dostane na konec -textu po pouziti pravidla a tim se parsovani ukonci. Ve slozitejsim -pripade se pri pouziti pravidla vyhodnocuje funkce, ktera ma -ukazovatko posunout na dalsi radku. Tento posun neni mozny jen diky -nekompletnosti textu listingu, a proto se parsovani ukonci uspesne -(jako by text listingu koncil tak, ze by prave pouzivane pravidlo -nebylo vubec treba). - - -Zobrazeni celkove velikosti oznacenych souboru v info-line: -=========================================================== - -Aby se pri oznaceni skupiny souboru v info-line zobrazovala celkova -velikost v bytech nebo blocich, je nutne aby byla velikost souboru -ulozena ve sloupci typu "File Size in Bytes" nebo ve sloupci -typu "Any Number" pojmenovanem standardnim jmenem "Blocks" nebo -"BlkSz". - - -Seznam funkci: -============== - -Pokud neni uvedeno jinak, je funkce vzdy uspesna, neposouva ukazovatko -a neprirazuje hodnotu do zadneho sloupce. Pokud funkce posouva -ukazovatko, tak pokud neni uvedeno jinak, tak neumi preskocit konec -radky. - -Pred pouzitim identifikatoru sloupce ve vyrazu je nutne do -sloupce priradit hodnotu. Bez tohoto prirazeni vyraz nema -smysl (takovy vyraz se da nahradit booleanovou konstantou -vypocitanou dosazenim prazdne hodnoty pro dany sloupec do vyrazu). - -(white-space: mezera nebo tabelator) - -- skip_white_spaces() - preskoci ukazovatkem vsechny znaky white-space, - -- skip_to_number() - preskoci ukazovatkem k nejblizsi dekadicke cislici, - -- white_spaces() - preskoci ukazovatkem vsechny znaky white-space, - funkce je uspesna jen pokud dojde k posunu ukazovatka, - -- white_spaces(cislo) - preskoci ukazovatkem retezec znaku white-space - o delce 'cislo', funkce je uspesna jen pokud takovy retezec existuje, - -- white_spaces_and_line_ends() - preskoci ukazovatkem vsechny znaky - white-space a znaky konce radky, funkce je uspesna jen pokud - dojde k posunu ukazovatka a ukazovatko neskonci na konci listingu - (zarazi se na nejakem znaku), - -- rest_of_line() - posune ukazovatko na konec radky, funkce je uspesna - jen pokud dojde k posunu ukazovatka, - -- rest_of_line() - (typ hodnot ve sloupci musi byt - retezec) - priradi do sloupce retezec, ktery saha od ukazovatka az - do konce radky, ukazovatko se posune na konec radky, funkce je uspesna, - pokud se posune ukazovatko, - -- word() - preskoci ukazovatkem vsechny znaky mimo white-space a znak - konce radky, funkce je uspesna jen pokud dojde k posunuti ukazovatka, - -- word() - (typ hodnot ve sloupci musi byt retezec) - priradi do - sloupce retezec, ktery saha od ukazovatka az do prvniho white-space nebo - konce radky, ukazovatko se posune za konec tohoto retezce, funkce je - uspesna, pokud lze retezec ziskat (obsahuje aspon jeden znak), - -- number() - (typ hodnot ve sloupci musi byt cislo) - priradi - do sloupce dekadicke cislo lezici na pozici ukazovatka, toto cislo - nesmi byt ukoncene pismenem - povolene jsou vsechny oddelovace (',', - '.', ';', ':', atd.) vcetne znaku white-space a konce radku, ukazovatko - se posune za konec tohoto cisla, funkce je uspesna, pokud cislo existuje, - je korektne ukoncene a pokud jde o sloupec typu "Size", pak jeste pokud - je cislo nezaporne, - -- positive_number() - (typ hodnot ve sloupci musi byt cislo) - priradi - do sloupce kladne dekadicke cislo lezici na pozici ukazovatka, je-li cislo - zaporne, do sloupce se priradi defaultni prazdna hodnota (nula pro typ Size, - "" pro typ Any Number), toto cislo nesmi byt ukoncene pismenem - povolene - jsou vsechny oddelovace (',', '.', ';', ':', atd.) vcetne znaku white-space - a konce radku, ukazovatko se posune za konec tohoto cisla, funkce je uspesna, - pokud cislo existuje a je korektne ukoncene, - -- number_with_separators(, retezec) - (typ hodnot ve sloupci musi - byt cislo) - priradi do sloupce dekadicke cislo s oddelovaci radu - (pouziva se pro snazsi cteni velkych cisel, povolene oddelovace jsou - v retezci 'retezec', povolene jsou vsechny znaky krome '+', '-' a cislic) - lezici na pozici ukazovatka, toto cislo nesmi byt ukoncene - pismenem - povolene jsou vsechny oddelovace (',', '.', ';', ':', atd.) - vcetne znaku white-space a konce radku, ukazovatko se posune za konec - tohoto cisla, funkce je uspesna, pokud cislo existuje, je korektne - ukoncene a pokud jde o sloupec typu "Size", pak jeste pokud je cislo - nezaporne, - -- month_3() - (typ hodnot ve sloupci musi byt datum) - obohati - hodnotu ve sloupci o mesic rozpoznany ve trech pismenech na pozici - ukazovatka, pracuje s nazvy mesicu v ruznych jazycich (zatim alespon - anglicky a nemecky), mesic nesmi byt ukonceny pismenem - povolene jsou - vsechny oddelovace (',', '.', ';', ':', atd.) vcetne znaku white-space - a konce radku, ukazovatko se posune za tato tri pismena, funkce je - uspesna jen pokud byl mesic rozpoznan a vsechny mesice v listingu - patri do jedineho jazyku, - -- month_3(, retezec) - (typ hodnot ve sloupci musi byt - datum) - obohati hodnotu ve sloupci o mesic rozpoznany ve trech - pismenech na pozici ukazovatka, nazvy mesicu jsou v retezci, ktery - musi obsahovat dvanact tripismenych nazvu mesicu vzajemne oddelenych - mezerami (napr. "jan feb mar apr may jun jul aug sep oct nov dec" - pro anglictinu), mesic nesmi byt ukonceny pismenem - povolene jsou - vsechny oddelovace (',', '.', ';', ':', atd.) vcetne znaku - white-space a konce radku, ukazovatko se posune za tato tri pismena, - funkce je uspesna jen pokud byl mesic rozpoznan, - -- month_txt() - (typ hodnot ve sloupci musi byt datum) - obohati - hodnotu ve sloupci o mesic rozpoznany na pozici ukazovatka, pracuje - s nazvy mesicu v ruznych jazycich (zatim jen nemecky), mesic nesmi byt - ukonceny pismenem - povolene jsou vsechny oddelovace (',', '.', ';', - ':', atd.) vcetne znaku white-space a konce radku, ukazovatko se posune - za nazev mesice, funkce je uspesna jen pokud byl mesic rozpoznan a - vsechny mesice v listingu patri do jedineho jazyku, - -- month_txt(, retezec) - (typ hodnot ve sloupci musi byt - datum) - obohati hodnotu ve sloupci o mesic rozpoznany na pozici - ukazovatka, nazvy mesicu jsou v retezci, ktery musi obsahovat dvanact - nazvu mesicu vzajemne oddelenych mezerami (napr. - "Jan. Feb. Mrz Apr. Mai Juni Juli Aug. Sept. Okt. Nov. Dez." pro - nemcinu), mesic nesmi byt ukonceny pismenem - povolene jsou vsechny - oddelovace (',', '.', ';', ':', atd.) vcetne znaku white-space a konce - radku, ukazovatko se posune za nazev mesice, funkce je uspesna jen pokud - byl mesic rozpoznan, - -- month() - (typ hodnot ve sloupci musi byt datum) - obohati - hodnotu ve sloupci o mesic ulozeny jako dekadicke cislo na pozici - ukazovatka, toto cislo nesmi byt ukoncene pismenem - povolene jsou - vsechny oddelovace (',', '.', ';', ':', atd.) vcetne znaku white-space - a konce radku, ukazovatko se posune za konec cisla mesice, funkce je - uspesna jen pokud je cislo mesice platne (1 az 12), - -- day() - (typ hodnot ve sloupci musi byt datum) - obohati - hodnotu ve sloupci o den ulozeny jako dekadicke cislo na pozici - ukazovatka, toto cislo nesmi byt ukoncene pismenem - povolene jsou - vsechny oddelovace (',', '.', ';', ':', atd.) vcetne znaku white-space - a konce radku, ukazovatko se posune za konec cisla dne, funkce je - uspesna jen pokud je cislo dne platne (1 az 31), - -- year() - (typ hodnot ve sloupci musi byt datum) - obohati - hodnotu ve sloupci o rok ulozeny jako dekadicke cislo na pozici - ukazovatka, toto cislo nesmi byt ukoncene pismenem - povolene jsou - vsechny oddelovace (',', '.', ';', ':', atd.) vcetne znaku white-space - a konce radku, ukazovatko se posune za konec cisla roku, funkce je - uspesna jen pokud je cislo roku platne (0-999 (0-79=>+2000, - 80-999=>+1900) nebo 1602-9999), - -- time() - (typ hodnot ve sloupci musi byt cas) - obohati - hodnotu ve sloupci o hodiny, minuty, sekundy a pripadne i milisekundy - nalezene jako vzajemne oddelena dekadicka cisla na miste ukazovatka, - ocekavane formaty jsou 00:00 nebo 00:00:00 nebo 00:00:00.000, pokud - primo za posledni cislici casoveho udaje nasleduje retezec "a"/"am" - nebo "p"/"pm", je povazovan za "a.m." (rano) a "p.m." (vecer) a casovy - udaj se prislusne upravi, jinak casovy udaj nesmi byt ukoncen pismenem - ani cislem - povolene jsou vsechny oddelovace (',', '.', ';', ':', atd.) - vcetne znaku white-space a konce radku, ukazovatko se posune za konec - casoveho udaje, funkce je uspesna jen pokud je casovy udaj platny - (0-23, 0-59, 0-59 a 0-999), - -- year_or_time(, ) - (typy hodnot ve sloupcich - sloupec_datum a sloupec_cas musi byt datum a cas) - ziska rok a pripadne - i cas (pokud je na pozici ukazovatka rok, cas neni znamy, je-li na pozici - ukazovatka cas, je rok urcen podle pravidla, ze cely datum by mel byt - stary mene nez sest mesicu od dnesniho datumu) a obohati hodnoty - ve sloupcich o rok a pripadne i o hodiny a minuty, rok je ulozeny jako - dekadicke cislo, cas je ulozen jako dve dekadicka cisla (hodiny a minuty) - oddelena dvojteckou, cisla nesmi byt ukoncena pismenem - povolene jsou - vsechny oddelovace (',', '.', ';', ':', atd.) vcetne znaku white-space - a konce radku, ukazovatko se posune za konec roku nebo casu, funkce je - uspesna jen pokud jsou cisla platna (1602-9999 a 0-23:0-59), - -- all(cislo) - ukazovatko se posune o 'cislo' znaku, funkce je uspesna, - pokud lze ukazovatko posunout, - -- all(, cislo) - (typ hodnot ve sloupci musi byt retezec) - priradi - do sloupce retezec o delce 'cislo', ktery zacina od ukazovatka, ukazovatko - se posune na konec tohoto retezce, funkce je uspesna, pokud lze retezec - ziskat, - -- all_to(retezec) - nastavi ukazovatko za prvni nasledujici vyskyt - retezce 'retezec' (porovnava se case insensitive), - funkce je uspesna jen pokud je retezec nalezen, - -- all_to(, retezec) - (typ hodnot ve sloupci musi byt - retezec) - priradi do sloupce retezec, ktery saha od ukazovatka az za - prvni nasledujici vyskyt retezce 'retezec' (porovnava se case - insensitive), ukazovatko se posune za konec nalezeneho retezce, - funkce je uspesna, pokud je retezec nalezen, - -- all_up_to(, retezec) - (typ hodnot ve sloupci musi byt - retezec) - priradi do sloupce retezec, ktery saha od ukazovatka az do - prvniho nasledujiciho vyskytu retezce 'retezec' (porovnava se case - insensitive), ukazovatko se posune za konec nalezeneho - retezce, funkce je uspesna, pokud je retezec nalezen, - -- unix_link(, , ) - (typy sloupcu - sloupec_name a sloupec_link musi byt "Name" a "Any Text") - zpracuje - retezec, ktery saha od ukazovatka az do konce radky, ukazovatko se - posune na konec radky, ocekava format "link_name -> target_name" - nebo jen "link_name" (je-li odepreny pristup k cili linku), - ziska jmeno linku a pripadne i cil linku a provede detekci jestli - jde o soubor nebo o adresar (heuristika: pokud jmeno nebo pripadne - cil maji priponu, jde pravdepodobne o soubor, jinak o adresar; - pokud tato heuristika nevyhovuje, staci napr. za funkci unix_link - pridat funkci "assign(,false)"), ziskane hodnoty priradi - do sloupcu sloupec_name, sloupec_link (jen pokud se podaril cil - linku ziskat) a is_dir, funkce je uspesna, pokud zpracovavany - retezec odpovida formatu a nezacina na znak white-space, - -- unix_device() - (typ hodnot ve sloupci musi byt retezec) - - priradi do sloupce retezec zacinajici u ukazovatka, ktery je slozeny - ze dvou dekadickych cisel oddelenych carkou a nekolika mezerami - (napr. "27, 26"), ukazovatko posune za tento retezec, funkce je uspesna, - pokud se podari tento retezec ziskat a pokud nekonci pismenem (povolene - jsou vsechny oddelovace (',', '.', ';', ':', atd.) vcetne znaku - white-space a konce radku), - -- if(vyraz) - (typ vysledne hodnoty vyrazu musi byt boolean) - funkce - je uspesna jen pokud je vyraz true, - -- assign(, vyraz) - (typ vysledne hodnoty vyrazu musi odpovidat - typu hodnot sloupce) - priradi hodnotu vyrazu do sloupce, - -- add_string_to_column(, vyraz) - (typ hodnot ve sloupci a typ - vysledne hodnoty vyrazu musi byt retezec) - prida retezec ziskany jako - hodnota vyrazu do sloupce, - -- cut_white_spaces_end() - (typ hodnot ve sloupci musi byt - retezec) - orizne znaky white_space na konci retezce ve sloupci - a tento novy retezec priradi do sloupce, - -- cut_white_spaces_start() - (typ hodnot ve sloupci musi byt - retezec) - orizne znaky white_space na zacatku retezce ve sloupci - a tento novy retezec priradi do sloupce, - -- cut_white_spaces() - (typ hodnot ve sloupci musi byt - retezec) - orizne znaky white_space na zacatku a konci retezce ve - sloupci a tento novy retezec priradi do sloupce, - -- back(cislo) - posune ukazovatko zpet o 'cislo' znaku, funkce je - uspesna pokud je posun mozny. - -- cut_end_of_string(, cislo) - (typ hodnot ve sloupci musi byt - retezec) - orizne retezec ve sloupci o 'cislo' znaku a tento zkraceny - retezec priradi do sloupce, funkce je uspesna, pokud lze retezec zkratit - (pokud ma aspon 'cislo' znaku) - - -Seznam stavovych promennych: -============================ - -- first_nonempty_line - (boolean) - true pokud je ukazovatko na - prvni neprazdne (obsahujici jine znaky nez white-spaces) radce, -- last_nonempty_line - (boolean) - true pokud je ukazovatko na - posledni neprazdne (obsahujici jine znaky nez white-spaces) radce, - nebere se v uvahu jestli text listingu je nebo neni nekompletni, -- next_char - (retezec) - retezec obsahujici jeden znak z pozice - ukazovatka, je-li ukazovatko na konci textu listingu, jde o prazdny - retezec, -- next_word - (retezec) - retezec zacinajici na pozici ukazovatka a - ukonceny znakem white-space nebo koncem radky, -- rest_of_line - (retezec) - retezec zacinajici na pozici ukazovatka a - ukonceny koncem radky, - - -Seznam operacnich znaku: +Constants may be string, number, or boolean. + +A string is delimited by the '"' character. A string may not extend +past the end of the line. Escape sequences use the '\' character: for +'"', it is "\""; for '\', it is "\\"; for a tab character, it is +"\t"; for the line-ending characters CR+LF, it is the pair "\r" and +"\n". Unknown escape sequences are reported as errors. + +A number is written in decimal form without any separators. A negative +number starts with '-'. A positive number starts with '+' (which may be +omitted). + +A boolean is "true" or "false" (written without quotes). + +The user defines columns. Each column has an identifier name, a value +type, an empty value, and a name and description for display in the +panel. The identifier is used when assigning values to columns. Each +item may have exactly one value assigned in a column. If no value is +assigned, the user-defined empty value is used in that column. Columns +also define whether they should be displayed in the panel. Display +cannot be turned off for columns of type "Name" and "Extension". + +A column identifier starts with '<', contains the user-defined +identifier name, and ends with '>'. + +The following column types exist: +- Name - (string) exactly one column of this type is required, it + cannot be hidden, defining an empty value for it makes no sense, and + the parser must assign to it for every file and directory. If no + assignment happens, parsing according to the current rule produces no + file or directory - this is used to skip empty lines and other + unimportant parts of the listing. Assigning the empty string to this + column is considered a parsing error, +- Extension - generated from the value in the "Name" column, cannot be + hidden, defining an empty value for it makes no sense, +- Size - (number - unsigned int64), for directories the value is + always 0 and "DIR" is displayed in the panel; the default empty value + is 0, +- Date - (date) the date must be valid (otherwise it is replaced with + 1.1.1602); the default empty value is 1.1.1602, +- Time - (time) the default empty value is 0:00:00, +- Type - generated from the value in the "Name" column; defining an + empty value for it makes no sense, +- Any Text - (string) the default empty value is "", +- Any Date - (date) the date must be valid (otherwise it is replaced + with 1.1.1602); the default empty value is "", +- Any Time - (time) the default empty value is "", +- Any Number - (number - signed int64) the default empty value is "". + +In addition, there are three columns with identifiers "", +"", and "". Boolean values are assigned to all +three, and they tell whether the item is a "file" or a "directory", +whether it "is hidden" or "is not hidden", and whether it "is a link" +or "is not a link". Assignment to these columns is not required; their +empty values are "file", "is not hidden", and "is not a link". + + +Description of the autodetection condition format: +================================================== + +This is a logical expression. The operators in the expression are +(from highest priority): NOT, AND, and OR. NOT (logical negation) is +unary; AND (logical conjunction) and OR (logical disjunction) are +binary. Parentheses may also be used in the expression (to define +subexpressions). The following functions are used as operands: + +- syst_contains(string) - evaluates to TRUE if the reply to the SYST + command (get type of operating system) contains the given string, + +- welcome_contains(string) - evaluates to TRUE if the given string + appears in the server's first reply (immediately after the connection + is established), + +- reg_exp_in_syst(regular_expression_string) - evaluates to TRUE if the + reply to the SYST command (get type of operating system) contains a + string matching the given regular expression, + +- reg_exp_in_welcome(regular_expression_string) - evaluates to TRUE if + the server's first reply (immediately after the connection is + established) contains a string matching the given regular expression. + + +Obtaining a listing for a fixed server type: +============================================ + +Parsing of the listing text is started. If parsing succeeds, the +obtained results are used and the algorithm terminates. If parsing +fails, the listing text is displayed in the panel without +modifications. + +Before the listing is placed into the panel, the "." directory is +removed (if it is present in the parsing results), and for the root +path the ".." directory is removed as well (if it is present in the +parsing results). If the ".." directory remains in the listing, it is +always visible (the value in the "" column is ignored). + + +Description of server type autodetection: +========================================= + +All defined server types are processed one by one. For each server +type, the "autodetect condition" is evaluated. If the condition is not +satisfied, processing continues with the next server type. If the +condition is satisfied, parsing of the listing text is started. If +parsing succeeds, the obtained results are used and the algorithm +terminates. If a parsing error occurs, processing continues with the +next server type. + +If all server types are processed this way without success, the +algorithm continues by processing those server types whose +"autodetect condition" was not satisfied. For those types, parsing of +the listing text is started. As in the previous case, the algorithm +terminates as soon as parsing succeeds without an error. + +If none of the parsers from the defined server types succeeds in +parsing the listing text, the listing text is displayed in the panel +without modifications. + +Autodetection works this way only for the listing of the first path on +the server. For later listings from the same server, the algorithm +first tries to reuse the same server type that was used for the +previous listing (so that, for example, empty listings still have the +"correct" columns in the panel, and so on). Only if parsing with that +server type fails is the server type autodetection process started +again. + +Before the listing is placed into the panel, the "." directory is +removed (if it is present in the parsing results), and for the root +path the ".." directory is removed as well (if it is present in the +parsing results). If the ".." directory remains in the listing, it is +always visible (the value in the "" column is ignored). + + +Description of the parsing process: +=================================== + +A parser is considered successful when the entire listing text can be +processed using the defined rules. + +For the description of the algorithm, we introduce the term "pointer", +which denotes a position within the listing text. + +Rules consist of functions. A rule may be used only if all of its +functions evaluate as successful, an empty string was not assigned to +the "Name" column (that is, either a non-empty string was assigned or +no assignment happened at all), and the pointer ends at the end of +some line of the listing text. After a rule is used, the pointer is +automatically moved to the beginning of the next line of the listing +text. + +In addition to reporting success and moving the pointer, a function may +also assign a value to a column or modify that value. + +A parser may define an entire sequence of rules. The rule to be used at +any given moment is always selected in the order in which the rules +were defined. In other words, the first usable rule is always used. + +The listing text may be incomplete because loading was interrupted, +either at the user's request or because of a server connection error. +Incomplete listing text is adjusted so that it contains only complete +lines of text (the remainder is cut off). + +Parsing of incomplete listing texts is handled at the rule-application +level. In the simpler case, the pointer reaches the end of the text +after a rule is used and parsing ends there. In the more complex case, +a function evaluated while using a rule is supposed to move the pointer +to the next line. That move is impossible only because the listing text +is incomplete, and parsing therefore ends successfully (as if the +listing text ended in such a way that the currently used rule was not +needed at all). + + +Displaying the total size of selected files in the info line: +============================================================= + +In order for the total size in bytes or blocks to be displayed in the +info line when a group of files is selected, the file size must be +stored in a column of type "File Size in Bytes" or in a column of type +"Any Number" with the standard name "Blocks" or "BlkSz". + + +List of functions: +================== + +Unless stated otherwise, a function always succeeds, does not move the +pointer, and does not assign a value to any column. If a function moves +the pointer, then unless stated otherwise it cannot skip the end of the +line. + +Before a column identifier may be used in an expression, a value must +be assigned to that column. Without such an assignment, the expression +has no meaning (such an expression can be replaced with a boolean +constant computed by substituting the empty value of the given column +into the expression). + +(white-space: space or tab) + +- skip_white_spaces() - skips all white-space characters using the + pointer, + +- skip_to_number() - moves the pointer to the nearest decimal digit, + +- white_spaces() - skips all white-space characters using the pointer; + the function succeeds only if the pointer moves, + +- white_spaces(number) - skips a sequence of white-space characters of + length 'number' using the pointer; the function succeeds only if such + a sequence exists, + +- white_spaces_and_line_ends() - skips all white-space characters and + line-ending characters using the pointer; the function succeeds only + if the pointer moves and does not end at the end of the listing + (it stops on some character), + +- rest_of_line() - moves the pointer to the end of the line; the + function succeeds only if the pointer moves, + +- rest_of_line() - (the value type of the column must be + string) - assigns to the column the string from the pointer position + to the end of the line, moves the pointer to the end of the line, and + succeeds if the pointer moves, + +- word() - skips all characters except white-space and end-of-line + characters using the pointer; the function succeeds only if the + pointer moves, + +- word() - (the value type of the column must be string) - + assigns to the column the string from the pointer position up to the + first white-space character or the end of the line, moves the pointer + past the end of that string, and succeeds if such a string can be + obtained (it contains at least one character), + +- number() - (the value type of the column must be number) - + assigns to the column the decimal number located at the pointer + position. This number must not be followed by a letter - all + separators are allowed (',', '.', ';', ':', and so on), including + white-space and end-of-line characters. The pointer is moved past the + end of the number. The function succeeds if the number exists, is + terminated correctly, and, for a column of type "Size", the number is + also non-negative, + +- positive_number() - (the value type of the column must be + number) - assigns to the column the positive decimal number located + at the pointer position. If the number is negative, the column + receives its default empty value (zero for type Size, "" for type Any + Number). The number must not be followed by a letter - all separators + are allowed (',', '.', ';', ':', and so on), including white-space + and end-of-line characters. The pointer is moved past the end of the + number. The function succeeds if the number exists and is terminated + correctly, + +- number_with_separators(, string) - (the value type of the + column must be number) - assigns to the column the decimal number + with digit group separators located at the pointer position (used to + make large numbers easier to read; the allowed separators are given + in the string 'string'; any characters except '+', '-', and digits + are allowed). The number must not be followed by a letter - all + separators are allowed (',', '.', ';', ':', and so on), including + white-space and end-of-line characters. The pointer is moved past the + end of the number. The function succeeds if the number exists, is + terminated correctly, and, for a column of type "Size", the number is + also non-negative, + +- month_3() - (the value type of the column must be date) - + enriches the value in the column with a month recognized as a + three-letter token at the pointer position. It works with month names + in multiple languages (currently at least English and German). The + month must not be followed by a letter - all separators are allowed + (',', '.', ';', ':', and so on), including white-space and + end-of-line characters. The pointer is moved past those three + letters. The function succeeds only if the month was recognized and + all months in the listing belong to a single language, + +- month_3(, string) - (the value type of the column must be + date) - enriches the value in the column with a month recognized as a + three-letter token at the pointer position. The month names are given + in the string, which must contain twelve three-letter month names + separated by spaces (for example "jan feb mar apr may jun jul aug sep + oct nov dec" for English). The month must not be followed by a + letter - all separators are allowed (',', '.', ';', ':', and so on), + including white-space and end-of-line characters. The pointer is + moved past those three letters. The function succeeds only if the + month was recognized, + +- month_txt() - (the value type of the column must be date) - + enriches the value in the column with a month recognized at the + pointer position. It works with month names in multiple languages + (currently only German). The month must not be followed by a letter - + all separators are allowed (',', '.', ';', ':', and so on), + including white-space and end-of-line characters. The pointer is + moved past the month name. The function succeeds only if the month + was recognized and all months in the listing belong to a single + language, + +- month_txt(, string) - (the value type of the column must be + date) - enriches the value in the column with a month recognized at + the pointer position. The month names are given in the string, which + must contain twelve month names separated by spaces (for example + "Jan. Feb. Maerz Apr. Mai Juni Juli Aug. Sept. Okt. Nov. Dez." for + German). The month must not be followed by a letter - all separators + are allowed (',', '.', ';', ':', and so on), including white-space + and end-of-line characters. The pointer is moved past the month name. + The function succeeds only if the month was recognized, + +- month() - (the value type of the column must be date) - + enriches the value in the column with the month stored as a decimal + number at the pointer position. The number must not be followed by a + letter - all separators are allowed (',', '.', ';', ':', and so on), + including white-space and end-of-line characters. The pointer is + moved past the end of the month number. The function succeeds only if + the month number is valid (1 through 12), + +- day() - (the value type of the column must be date) - + enriches the value in the column with the day stored as a decimal + number at the pointer position. The number must not be followed by a + letter - all separators are allowed (',', '.', ';', ':', and so on), + including white-space and end-of-line characters. The pointer is + moved past the end of the day number. The function succeeds only if + the day number is valid (1 through 31), + +- year() - (the value type of the column must be date) - + enriches the value in the column with the year stored as a decimal + number at the pointer position. The number must not be followed by a + letter - all separators are allowed (',', '.', ';', ':', and so on), + including white-space and end-of-line characters. The pointer is + moved past the end of the year number. The function succeeds only if + the year number is valid (0-999 (0-79 => +2000, 80-999 => +1900) or + 1602-9999), + +- time() - (the value type of the column must be time) - + enriches the value in the column with hours, minutes, seconds, and + optionally milliseconds found as decimal numbers separated from each + other at the pointer position. The expected formats are 00:00, + 00:00:00, or 00:00:00.000. If the string "a"/"am" or "p"/"pm" + follows immediately after the last digit of the time value, it is + treated as "a.m." (morning) or "p.m." (evening) and the time value is + adjusted accordingly. Otherwise, the time value must not be followed + by a letter or a digit - all separators are allowed (',', '.', ';', + ':', and so on), including white-space and end-of-line characters. + The pointer is moved past the end of the time value. The function + succeeds only if the time value is valid (0-23, 0-59, 0-59, and + 0-999), + +- year_or_time(, ) - (the value types of + date_column and time_column must be date and time) - obtains a year + and optionally also a time. If there is a year at the pointer + position, the time is unknown. If there is a time at the pointer + position, the year is determined using the rule that the full date + should be less than six months old relative to the current date. The + function enriches the column values with the year and optionally with + hours and minutes. The year is stored as a decimal number; the time + is stored as two decimal numbers (hours and minutes) separated by a + colon. The numbers must not be followed by a letter - all separators + are allowed (',', '.', ';', ':', and so on), including white-space + and end-of-line characters. The pointer is moved past the end of the + year or time. The function succeeds only if the numbers are valid + (1602-9999 and 0-23:0-59), + +- all(number) - moves the pointer by 'number' characters; the function + succeeds if the pointer can be moved, + +- all(, number) - (the value type of the column must be + string) - assigns to the column a string of length 'number' starting + at the pointer position, moves the pointer to the end of that string, + and succeeds if the string can be obtained, + +- all_to(string) - moves the pointer behind the first following + occurrence of the string 'string' (case-insensitive comparison); the + function succeeds only if the string is found, + +- all_to(, string) - (the value type of the column must be + string) - assigns to the column the string from the pointer position + up to and including the first following occurrence of the string + 'string' (case-insensitive comparison), moves the pointer behind the + end of the found string, and succeeds if the string is found, + +- all_up_to(, string) - (the value type of the column must be + string) - assigns to the column the string from the pointer position + up to the first following occurrence of the string 'string' + (case-insensitive comparison), moves the pointer behind the end of + the found string, and succeeds if the string is found, + +- unix_link(, , ) - (the column + types of name_column and link_column must be "Name" and "Any Text") - + processes the string from the pointer position to the end of the + line, moves the pointer to the end of the line, and expects the + format "link_name -> target_name" or just "link_name" (if access to + the link target is denied). It obtains the link name and optionally + the link target and detects whether it is a file or a directory + (heuristic: if the name or, if available, the target has an + extension, it is probably a file; otherwise it is a directory. If + that heuristic is not suitable, it is enough to append, for example, + the function "assign(,false)" after unix_link). The obtained + values are assigned to the columns name_column, link_column (only if + the link target was obtained), and is_dir. The function succeeds if + the processed string matches the format and does not start with a + white-space character, + +- unix_device() - (the value type of the column must be + string) - assigns to the column a string starting at the pointer + position and consisting of two decimal numbers separated by a comma + and several spaces (for example "27, 26"), moves the pointer behind + that string, and succeeds if the string can be obtained and does not + end with a letter (all separators are allowed (',', '.', ';', ':', + and so on), including white-space and end-of-line characters), + +- if(expression) - (the result type of the expression must be boolean) + - the function succeeds only if the expression is true, + +- assign(, expression) - (the result type of the expression + must match the value type of the column) - assigns the value of the + expression to the column, + +- add_string_to_column(, expression) - (the value type of the + column and the result type of the expression must be string) - adds + the string obtained as the value of the expression to the column, + +- cut_white_spaces_end() - (the value type of the column must + be string) - trims white-space characters from the end of the string + in the column and assigns the new string back to the column, + +- cut_white_spaces_start() - (the value type of the column must + be string) - trims white-space characters from the start of the + string in the column and assigns the new string back to the column, + +- cut_white_spaces() - (the value type of the column must be + string) - trims white-space characters from the start and end of the + string in the column and assigns the new string back to the column, + +- back(number) - moves the pointer back by 'number' characters; the + function succeeds if the move is possible. + +- cut_end_of_string(, number) - (the value type of the column + must be string) - trims 'number' characters from the end of the + string in the column and assigns the shortened string back to the + column. The function succeeds if the string can be shortened (if it + has at least 'number' characters) + + +List of state variables: ======================== -Pred pouzitim identifikatoru sloupce ve vyrazu je nutne do -sloupce priradit hodnotu. Bez tohoto prirazeni vyraz nema -smysl (takovy vyraz se da nahradit booleanovou konstantou -vypocitanou dosazenim prazdne hodnoty pro dany sloupec do vyrazu). - -- == - rovnost (u retezcu je porovnani case sensitive) -- != - nerovnost (u retezcu je porovnani case sensitive) -- eq - rovnost retezcu (case insensitive) -- not_eq - nerovnost retezcu (case insensitive) -- in - podretezec je v retezci (case insensitive) -- not_in - podretezec neni v retezci (case insensitive) -- end_with - retezec konci na retezec (case insensitive) -- not_end_with - retezec nekonci na retezec (case insensitive) +- first_nonempty_line - (boolean) - true if the pointer is on the first + non-empty line (containing characters other than white-space), +- last_nonempty_line - (boolean) - true if the pointer is on the last + non-empty line (containing characters other than white-space); it + does not matter whether the listing text is complete or incomplete, +- next_char - (string) - a string containing one character from the + pointer position; if the pointer is at the end of the listing text, + it is an empty string, +- next_word - (string) - a string starting at the pointer position and + ending at a white-space character or the end of the line, +- rest_of_line - (string) - a string starting at the pointer position + and ending at the end of the line, + + +List of operator symbols: +========================= + +Before a column identifier may be used in an expression, a value must +be assigned to that column. Without such an assignment, the expression +has no meaning (such an expression can be replaced with a boolean +constant computed by substituting the empty value of the given column +into the expression). + +- == - equality (string comparison is case-sensitive) +- != - inequality (string comparison is case-sensitive) +- eq - string equality (case-insensitive) +- not_eq - string inequality (case-insensitive) +- in - substring is contained in string (case-insensitive) +- not_in - substring is not contained in string (case-insensitive) +- end_with - string ends with string (case-insensitive) +- not_end_with - string does not end with string (case-insensitive) diff --git a/src/plugins/ftp/servers/path_types.txt b/src/plugins/ftp/servers/path_types.txt index bdc065443..f8a442a23 100644 --- a/src/plugins/ftp/servers/path_types.txt +++ b/src/plugins/ftp/servers/path_types.txt @@ -1,23 +1,25 @@ +CommentsTranslationProject: TRANSLATED + UNIX: /pub/d -d - relativni +d - relative / - root VMS: PUB$DEVICE:[PUB.VMS] PUB$DEVICE:[PUB] [PUB.VMS] -PUB$DEVICE:[PUB]FILE.TXT;1 - soubor -[.VMS] - relativni +PUB$DEVICE:[PUB]FILE.TXT;1 - file +[.VMS] - relative [000000] - root PUB$DEVICE:[000000] - root -PUB$DEVICE:[PUB.aa^.bb] - "aa^.bb" je jmeno adresare ("^." je escape-sekvence pro '.') -PUB$DEVICE:[PUB]FI^.LE.TXT;1 - "FI^.LE.TXT;1" je jmeno souboru ("^." je escape-sekvence pro '.') +PUB$DEVICE:[PUB.aa^.bb] - "aa^.bb" is the directory name ("^." is the escape sequence for '.') +PUB$DEVICE:[PUB]FI^.LE.TXT;1 - "FI^.LE.TXT;1" is the file name ("^." is the escape sequence for '.') MVS: 'VEA0016.MAIN.CLIST' 'VEA0016.MAIN.CLIST.' -MAIN.CLIST - relativni +MAIN.CLIST - relative '' - root NOVELL/WINDOWS-NT: @@ -25,24 +27,24 @@ NOVELL/WINDOWS-NT: /PUB/DIR \PUB\DIR\ /PUB/DIR/ -DIR - relativni +DIR - relative / - root \ - root IBM z/VM (CMS): ACADEM:ANONYMOU.PICS -ACADEM:ANONYMOU. - root (pozor: '.' na konci povinna) +ACADEM:ANONYMOU. - root (note: the trailing '.' is required) OS/2: C:/dir1/dir2 -dir2 - relativni +dir2 - relative C:/ - root -(pro sychr pocitame i s backslashem:) +(for safety we also handle backslashes:) C:\dir1\dir2 -dir2 - relativni +dir2 - relative C:\ - root Tandem: \SYSTEM.$VVVVV.SUBVOLUM.FILENAME -SUBVOLUM - relativni -\SYSTEM ('\\' + text do prvni tecky) - root cesty +SUBVOLUM - relative +\SYSTEM ('\\' + text up to the first dot) - path root diff --git a/src/plugins/ftp/servers/proxy_script.txt b/src/plugins/ftp/servers/proxy_script.txt index cd6fc71ed..99bcc3dc6 100644 --- a/src/plugins/ftp/servers/proxy_script.txt +++ b/src/plugins/ftp/servers/proxy_script.txt @@ -1,53 +1,55 @@ -Popis formatu prihlasovaciho skriptu (pro proxy-servery a firewally): -===================================================================== - -Prvni radek skriptu je vzdy "Connect to:" nasledovany dvojici host:port - jde -o hostitele (server) a port kam se mame pripojit. Hostitel musi byt definovany, -neni-li definovany port, predpoklada se 21. - -Vsechny dalsi radky obsahuji prikazy posilane na server po pripojeni (co radek, -to jeden prikaz). Radky muzou obsahovat promenne, ktere se pred poslanim -prikazu nahradi obsahem techto promennych. - -Mame promenne dvou typu, lisi se podle toho co se deje kdyz promenna neni -definovana (zadana uzivatelem) - prvni typ (rikejme mu "nepovinny") vede -k preskoceni celeho radku (neposle se zadny prikaz), druhy (rikejme mu -"povinny") vede k otevreni okna, kam uzivatel musi zadat hodnotu (nebo -prerusit celou prihlasovani sekvenci). Promenne se pisou do zavorek a -predchazi jim znak "$": napr. "$(Password)". "$$" je escape sekvence pro -znak "$". - -Radky zacinajici na "3xx:" se preskakuji pokud byl prikaz z predchoziho radku -preskocen nebo vratil jinou odpoved nez 3xx (3xx="posli dalsi prikaz, jde -o sekvenci prikazu" - zde jde o user+password sekvence). - -Omezeni parametru na prvnim radku skriptu (za "Connect to:"): hostitele je -mozne definovat jen jako text nebo text obsahujici promennou $(ProxyHost) -nebo $(Host), port je mozne definovat jen jako cislo nebo promennou $(ProxyPort) -nebo promennou $(Port). - -Prihlasovaci sekvence se povazuje za uspesnou (uzivatel je prihlasen na FTP -serveru) pokud zadny spousteny prikaz nevrati odpoved 4xx ani 5xx (4xx="docasna -chyba", 5xx="stala chyba") a posledni poslany prikaz vrati odpoved 2xx -(2xx="uspech"). - - -Promenne: -========= - -$(ProxyHost) - povinny - jmena adresa nebo IP proxy-serveru/firewallu -$(ProxyPort) - vzdy definovany (nezada-li ho uzivatel, nastavi se na 21) -$(ProxyUser) - nepovinny - uzivatelske jmeno pro proxy-server/firewall -$(ProxyPassword) - povinny - heslo pro proxy-server/firewall -$(Host) - vzdy definovany - hostitel (FTP server) -$(Port) - vzdy definovany (nezada-li ho uzivatel, nastavi se na 21) -$(User) - povinny - uzivatelske jmeno pro hostitele (FTP server) -$(Password) - povinny - heslo pro hostitele (FTP server) -$(Account) - povinny - ucet pro hostitele (FTP server) - - -Skripty pro zname typy proxy-serveru/firewallu: -=============================================== +CommentsTranslationProject: TRANSLATED + +Description of the login script format (for proxy servers and firewalls): +========================================================================= + +The first line of the script is always "Connect to:" followed by a host:port +pair - this is the host (server) and port we should connect to. The host must +be defined; if the port is not defined, 21 is assumed. + +All following lines contain commands sent to the server after connecting (one +line, one command). The lines may contain variables that are replaced with +their contents before the command is sent. + +There are two types of variables; they differ in what happens when the variable +is not defined (entered by the user) - the first type (let us call it +"optional") causes the entire line to be skipped (no command is sent), while +the second type (let us call it "required") opens a window where the user must +enter a value (or cancel the entire login sequence). Variables are written in +parentheses and are preceded by the "$" character, for example "$(Password)". +"$$" is an escape sequence for the "$" character. + +Lines starting with "3xx:" are skipped if the command on the previous line was +skipped or returned a reply other than 3xx (3xx = "send the next command, this +is a command sequence" - here this is a user+password sequence). + +Restrictions for parameters on the first script line (after "Connect to:"): +the host may be defined only as text or text containing the $(ProxyHost) or +$(Host) variable, and the port may be defined only as a number or the +$(ProxyPort) or $(Port) variable. + +The login sequence is considered successful (the user is logged in to the FTP +server) if no executed command returns a 4xx or 5xx reply (4xx = "temporary +error", 5xx = "permanent error") and the last sent command returns a 2xx reply +(2xx = "success"). + + +Variables: +========== + +$(ProxyHost) - required - domain name or IP address of the proxy server/firewall +$(ProxyPort) - always defined (if the user does not enter it, it is set to 21) +$(ProxyUser) - optional - user name for the proxy server/firewall +$(ProxyPassword) - required - password for the proxy server/firewall +$(Host) - always defined - host (FTP server) +$(Port) - always defined (if the user does not enter it, it is set to 21) +$(User) - required - user name for the host (FTP server) +$(Password) - required - password for the host (FTP server) +$(Account) - required - account for the host (FTP server) + + +Scripts for known proxy server/firewall types: +============================================== "direct connection" Connect to: $(Host):$(Port) diff --git a/src/plugins/ftp/servers/target_path_types.txt b/src/plugins/ftp/servers/target_path_types.txt index efb25dd7b..ea86e7f56 100644 --- a/src/plugins/ftp/servers/target_path_types.txt +++ b/src/plugins/ftp/servers/target_path_types.txt @@ -1,50 +1,50 @@ +CommentsTranslationProject: TRANSLATED + OS/2: NOVELL/WINDOWS-NT: UNIX: -/pub/d/dir ("/pub/d/dir" musi byt cesta a musi existovat) -/pub/d/*.* ("/pub/d" musi byt cesta a musi existovat, "*.*" je maska) -/pub/d/newname ("/pub/d" musi byt cesta a musi existovat, "/pub/d/newname" - neexistuje nebo jde o soubor (v tomto pripade musi byt oznaceny - soubor, u adresare nesmysl), "newname" je - novy nazev jedineho zdrojoveho souboru/adresare) +/pub/d/dir ("/pub/d/dir" must be a path and it must exist) +/pub/d/*.* ("/pub/d" must be a path and it must exist, "*.*" is a mask) +/pub/d/newname ("/pub/d" must be a path and it must exist, "/pub/d/newname" + does not exist or it is a file (in this case a file must be selected; + for a directory this would make no sense), "newname" is + the new name of the single source file/directory) VMS: -PUB$DEVICE:[PUB.VMS] ("PUB$DEVICE:[PUB.VMS]" musi byt cesta a musi existovat) +PUB$DEVICE:[PUB.VMS] ("PUB$DEVICE:[PUB.VMS]" must be a path and it must exist) -oznacene jen soubory: -PUB$DEVICE:[PUB.VMS]*.* ("PUB$DEVICE:[PUB.VMS]" musi byt cesta a musi existovat, "*.*" je maska) +only files selected: +PUB$DEVICE:[PUB.VMS]*.* ("PUB$DEVICE:[PUB.VMS]" must be a path and it must exist, "*.*" is a mask) -oznaceny jeden soubor: -PUB$DEVICE:[PUB.VMS]newname ("PUB$DEVICE:[PUB.VMS]" musi byt cesta a musi existovat, - "PUB$DEVICE:[PUB.VMS]newname" neexistuje nebo jde o soubor, - "newname" je novy nazev jedineho zdrojoveho souboru) +one file selected: +PUB$DEVICE:[PUB.VMS]newname ("PUB$DEVICE:[PUB.VMS]" must be a path and it must exist, + "PUB$DEVICE:[PUB.VMS]newname" does not exist or it is a file, + "newname" is the new name of the single source file) -oznacene jen adresare: -PUB$DEVICE:[PUB.VMS.*] ("PUB$DEVICE:[PUB.VMS]" musi byt cesta a musi existovat, "*" je maska) +only directories selected: +PUB$DEVICE:[PUB.VMS.*] ("PUB$DEVICE:[PUB.VMS]" must be a path and it must exist, "*" is a mask) -oznaceny jeden adresar: -PUB$DEVICE:[PUB.VMS.newname] ("PUB$DEVICE:[PUB.VMS]" musi byt cesta a musi existovat, - "PUB$DEVICE:[PUB.VMS.newname]" neexistuje, - "newname" je novy nazev jedineho zdrojoveho adresare) +one directory selected: +PUB$DEVICE:[PUB.VMS.newname] ("PUB$DEVICE:[PUB.VMS]" must be a path and it must exist, + "PUB$DEVICE:[PUB.VMS.newname]" does not exist, + "newname" is the new name of the single source directory) MVS: -'VEA0016.MAIN.CLIST' ("'VEA0016.MAIN.CLIST'" musi byt cesta a musi existovat) -'VEA0016.MAIN.CLIST.*' ("'VEA0016.MAIN.CLIST'" musi byt cesta a musi existovat, "*" je maska) -'VEA0016.MAIN.CLIST.newname' ("'VEA0016.MAIN.CLIST'" musi byt cesta a musi existovat, - 'VEA0016.MAIN.CLIST.newname' neexistuje nebo je soubor, - (v tomto pripade musi byt oznaceny soubor, u adresare nesmysl), - "newname" je novy nazev jedineho zdrojoveho souboru/adresare) +'VEA0016.MAIN.CLIST' ("'VEA0016.MAIN.CLIST'" must be a path and it must exist) +'VEA0016.MAIN.CLIST.*' ("'VEA0016.MAIN.CLIST'" must be a path and it must exist, "*" is a mask) +'VEA0016.MAIN.CLIST.newname' ("'VEA0016.MAIN.CLIST'" must be a path and it must exist, + 'VEA0016.MAIN.CLIST.newname' does not exist or it is a file, + (in this case a file must be selected; for a directory this would make no sense), + "newname" is the new name of the single source file/directory) IBM z/VM (CMS): -ACADEM:ANONYMOU.PICS ("ACADEM:ANONYMOU.PICS" musi byt cesta a musi existovat) - -oznacene jen soubory: -ACADEM:ANONYMOU.PICS.*.* (maska je formatu: filename '.' filetype; "ACADEM:ANONYMOU.PICS" - musi byt cesta a musi existovat) - -oznacene jen adresare: -ACADEM:ANONYMOU.PICS.* (maska je formatu: dirname; "ACADEM:ANONYMOU.PICS" musi byt cesta - a musi existovat) +ACADEM:ANONYMOU.PICS ("ACADEM:ANONYMOU.PICS" must be a path and it must exist) +only files selected: +ACADEM:ANONYMOU.PICS.*.* (the mask format is: filename '.' filetype; "ACADEM:ANONYMOU.PICS" + must be a path and it must exist) +only directories selected: +ACADEM:ANONYMOU.PICS.* (the mask format is: dirname; "ACADEM:ANONYMOU.PICS" must be a path + and it must exist) diff --git a/src/plugins/ftp/servers/todo.txt b/src/plugins/ftp/servers/todo.txt index fd3736c2e..12cfcbcae 100644 --- a/src/plugins/ftp/servers/todo.txt +++ b/src/plugins/ftp/servers/todo.txt @@ -1,107 +1,149 @@ -- porad narazime na lidi, ktery chteji ukladat bookmarky, ale nechteji ukladat - konfiguraci Salama, aby si neco neopspinili (asi trochu uchylaci) ... resit - (dat tam tlacitko pro ulozeni jen FTP konfigu, jaka jsou rizika??? pri unloadu - pluginu to delame taky) -- download/upload do "filename.part" a az po dokonceni prenosu rename na "filename" - (asi jen na UNIXovych serverech + kde to pujde snadno, u ostatnich nechat jak to je ted) +CommentsTranslationProject: TRANSLATED -- CPluginFSInterface::GetFullFSPath by mel nejspis vracet plnou cestu i pri pastnuti - jmena souboru do panelu (ted se tvrde zkousi zmena cesty, takze musi jit o adresar), - ted kvuli tomu nechodi focus souboru v panelu (pres paste jeho jmena do panelu) -- moznost vybrat casovou zonu serveru (nebo aspon zadat o kolik hodin se vsechno - ma automaticky posouvat) -- moznost vybrat transfer mode pro prave startovanou operaci (copy/move)??? -- komprese behem prenosu - MODE Z - zajem na foru nebyl, ale mohlo by byt celkem trivialni -- umoznit userum konfiguraci poctu pripojeni pro operace: asi zadat pocet pro - kazdy typ operace zvlast a pak kdyz se operace nastartuje, zacit je postupne - pridavat (dokud je server nezacne odmitat) -- Move (F6 key): mohlo by umet aspon hromadne prejmenovani na serveru: oznacim vic souboru, - zadam masku "*.old" a prejmenuje se to posloupnosti RNFR+RNTO -- klavesa Enter by mela v progress dialogu v listview Operations i Connections otevirat - Solve Error dialogy -- automaticke rolovani v listview Operations, aby user videl na operace, ktery se prave - provadeji (ted je nutne rolovat rucne), viz https://forum.altap.cz/viewtopic.php?f=2&t=3433 -- upload/download in lower/UPPER case - omrknout konkurenci -- pri zmene bookmarku v Connect dialogu pridat potvrzeni (lidi si to meni nechtene) -- pri reconnectech zjistovat znovu IP adresu serveru (muze byt dynamicka a zmenit se), - asi by stacilo jednou za 5 minut (otazka je, jestli to neni zbytecna komplikace, DNS - je snad lokalni sluzba, takze asi moc zdrzovat nebude) -- pri kopirovani na FAT32 disk varovat u souboru vetsiho nez 4GB minus 2 byty, ze ho neni mozne - ulozit (viz testy v Salamovi: IDS_FILEISTOOBIGFORFAT32) -- do konfigurace u problemu "if tgt file exists" pridat option "overwrite if src is newer" (chtel Tom - jako nahrazku synchronizace) -- pridat moznost "select server code page": pro konverzi listingu do ANSI (ovsem musime si nechat - i originaly kvuli adresaci souboru na serveru): Kalashnikov Alexander : - During files browsing I see unreadable symbols. Our FTP server supports only DOS code table. -- pridat Paste do kontextoveho menu panelu (salamanderi command) -- moznost specifikovat chovani FTP per connection pro veci jako je treba prepisovani souboru, - adresaru, kolize jmen, atp. Tedy to co je mozne nyni nastavit jen pro cely plugin. - Casto u nekterych FTP porad jen prepisuju (napr. kopirovani zdrojaku na testovaci masinu) - a nechci aby me 100 za den otravoval dialog na prepsani. -- FXP: hodi se hlavne pri presunech/kopirovani dat v ramci jednoho serveru - (zrejme by nemuselo byt az tak slozite: pridat control-connectionu na - druhy server a zadat datovy prenos, datovou connectionu uz oteviraji servery - jen mezi sebou - takze nejsme schopny ukazat ani progres) -- lidi chteji do "disconnect or keep connection?" dialogu pri odchodu z FTP - cesty checkbox "always disconnect" (ted je tam jen "always keep") -- lidi taky nechapou, proc se to pta "disconnect or keep connection?" v situaci, kdy uz - byla connectiona zavrena (by server, due to inactive user): asi v teto situaci zmenit - dotaz na "close or keep FTP path?" a checkboxy asi nabizet take oba + zavest tomuto dotazu - zvlastni polozku v FTP-konfiguraci/Confirmations -- Password Manager: pamet na hesla z bookmark ale i z quick-connectu a spojeni na - zaklade pastnuti URL do panelu -- mel by byt chranitelny heslem + uzamknutelny - (kdyz user odejde od masiny, aby se cizi osoba nedostala k jeho heslum) -- casy na FTP nesedi o hodinu diky zmene casu letni/zimni. Doplnit korekci o cele hodiny? -- SSL ("FTPS is simply ftp with SSL for the control channel" (viz CURL) - (server s SSL je GlobalSCAPE FTP Server - trial ver. viz X:\STORE)) -- udelat auto-focus polozky, kterou zpracovava vyfokusena connectiona - delat - to jen kdyz je user neaktivni (abych mu nescroloval behem toho, co sam neco hleda) -- na FTP bookmarku dopsat Export, ktery vytvori soubor, ktery se da snadno - prenest a na druhe masine Importovat a pridat tak FTP bookmarku. Navic by - to melo by jit udelat pro vic vybranych bookmark najednou -- lidi chteji i pamet na cesty v ramci kazdeho serveru (v ramci bookmarky), - je to naprgany ve FlashFXP -- lidi chteji foldry v bookmarkach (kdyz jich nekdo ma stovky, neni se co divit), - proste silenci ;-) -- keep-alive s data-transfer (NLST+LIST): cas pro poslani dalsiho keep-alive prikazu - by se mel urcovat od posledniho data-transferu a ne od posledni aktivity na serveru -- fronta uloh FTP - svuj thread, load/save, export/import vyberu (zprovoznit checkboxy - v F5/F8/F6/Ctrl+F2 dialozich) -- prejit na bookmarkove cesty: ukladat do historie/hotpath/atd na zaklade udaju o serveru - z bookmark (treba ftp:///bookmarkUID/path) - resilo by pamet hesel+passive mode+list-cmd+... - "bookmarkUID" by se asi generovalo z usera + hosta + portu a delalo by se unikatni - pomoci "(cislo)" - user by si to mohl libovolne zmenit (jen zachovat unikatnost + '/' je - zakazany znak) - +co rozsirit hesla v ceste na scrambleny hesla (ftp://user:scrambledpasswd@server/path)??? -- periodicky update listingu (treba po deseti sekundach - nastavitelne) + user - by mel mit sanci povolit refresh pri aktivaci Salama s FTP v panelu -- nekteri silenci chteji refresh uplne zakazat (nechat to ciste na nich, kdy si - stisknou Ctrl+R) - pisou o pomalem pripojeni a "nedulezitych operacich" typu - prejmenovani (asi vic malych operaci za sebou + prudi je cekat vzdy na refresh) -- dodelat sloupce - razeni (nejen podle viditelnych sloupcu) + sirky u custom - sloupcu + zmenu viditelnosti sloupcu + volba zarovnani vlevo -- podpora pro listingy vznikle prikazem NLST (jen jmena) - problem: jak to udelat, - aby to nevzalo vsechny listingy (rest-of-line bude TRUE pro vsechny listingy) - (asi to natvrdo ohackovat podle prikazu listovani - je-li "NLST", vubec nepouzivat - klasicky vyber parseru, proste to primo vrznout do panelu jako soubory) -- pridavani/update server types: - -jmeno pridavaneho noveho typu serveru nekoliduje -> vlozime ho - -user uz novy typ serveru importoval, ale needitoval ho -> updatneme ho (prip. zmenime prioritu) - -user uz novy typ serveru importoval a editoval ho NEBO user pridal - novy typ a jmenem se trefil do nove importovaneho typu -> dotaz na skip/update/rename_existing_and_insert_new -- raw listing v panelu ma zatim dva sloupce - Name+Listing -> predelat na - jeden sloupec (pridat vlastni razeni podle cisel radku a ne podle abecedy + vypnout - razeni podle jmena v panelu a na sloupci "Name") -- HTTP support - staci stazeni jednoho souboru - vcetne retry je to - neocenitelny - WWW browsery jsou strasny sracky -- operace bez parsnuteho listingu - manual mode - ma to vubec cenu prgat??? +- we keep running into users who want to save bookmarks but do not want to save + the Salamander configuration so they do not mess anything up (a bit + eccentric, apparently) ... address this + (add a button to save only the FTP configuration, what are the risks??? we + already do that when the plugin is unloaded) +- download/upload to "filename.part" and rename to "filename" only after the + transfer finishes + (probably only on UNIX servers + wherever it is easy to support, leave the + current behavior elsewhere) + +- CPluginFSInterface::GetFullFSPath should probably return the full path even + when a file name is pasted into the panel (the code currently tries a hard + path change, so it must be a directory), + which is why focusing a file in the panel does not work now (when its name is + pasted into the panel) +- allow selecting the server time zone (or at least specify by how many hours + everything should be shifted automatically) +- allow selecting the transfer mode for the operation being started right now + (copy/move)??? +- compression during transfer - MODE Z - there was no interest on the forum, + but it could be fairly trivial +- allow users to configure the number of connections for operations: probably + enter a separate count for each operation type and then, when the operation + starts, add them gradually + (until the server starts rejecting them) +- Move (F6 key): it should at least support batch renaming on the server: + select multiple files, enter the mask "*.old", and rename them using an + RNFR+RNTO sequence +- the Enter key should open Solve Error dialogs in the progress dialog listviews + Operations and Connections +- automatic scrolling in the Operations listview so the user can see the + operations currently running + (manual scrolling is required now), see https://forum.altap.cz/viewtopic.php?f=2&t=3433 +- upload/download in lower/UPPER case - check the competition +- when a bookmark is changed in the Connect dialog, add a confirmation + (people change it unintentionally) +- during reconnects, resolve the server IP address again (it may be dynamic and + change), + once every 5 minutes would probably be enough (the question is whether this + is not unnecessary complexity, DNS is probably a local service, so it should + not delay things much) +- when copying to a FAT32 disk, warn for files larger than 4 GB minus 2 bytes + that they cannot be saved + (see Salamander tests: IDS_FILEISTOOBIGFORFAT32) +- in the configuration for the "if tgt file exists" problem, add the option + "overwrite if src is newer" (Tom wanted this as a synchronization substitute) +- add the option "select server code page": for converting listings to ANSI + (but we must also keep the originals for addressing files on the server): + Kalashnikov Alexander : + During files browsing I see unreadable symbols. Our FTP server supports only + DOS code table. +- add Paste to the panel context menu (Salamander command) +- allow specifying per-connection FTP behavior for things such as overwriting + files, directories, name collisions, etc. That is, what can currently be set + only for the whole plugin. + On some FTP servers I keep overwriting everything all the time (for example, + copying sources to a test machine), and I do not want an overwrite dialog to + bother me 100 times a day. +- FXP: mainly useful for moving/copying data within one server + (it probably would not even be that hard: add a control connection to the + second server and start the data transfer, the data connection is then opened + by the servers between themselves only, so we cannot show any progress + anyway) +- people want an "always disconnect" checkbox in the "disconnect or keep + connection?" dialog when leaving an FTP path + (there is only "always keep" there now) +- people also do not understand why it asks "disconnect or keep connection?" in + a situation where the connection has already been closed + (by the server, due to inactive user): in this situation, probably change the + prompt to "close or keep FTP path?" and probably offer both checkboxes here + as well + add a separate item for this prompt in FTP + configuration/Confirmations +- Password Manager: remember passwords from bookmarks as well as from quick + connect and connections established by pasting a URL into the panel -- it + should be protectable by a password + lockable + (so that when the user leaves the machine, another person cannot access + their passwords) +- FTP times are off by one hour due to daylight saving / standard time changes. + Add correction by whole hours? +- SSL ("FTPS is simply ftp with SSL for the control channel" (see CURL) + (a server with SSL is GlobalSCAPE FTP Server - trial version, see X:\STORE)) +- auto-focus the item being processed by the focused connection - do it only + when the user is inactive (so I do not scroll the list while they are looking + for something themselves) +- add Export to an FTP bookmark, creating a file that can be transferred easily + and imported on another machine to add the FTP bookmark there. It should also + be possible to do this for multiple selected bookmarks at once +- people also want path history within each server (within the bookmark), + FlashFXP has it hacked in +- people want folders in bookmarks (when someone has hundreds of them, it is + not hard to see why), + just power users gone wild ;-) +- keep-alive with data transfer (NLST+LIST): the time for sending the next + keep-alive command should be based on the last data transfer, not the last + activity on the server +- FTP job queue - its own thread, load/save, export/import selection + (enable checkboxes in the F5/F8/F6/Ctrl+F2 dialogs) +- switch to bookmark-based paths: store history/hot paths/etc. based on server + information from the bookmark + (for example ftp:///bookmarkUID/path) - it would solve password memory + + passive mode + list command + ... + "bookmarkUID" would probably be generated from user + host + port and made + unique using "(number)" - the user could change it freely + (just keep uniqueness + '/' is a forbidden character) + + what about expanding passwords in the path to scrambled passwords + (ftp://user:scrambledpasswd@server/path)??? +- periodic listing refresh (for example every ten seconds - configurable) + the + user should have a chance to enable refresh when Salamander is activated with + FTP in a panel +- some power users want refresh disabled entirely (leave it entirely up to them + when to press Ctrl+R) - they complain about slow connections and + "unimportant operations" such as renaming + (probably several small operations in a row + they are annoyed by waiting for + refresh every time) +- finish columns - sorting (not only by visible columns) + widths for custom + columns + changing column visibility + left alignment option +- support for listings produced by the NLST command (names only) - problem: how + to do it so it does not catch all listings + (rest-of-line will be TRUE for all listings) + (probably hardwire it according to the listing command - if it is "NLST", do + not use the normal parser selection at all, just put it directly into the + panel as files) +- adding/updating server types: + - the name of the newly added server type does not collide -> insert it + - the user has already imported the new server type, but has not edited it + -> update it (possibly change priority) + - the user has already imported and edited the new server type OR the user + added a new type and happened to hit the same name as the newly imported + type -> prompt for skip/update/rename_existing_and_insert_new +- raw listing in the panel currently has two columns - Name+Listing -> convert + it to a single column + (add custom sorting by line numbers instead of alphabetically + disable + sorting by name in the panel and on the "Name" column) +- HTTP support - downloading a single file is enough - with retry it would be + invaluable - web browsers are terrible +- operations without a parsed listing - manual mode - is it even worth hacking + in??? ------------------------------------------------------------------------ ------------------------------------------------------------------------ ------------------------------------------------------------------------ -CRC ze serveru: XCRC (asi nepodporuje zrovna kazdy server) +CRC from the server: XCRC (probably not supported by every server) Cache entire structure (whole site): "LIST -laR" diff --git a/src/plugins/ftp/sockets.cpp b/src/plugins/ftp/sockets.cpp index 59f2d2c50..3bab7b7a4 100644 --- a/src/plugins/ftp/sockets.cpp +++ b/src/plugins/ftp/sockets.cpp @@ -407,7 +407,7 @@ BOOL CSocket::Connect(DWORD ip, unsigned short port, DWORD* error, BOOL calledFr ShouldPostFD_WRITE = FALSE; BOOL addCalled = FALSE; - if (Msg == -1) // the socket is not in SocketsThread, add it + if (Msg == -1) // the socket is not in SocketsThread; add it { if (!SocketsThread->AddSocket(this)) // we are inside CSocketsThread::CritSect, so this call is possible even from CSocket::SocketCritSect { @@ -426,10 +426,10 @@ BOOL CSocket::Connect(DWORD ip, unsigned short port, DWORD* error, BOOL calledFr Socket = socket(AF_INET, SOCK_STREAM, 0); if (Socket != INVALID_SOCKET) { - // disable the Nagle algorithm, we do not want any unnecessary waiting - // WARNING: when downloading on a local network there were frequent dropouts, the transfer often - // restarted, and I did not notice any speedup, so I decided - // to give this up (this was still at accept()) + // disable the Nagle algorithm to avoid unnecessary waiting + // WARNING: when downloading on a local network, frequent dropouts occurred, the transfer often + // restarted, and no speedup was observed, so this was abandoned + // (this was still in accept()) // BOOL noDelayOn = TRUE; // setsockopt(Socket, IPPROTO_TCP, TCP_NODELAY, (char *)&noDelayOn, sizeof(noDelayOn)); @@ -446,7 +446,7 @@ BOOL CSocket::Connect(DWORD ip, unsigned short port, DWORD* error, BOOL calledFr if (connect(Socket, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR) { DWORD err = WSAGetLastError(); - if (err == WSAEWOULDBLOCK) // normal reaction to connecting a non-blocking socket + if (err == WSAEWOULDBLOCK) // normal response when connecting a non-blocking socket { ret = TRUE; } @@ -456,7 +456,7 @@ BOOL CSocket::Connect(DWORD ip, unsigned short port, DWORD* error, BOOL calledFr *error = WSAGetLastError(); } } - else // returned NO_ERROR, behaves like the blocking variant of "connect", should never happen + else // connect returned NO_ERROR, behaves like the blocking variant of "connect", should never happen { TRACE_E("CSocket::Connect(): connect has returned unexpected value!"); } @@ -797,7 +797,7 @@ BOOL CSocket::GetHostByAddress(const char* address, int hostUID) if (t != NULL) { if (t->Create(SocketsThreadQueue) == NULL) - delete t; // the thread did not start, error + delete t; // thread failed to start, error else maybeOK = TRUE; // the thread is running, the address lookup may succeed } @@ -885,7 +885,7 @@ BOOL CSocket::GetProxyError(char* errBuf, int errBufSize, char* formatBuf, int f CALL_STACK_MESSAGE1("CSocket::GetProxyError(, , ,)"); HANDLES(EnterCriticalSection(&SocketCritSect)); - BOOL ret = FALSE; // FALSE = it is not an error reported by the proxy server (but for example an error connecting to the proxy server) + BOOL ret = FALSE; // FALSE = not an error reported by the proxy server (for example, an error connecting to the proxy server) if (ProxyErrorCode != pecNoError) { ret = TRUE; @@ -1201,7 +1201,7 @@ void CSocket::Socks5SendRequest(int request, int index, BOOL* csLeft, BOOL isCon len = 255; // longer named addresses simply cannot be entered in a SOCKS 5 request buf[4] = (unsigned char)len; memcpy(buf + 5, HostAddress, len); - len++; // for the byte with the address length + len++; // for the address-length byte } else { @@ -1579,7 +1579,7 @@ void CSocket::ReceiveNetEventInt(LPARAM lParam, int index) { // process the first response from the SOCKS5 proxy server if (read == 2) // the response should have 2 bytes (the first byte is the version, but they do not say what it should be set to, so we ignore it) { - if (buf[1] == 0 /* anonymous */) + if (buf[1] == 0 /* no authentication */) { SocketState = ssSocks5_WaitForCon; BOOL csLeft; @@ -1635,7 +1635,7 @@ void CSocket::ReceiveNetEventInt(LPARAM lParam, int index) if (!csLeft) HANDLES(LeaveCriticalSection(&SocketCritSect)); } - else // the server rejected us, we are done + else // the server rejected us, aborting { ProxyErrorCode = pecUserPassAuthFail; SocketState = ssConnectFailed; @@ -1754,7 +1754,7 @@ void CSocket::ReceiveNetEventInt(LPARAM lParam, int index) int read = 2; if (ProxyReceiveBytes(lParam, buf, &read, index, FALSE, TRUE /* listen */, FALSE)) { // process the first response from the SOCKS5 proxy server - if (read == 2) // the response should have 2 bytes (the first byte is the version, but they do not say what it should be set to, so we ignore it) + if (read == 2) // the response should have 2 bytes (the first byte is the version, but its expected value is not specified, so we ignore it) { if (buf[1] == 0 /* anonymous */) { @@ -1813,7 +1813,7 @@ void CSocket::ReceiveNetEventInt(LPARAM lParam, int index) if (!csLeft) HANDLES(LeaveCriticalSection(&SocketCritSect)); } - else // the server rejected us, we are done + else // the server rejected us, terminate { ProxyErrorCode = pecUserPassAuthFail; SocketState = ssListenFailed; @@ -1833,13 +1833,13 @@ void CSocket::ReceiveNetEventInt(LPARAM lParam, int index) break; } - case ssSocks4_WaitForListenRes: // waiting for the proxy to open a port for "listen" and return the IP+port where it listens or an error (timeout should be handled outside - timeout for calling ListeningForConnection()) + case ssSocks4_WaitForListenRes: // waiting for the proxy to open a port for "listen" and return the IP+port where it is listening or an error (timeout should be handled outside - timeout for calling ListeningForConnection()) case ssSocks4A_WaitForListenRes: // waiting for the proxy to open a port for "listen" and return the IP+port where it listens or an error (timeout should be handled outside - timeout for calling ListeningForConnection()) { int read = 8; if (ProxyReceiveBytes(lParam, buf, &read, index, FALSE, TRUE /* listen */, FALSE)) { // process the SOCKS4 proxy server response - if (read == 8 && buf[0] == 0) // the response should have 8 bytes + "version" should be 0 + if (read == 8 && buf[0] == 0) // the response should have 8 bytes and the "version" should be 0 { if (buf[1] == 90) // reply code == success { @@ -1875,12 +1875,12 @@ void CSocket::ReceiveNetEventInt(LPARAM lParam, int index) break; } - case ssSocks5_WaitForListenRes: // waiting for the proxy to open a port for "listen" and return the IP+port where it listens or an error (timeout should be handled outside - timeout for calling ListeningForConnection()) + case ssSocks5_WaitForListenRes: // waiting for the proxy to open a port for "listen" and return the IP+port where it is listening, or return an error (timeout should be handled outside - timeout for calling ListeningForConnection()) { int read = 10; if (ProxyReceiveBytes(lParam, buf, &read, index, FALSE, TRUE /* listen */, FALSE)) { // process the SOCKS5 proxy server response - if (read == 10 && buf[0] == 5 && buf[3] == 1) // the response should have 10 bytes + "version" should be 5 + address type should be 1 (IPv4) + if (read == 10 && buf[0] == 5 && buf[3] == 1) // the response should have 10 bytes, the "version" should be 5, and the address type should be 1 (IPv4) { if (buf[1] == 0) // reply code == success { @@ -1973,12 +1973,12 @@ void CSocket::ReceiveNetEventInt(LPARAM lParam, int index) PostMessage(SocketsThread->GetHiddenWindow(), WM_APP_SOCKET_MIN + index, (WPARAM)Socket, MAKELPARAM(FD_WRITE, NO_ERROR)); } - if (event == FD_CLOSE) // this close occurred after a successful connection from the FTP server, it will be processed later... + if (event == FD_CLOSE) // this close occurred after successfully connecting to the FTP server, it will be processed later... { PostMessage(SocketsThread->GetHiddenWindow(), WM_APP_SOCKET_MIN + index, (WPARAM)Socket, lParam); } - ConnectionAccepted(TRUE, NO_ERROR, FALSE); // announce a successful connection establishment + ConnectionAccepted(TRUE, NO_ERROR, FALSE); // report successful connection establishment HANDLES(LeaveCriticalSection(&SocketCritSect)); } else // error @@ -2152,7 +2152,7 @@ void CSocket::ReceiveNetEventInt(LPARAM lParam, int index) if (!csLeft) HANDLES(LeaveCriticalSection(&SocketCritSect)); } - // else HANDLES(LeaveCriticalSection(&SocketCritSect)); // ProxyReceiveBytes() returns FALSE = the SocketCritSect section has already been left + // else HANDLES(LeaveCriticalSection(&SocketCritSect)); // ProxyReceiveBytes() returns FALSE, so SocketCritSect has already been left break; } @@ -2190,7 +2190,7 @@ void CSocket::ReceiveNetEventInt(LPARAM lParam, int index) void CSocket::ReceiveNetEvent(LPARAM lParam, int index) { CALL_STACK_MESSAGE3("CSocket::ReceiveNetEvent(0x%IX, %d)", lParam, index); - DWORD eventError = WSAGETSELECTERROR(lParam); // extract error code of event + DWORD eventError = WSAGETSELECTERROR(lParam); // extract the event error code switch (WSAGETSELECTEVENT(lParam)) { case FD_CLOSE: @@ -2230,7 +2230,7 @@ void CSocket::ReceiveNetEvent(LPARAM lParam, int index) { int r = SSLLib.SSL_read(SSLConn, buf, 500); if (r <= 0) - break; // loop until an error or zero (0 = gracefully closed) + break; // loop until an error or zero (0 = graceful close) else { if (OurShutdown) // shutdown was initiated by the client @@ -2268,18 +2268,18 @@ void CSocket::ReceiveNetEvent(LPARAM lParam, int index) TRACE_E("Incorrect call to CSocket::ReceiveNetEvent(FD_ACCEPT): from section SocketCritSect!"); #endif - if (eventError == NO_ERROR) // only accept without error, ignore the rest (the connection is retried until timeout) + if (eventError == NO_ERROR) // accept only error-free events, ignore the rest (the connection is retried until timeout) { - if (Socket != INVALID_SOCKET) // the socket is connected (otherwise ignore it - the user probably aborted) + if (Socket != INVALID_SOCKET) // the socket is still valid (otherwise ignore it - the user probably aborted) { SOCKADDR_IN addr; memset(&addr, 0, sizeof(addr)); int len = sizeof(addr); SOCKET sock = accept(Socket, (SOCKADDR*)&addr, &len); if (sock != INVALID_SOCKET && - // according to the help calling WSAAsyncSelect is not necessary, but supposedly some versions of Windows Sockets - // do not do it automatically, so it must be done - an anomaly occurred: when stepping through sending - // the LIST command it generates FD_XXX twice (the second set arrives after the first FD_CLOSE -> it is undeliverable) + // according to the help, calling WSAAsyncSelect is not necessary, but supposedly some versions of Windows Sockets + // do not do it automatically, so it is necessary - an anomaly occurred: when stepping through sending + // the LIST command, it generates FD_XXX twice (the second set arrives after the first FD_CLOSE -> it cannot be delivered) WSAAsyncSelect(sock, socketsWindow, Msg, FD_READ | FD_WRITE | FD_CLOSE) != SOCKET_ERROR) { closesocket(Socket); // close the "listen" socket, it will no longer be needed - calling CloseSocketEx is undesirable @@ -2356,7 +2356,7 @@ CSocket::GetSocket() void CSocket::SetCertificate(CCertificate* certificate) { HANDLES(EnterCriticalSection(&SocketCritSect)); - CCertificate* old = pCertificate; // ensures AddRef is called via Release (in case pCertificate == certificate) + CCertificate* old = pCertificate; // ensures AddRef is called before Release (in case pCertificate == certificate) pCertificate = certificate; if (pCertificate) pCertificate->AddRef(); @@ -2658,7 +2658,7 @@ void CSocketsThread::ReceiveMsgData() CSocket* s = Sockets[index]; if (s != NULL && s->GetUID() == data->SocketUID) // it is the recipient of the message (it was waiting) s->ReceiveHostByAddressInt(data->IP, data->HostUID, data->Err, index); - else // IP that did not arrive because the socket was cancelled or swapped, + else // This is an IP that did not arrive because the socket was canceled or swapped. { // when sockets are swapped, find the target socket sequentially and deliver the IP int i; for (i = 0; i < Sockets.Count; i++) @@ -2763,7 +2763,7 @@ void CSocketsThread::ReceivePostMessage() CSocket* s = Sockets[index]; if (s != NULL && s->GetUID() == data->SocketUID) // it is the recipient of the message (it was waiting) s->ReceivePostMessage(data->ID, data->Param); - else // a message that did not arrive because the socket was cancelled or swapped, + else // this is a message that did not arrive because the socket was cancelled or swapped { // when sockets are swapped, find the target socket sequentially and deliver the message int i; for (i = 0; i < Sockets.Count; i++) @@ -2814,7 +2814,7 @@ int CSocketsThread::FindIndexForNewTimer(DWORD timeoutAbs, int leftIndex) if (actTimeoutAbs == timeoutAbs) { while (++m < Timers.Count && Timers[m]->TimeoutAbs - timeoutAbsBase == timeoutAbs) - ; // return the index after the last identical timer + ; // return the index after the last timer with the same timeout return m; // found } else if (actTimeoutAbs > timeoutAbs) @@ -2845,7 +2845,7 @@ BOOL CSocketsThread::AddTimer(int socketMsg, int socketUID, DWORD timeoutAbs, DW Timers.Insert(i, data); if (Timers.IsGood()) { - if (i == 0 && !Terminating) // inserting the timer with the shortest time into the timeout + if (i == 0 && !Terminating) // inserting the timer with the shortest time to timeout { DWORD ti = timeoutAbs - GetTickCount(); if ((int)ti > 0) // if the new timer has not yet expired (the time difference can also be negative), adjust or start the Windows timer @@ -2930,12 +2930,12 @@ void CSocketsThread::ReceiveTimer() HANDLES(EnterCriticalSection(&CritSect)); // guard against recursive calls to ReceiveTimer() - there is no point posting WM_TIMER until the first run completes - // processing the first call to ReceiveTimer(), a new timer will be started or WM_TIMER posted + // after processing the first call to ReceiveTimer(), a new timer will be started or WM_TIMER posted if (LockedTimers == -1) { DWORD ti = GetTickCount(); int last = FindIndexForNewTimer(ti, 0); - if (last > 0) // if any timer timeout occurred + if (last > 0) // if any timer has timed out { LockedTimers = last; // protect the timers being processed from deletion and array shifting int i; @@ -2948,7 +2948,7 @@ void CSocketsThread::ReceiveTimer() CSocket* s = Sockets[index]; if (s != NULL && s->GetUID() == timer->SocketUID) // it is the recipient of the message (it was waiting) s->ReceiveTimer(timer->ID, timer->Param); - else // a timer that did not arrive because the socket was cancelled or swapped, + else // This is a timer that did not arrive because the socket was canceled or swapped. { // when sockets are swapped, find the target socket sequentially and deliver the timer int j; for (j = 0; j < Sockets.Count; j++) @@ -3042,8 +3042,8 @@ CSocketsThread::WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) // SLOW_CALL_STACK_MESSAGE5("CSocketsThread::WindowProc(0x%X, 0x%X, 0x%X, 0x%X)", hwnd, uMsg, wParam, lParam); if (GetTickCount() - LastWM_TIMER_Processing >= 500 && uMsg != WM_TIMER) - { // if 1000 ms passed since the last WM_TIMER, insert it for processing manually, because most likely - // the thread simply is not "idle", and therefore the system does not send WM_TIMER (it is unfortunately a low-priority message) + { // if 1000 ms has passed since the last WM_TIMER, insert one for processing manually, because most likely + // the thread simply is not "idle", so the system does not send WM_TIMER (unfortunately, it is a low-priority message) LastWM_TIMER_Processing = GetTickCount(); // store when WM_TIMER was last processed if (SocketsThread != NULL) SocketsThread->ReceiveTimer(); diff --git a/src/plugins/ftp/sockets.h b/src/plugins/ftp/sockets.h index 243338799..4abef896f 100644 --- a/src/plugins/ftp/sockets.h +++ b/src/plugins/ftp/sockets.h @@ -33,8 +33,8 @@ extern WSADATA WinSocketsData; // info about the implementation of Windows Socke // GLOBAL FUNCTIONS // **************************************************************************** -// initialization of the sockets module; 'parent' is the parent of the message box, -// returns TRUE if initialization is successful +// initializes the sockets module; 'parent' is the parent window for message boxes, +// returns TRUE if initialization succeeds BOOL InitSockets(HWND parent); // release the sockets module void ReleaseSockets(); @@ -44,7 +44,7 @@ void ReleaseSockets(); void DeleteSocket(class CSocket* socket); #ifdef _DEBUG -extern BOOL InDeleteSocket; // TRUE if we are inside ::DeleteSocket (to test direct calls of "delete socket") +extern BOOL InDeleteSocket; // TRUE if we are inside ::DeleteSocket (to detect direct calls to "delete socket") #endif // @@ -132,15 +132,15 @@ class CSocket SOCKET Socket; // encapsulated Windows Sockets socket; if INVALID_SOCKET, the socket is not open SSL* SSLConn; // SSL connection, use instead of Socket if non-NULL int ReuseSSLSession; // reuse the SSL session of this control connection for all its data connections: 0 = try, 1 = yes, 2 = no - BOOL ReuseSSLSessionFailed; // TRUE = reusing the SSL session for the last data connection opened failed: if we cannot do without it, we have to reconnect this control connection + BOOL ReuseSSLSessionFailed; // TRUE = reusing the SSL session for the most recently opened data connection failed: if SSL session reuse is required, this control connection must be reconnected CCertificate* pCertificate; // non-NULL on FTPS connections BOOL OurShutdown; // TRUE if this side (the FTP client) initiated the shutdown - BOOL IsDataConnection; // TRUE = socket for data transfer, set larger buffers (speed up listing, downloads and uploads) + BOOL IsDataConnection; // TRUE = data transfer socket; larger buffers are used (to speed up listing, downloads, and uploads) CSocketState SocketState; // socket state // data for connecting through proxy servers (firewalls) - char* HostAddress; // name address of the target machine we want to connect to + char* HostAddress; // host name of the target machine we want to connect to DWORD HostIP; // IP address of 'HostAddress' (==INADDR_NONE until the IP is known) unsigned short HostPort; // port of the target machine we want to connect to char* ProxyUser; // username for the proxy server @@ -201,8 +201,8 @@ class CSocket // callable from any thread void SwapSockets(CSocket* sock); - // returns TRUE if CSocketsThread::IsSocketConnected() has been called for this socket - - // returns the call time in 'lastCallTime'; returns FALSE if CSocketsThread::IsSocketConnected() + // returns TRUE if CSocketsThread::IsSocketConnected() has been called for this socket; + // the call time is returned in 'lastCallTime'; returns FALSE if CSocketsThread::IsSocketConnected() // has not been called yet BOOL GetIsSocketConnectedLastCallTime(DWORD* lastCallTime); @@ -214,27 +214,27 @@ class CSocket // receives the results in the "sockets" thread - the "receive" methods of this object are called there) // ****************************************************************************************** - // obtains an IP address from a host name (or even the textual IP address itself); 'hostUID' is used + // obtains an IP address from a host name (or even directly from a textual IP address); 'hostUID' is used // to identify the result when this method is called multiple times; the result (including 'hostUID') - // will be in the parameters of the ReceiveHostByAddress method called in the "sockets" thread; + // will be passed in the parameters of a call to the ReceiveHostByAddress method in the "sockets" thread; // returns TRUE if there is a chance of success (if the thread retrieving the IP address can be started), - // returns FALSE on failure; if it returns TRUE and this object was not connected to - // SocketsThread, it connects it (see the AddSocket method) + // returns FALSE on failure; if it returns TRUE and this object has not been attached to + // SocketsThread, it attaches it (see the AddSocket method) // WARNING: this method cannot be called from the SocketCritSect critical section (the method uses - // SocketsThread); the exception is when we are already inside the CSocketsThread::CritSect critical section + // SocketsThread); the exception is when already inside the CSocketsThread::CritSect critical section // callable from any thread BOOL GetHostByAddress(const char* address, int hostUID = 0); - // connects to a SOCKS 4/4A/5 or HTTP 1.1 (the proxy type is in 'proxyType') proxy server - // 'serverIP' on port 'serverPort' + if it is not one of these proxy servers, it works the same as - // the Connect method; creates a Windows socket and sets it as non-blocking - it sends messages + // connects to the proxy server at 'serverIP':'serverPort' using SOCKS 4/4A/5 or HTTP 1.1 + // (the proxy type is in 'proxyType'); for other proxy server types, it behaves like the + // Connect method; creates a Windows socket and sets it to non-blocking mode - it sends messages // to the SocketsThread object, which, according to the proxy server protocol, performs - // the connection to address 'host' port 'port' with proxy-user-name 'proxyUser' and proxy-password - // 'proxyPassword' (only SOCKS 5 and HTTP 1.1); 'hostIP' (only SOCKS 4) is the IP address of 'host' + // the connection to address 'host' on port 'port' using proxy user name 'proxyUser' and proxy password + // 'proxyPassword' (SOCKS 5 and HTTP 1.1 only); 'hostIP' (SOCKS 4 only) is the IP address of 'host' // (if unknown, use INADDR_NONE); returns TRUE if there is a chance of success (the result of // connecting to 'host' is received by the ReceiveNetEvent method - FD_CONNECT), returns FALSE on failure - // and if the Windows error code is known, returns it in 'error' (if not NULL); if it returns TRUE - // and this object was not connected to SocketsThread, it connects it (see the AddSocket method) + // and, if the Windows error code is known, returns it in 'err' (if not NULL); if it returns TRUE + // and this object has not been attached to SocketsThread, it attaches it (see the AddSocket method) // WARNING: this method cannot be called from the SocketCritSect critical section (the method uses // SocketsThread) // callable from any thread @@ -242,12 +242,12 @@ class CSocket DWORD* err, const char* host, unsigned short port, const char* proxyUser, const char* proxyPassword, DWORD hostIP); - // connects to IP address 'ip' on port 'port'; creates a Windows socket and sets it as non-blocking - - // it sends messages to the SocketsThread object, which based on these messages calls the - // ReceiveNetEvent method of this object; returns TRUE if there is a chance of success - // (the result is received by the ReceiveNetEvent method - FD_CONNECT), returns FALSE on failure - // and if the Windows error code is known, returns it in 'error' (if not NULL); if it returns - // TRUE and this object was not connected to SocketsThread, it connects it (see the AddSocket method); + // connects to IP address 'ip' on port 'port'; creates a Windows socket and sets it to + // non-blocking mode - it sends messages to the SocketsThread object, which invokes this + // object's ReceiveNetEvent method based on those messages; returns TRUE if there is a chance + // of success (the result is received by the ReceiveNetEvent method - FD_CONNECT), returns FALSE + // on failure and, if the Windows error code is known, returns it in 'error' (if not NULL); if it returns + // TRUE and this object has not been attached to SocketsThread, it attaches it (see the AddSocket method); // 'calledFromConnect' is TRUE only when called from one of the ConnectUsingXXX methods; // WARNING: this method cannot be called from the SocketCritSect critical section (the method uses // SocketsThread) @@ -268,16 +268,16 @@ class CSocket // with a length of at least 'bufSize' characters BOOL GetProxyTimeoutDescr(char* buf, int bufSize); - // returns TRUE if the socket is not closed (INVALID_SOCKET) + // returns TRUE if the socket is not closed (i.e. is not INVALID_SOCKET) BOOL IsConnected(); - // initiates a socket shutdown - after successfully sending + confirming the unsent data, - // FD_CLOSE arrives and closes the socket (releases Windows socket resources); after starting - // the shutdown, no data can be written to the socket anymore (if Write does not write the whole buffer - // at once, you must wait for the write to finish - event ccsevWriteDone); - // returns TRUE on success, FALSE on error - if the Windows error code is known, returns it - // in 'error' (if not NULL) - // NOTE: after receiving FD_CLOSE, the SocketWasClosed method is called (information about the socket closure) + // initiates socket shutdown - after all unsent data has been sent and acknowledged, + // FD_CLOSE is received and closes the socket (releasing Windows socket resources); once + // shutdown has started, no more data can be written to the socket (if Write does not write the entire buffer + // at once, it is necessary to wait for the write to complete - ccsevWriteDone event); + // returns TRUE on success, FALSE on error - if the Windows error code is known, returns + // it in 'error' (if not NULL) + // NOTE: after FD_CLOSE is received, the SocketWasClosed method is called (information about socket closure) BOOL Shutdown(DWORD* error); // hard socket closure (only when Shutdown timed out) - calls closesocket (deallocation of @@ -285,45 +285,47 @@ class CSocket // code is known, returns it in 'error' (if not NULL) BOOL CloseSocket(DWORD* error); - // encrypts the socket, returns TRUE on success; if the server certificate cannot be + // encrypts the socket and returns TRUE on success; if the server certificate cannot be // verified and the user has not previously accepted it as trusted: if 'unverifiedCert' - // is NULL, it returns failure and SSLCONERR_UNVERIFIEDCERT in 'sslErrorOccured'; if - // 'unverifiedCert' is not NULL, it returns success and the server certificate in 'unverifiedCert', - // the caller is responsible for releasing it by calling unverifiedCert->Release() and - // returns the reason why the certificate cannot be verified in 'errorBuf' (of size 'errorBufLen', - // if it is 0, 'errorBuf' can be NULL); in 'errorID' (if not NULL) it returns the resource-id - // of the error text or -1 if no error should be displayed; for other errors - // (except an untrusted certificate): it returns NULL in 'unverifiedCert', returns supplementary - // text for the error in 'errorBuf' (of size 'errorBufLen', if it is 0, 'errorBuf' can be NULL) (it is inserted - // into 'errorID' at position %s via sprintf); in 'sslErrorOccured' (if not NULL) it returns the error code (one of SSLCONERR_XXX); - // 'logUID' is the log UID; 'conForReuse' (if not NULL) is the socket whose SSL session should be reused (called - // "SSL session reuse", see for example http://vincent.bernat.im/en/blog/2011-ssl-session-reuse-rfc5077.html - // and it is used from the control connection for all its data connections) + // is NULL, returns failure and SSLCONERR_UNVERIFIEDCERT in 'sslErrorOccured'; if + // 'unverifiedCert' is not NULL, returns success and the server certificate in 'unverifiedCert'; + // the caller is responsible for releasing it by calling unverifiedCert->Release(), and + // the reason why the certificate cannot be verified is returned in 'errorBuf' (of size 'errorBufLen'; + // if it is 0, 'errorBuf' may be NULL); in 'errorID' (if not NULL), returns the resource ID + // of the error text, or -1 if no error should be displayed; for other errors + // (except an untrusted certificate): returns NULL in 'unverifiedCert', and returns additional + // error text in 'errorBuf' (of size 'errorBufLen'; if it is 0, 'errorBuf' may be NULL) + // (inserted into the text identified by 'errorID' at the %s position via sprintf); in 'sslErrorOccured' + // (if not NULL), returns the error code (one of SSLCONERR_XXX); 'logUID' is the log UID; + // 'conForReuse' (if not NULL) is the socket whose SSL session should be reused (this is called + // "SSL session reuse", see e.g. http://vincent.bernat.im/en/blog/2011-ssl-session-reuse-rfc5077.html + // and it is used to reuse the control connection's SSL session for all its data connections) BOOL EncryptSocket(int logUID, int* sslErrorOccured, CCertificate** unverifiedCert, int* errorID, char* errorBuf, int errorBufLen, CSocket* conForReuse); - // connects to a SOCKS 4/4A/5 or HTTP 1.1 (the proxy type is in 'proxyType') proxy server - // 'proxyIP' on port 'proxyPort' and opens a port for "listen" on it; the IP+port where it - // listens is received by the socket in the ListeningForConnection() method; if it is not one of these - // proxy servers, it works like OpenForListening(), except that it also passes the result + // connects to a SOCKS 4/4A/5 or HTTP 1.1 proxy server (the proxy type is in 'proxyType') + // at 'proxyIP':'proxyPort' and opens a "listen" port on it; the socket receives the listening + // IP+port in ListeningForConnection(); if it is not one of these proxy + // servers, it works like OpenForListening(), except that it also passes the result // through ListeningForConnection() - it is called directly from the OpenForListeningWithProxy() method; - // 'listenOnIP'+'listenOnPort' is used only when it is not a connection through these proxy - // servers - 'listenOnIP' is the IP of this machine (when binding the socket on multi-home machines - // the IP may not be detectable, for FTP we take the IP from the "control connection"), 'listenOnPort' is - // the port on which to listen; if it does not matter, value 0 is used; - // it creates a Windows socket and sets it as non-blocking - it sends messages to the - // SocketsThread object, which according to the proxy server protocol requests the opening of a "listen" port - // for connections from address 'host' (IP 'hostIP') port 'hostPort' with proxy-user-name - // 'proxyUser' and proxy-password 'proxyPassword' (only SOCKS 5 and HTTP 1.1); 'hostIP' + // 'listenOnIP'+'listenOnPort' are used only if the connection is not through one of these proxy + // servers - 'listenOnIP' is the IP of this machine (when binding the socket on multihomed machines, + // the IP may not be determinable; for FTP, the IP is taken from the "control connection"), 'listenOnPort' is + // the port on which to listen; if it does not matter, 0 is used; + // creates a Windows socket and sets it to non-blocking mode - sends messages to the + // SocketsThread object, which, according to the proxy server protocol, requests opening a "listen" port + // for a connection from address 'host' (IP 'hostIP') port 'hostPort' with proxy user name + // 'proxyUser' and proxy password 'proxyPassword' (only SOCKS 5 and HTTP 1.1); 'hostIP' // (used only for SOCKS 4, otherwise INADDR_NONE) is the IP address of 'host' (the IP must be - // known - a connection to 'hostIP' must be open, otherwise it is impossible to request this opening of a - // "listen" port); returns TRUE if there is a chance of success (the "listen" IP+port is received by the - // ListeningForConnection() method, and then the result of the connection from 'host' is received by the - // ConnectionAccepted() method - provided that the CSocket::ReceiveNetEvent method is called for FD_ACCEPT); - // returns FALSE on failure and if the Windows error code is known, returns it in 'err' (if not NULL), and - // if 'listenError' is not NULL, returns TRUE/FALSE in it depending on whether it is a LISTEN error (listen error without a proxy server) - // or CONNECT error (error connecting to the proxy server); if it returns TRUE and this object was not connected - // to SocketsThread, it connects it (see the AddSocket method) + // known - a connection to 'hostIP' must already be open, otherwise this opening of a + // "listen" port cannot be requested); returns TRUE if the operation can proceed + // (ListeningForConnection() receives the "listen" IP+port, and then the result of the connection from 'host' + // is received by ConnectionAccepted() - provided that CSocket::ReceiveNetEvent + // is called for FD_ACCEPT); returns FALSE on failure and, if the Windows error code is known, + // returns it in 'err' (if not NULL); if 'listenError' is not NULL, returns TRUE/FALSE in it + // depending on whether it is a LISTEN error (listen error without a proxy server) or a CONNECT error + // (error connecting to the proxy server); if it returns TRUE and this object is not connected + // to SocketsThread, it connects it (see AddSocket) // WARNING: this method cannot be called from the SocketCritSect critical section (the method uses // SocketsThread) // callable from any thread @@ -333,18 +335,20 @@ class CSocket unsigned short proxyPort, const char* proxyUser, const char* proxyPassword, BOOL* listenError, DWORD* err); - // opens a socket and waits for a connection on it (listens); 'listenOnIP' (must not be NULL) is on - // input the IP of this machine (when binding the socket on multi-home machines the IP may not be detectable, - // for FTP we take the IP from the "control connection"), on output it is the IP where the connection is awaited; - // 'listenOnPort' (must not be NULL) is on input the port on which to wait for a connection, - // if it does not matter, value 0 is used; on output it is the port where the connection is awaited; - // it creates a Windows socket and sets it as non-blocking - it sends messages to the - // SocketsThread object, which based on these messages calls the ReceiveNetEvent method of this object - // (the incoming connection is announced by calling the ConnectionAccepted() method - provided that the - // CSocket::ReceiveNetEvent method is called for FD_ACCEPT); returns TRUE when the socket is opened successfully, - // returns FALSE on failure and if the Windows error code is known, returns it in 'error' (if not NULL); - // if it returns TRUE and this object was not connected to SocketsThread, it connects it (see the AddSocket method) - // WARNING: this method cannot be called from the SocketCritSect critical section (the method uses + // opens a socket and listens for connections; 'listenOnIP' (must not be NULL) specifies + // on input the IP address of this machine (when binding the socket on multihomed machines, + // the IP address may not be detectable; for FTP, the IP is taken from the "control connection"), + // and on output receives the IP address on which the socket listens; + // 'listenOnPort' (must not be NULL) specifies on input the port on which to listen for a connection; + // if it does not matter, use value 0; on output it receives the port on which the socket listens; + // creates a Windows socket and sets it to nonblocking mode; messages are sent to the + // SocketsThread object, which invokes this object's ReceiveNetEvent method based on them + // (an incoming connection is reported by calling ConnectionAccepted(), provided that + // CSocket::ReceiveNetEvent is called for FD_ACCEPT); returns TRUE if the socket is opened + // successfully; on failure returns FALSE and, if the Windows error code is known, stores it + // in 'error' (if not NULL); if the method returns TRUE and this object is not connected to + // SocketsThread, it connects it (see the AddSocket method) + // WARNING: this method cannot be called from the SocketCritSect critical section (it uses // SocketsThread) // callable from any thread BOOL OpenForListening(DWORD* listenOnIP, unsigned short* listenOnPort, DWORD* error); @@ -376,7 +380,7 @@ class CSocket // the Windows error code (arrived with FD_CLOSE or occurred during FD_CLOSE processing) virtual void SocketWasClosed(DWORD error) {} - // receives a timer with ID 'id' and parameter 'param' + // receives a timer event with ID 'id' and parameter 'param' virtual void ReceiveTimer(DWORD id, void* param) {} // receives a posted message with ID 'id' and parameter 'param' @@ -420,10 +424,10 @@ class CSocket // WARNING: call only with a single nesting level in the SocketCritSect section void ProxySendBytes(const char* buf, int bufLen, int index, BOOL* csLeft, BOOL isConnect); - // helper methods: 'index' is the socket index in the SocketsThread->Sockets array (used - // when calling ReceiveNetEvent()); inside the method the SocketCritSect critical section may be left, + // helper methods: 'index' is the index of the socket in the SocketsThread->Sockets array (used + // when calling ReceiveNetEvent()); the method may leave the SocketCritSect critical section, // in which case it returns TRUE in 'csLeft' - // WARNING: call only with a single nesting level in the SocketCritSect section + // WARNING: call only with exactly one nesting level in the SocketCritSect critical section // // sends request 'request' (1=CONNECT, 2=LISTEN) to the SOCKS4 proxy server; 'isConnect' is // TRUE/FALSE for CONNECT/LISTEN; 'isSocks4A' is TRUE/FALSE for SOCKS 4A/4 @@ -440,17 +444,17 @@ class CSocket void HTTP11SendRequest(int index, BOOL* csLeft); // helper method: receives a reply from the proxy server; returns TRUE if any data appears on - // the socket (if FD_CLOSE arrived, it returns the data + further FD_CLOSE processing is up to the caller); - // WARNING: if it returns FALSE, it has left the SocketCritSect section; 'buf' - // is the buffer for this response ('read' is on input the size of the 'buf' buffer, on - // output it is the number of bytes read); 'index' is the socket index in the + // the socket (if FD_CLOSE was received, it returns the data, and further FD_CLOSE processing + // is up to the caller); WARNING: if it returns FALSE, it has left the SocketCritSect critical + // section; 'buf' is the buffer for this reply ('read' is the size of 'buf' on input and the + // number of bytes read on output); 'index' is the socket index in the // SocketsThread->Sockets array (used when calling ReceiveNetEvent()); 'isConnect' is - // TRUE/FALSE for CONNECT/LISTEN_or_ACCEPT; 'isListen' only makes sense when - // 'isConnect'==FALSE and is TRUE/FALSE for LISTEN/ACCEPT; if 'readOnlyToEOL' is TRUE, - // the socket is read byte by byte only until the first LF occurs (reads at most + // TRUE for CONNECT and FALSE for LISTEN or ACCEPT; 'isListen' only makes sense when + // 'isConnect'==FALSE and is TRUE for LISTEN and FALSE for ACCEPT; if 'readOnlyToEOL' is TRUE, + // the socket is read one byte at a time only until the first LF is encountered (reads at most // one line including the trailing LF) - // WARNING: call only with a single nesting in the SocketCritSect section and at least one - // nesting in the CSocketsThread::CritSect section + // WARNING: call only with one level of nesting in the SocketCritSect critical section and at + // least one level of nesting in the CSocketsThread::CritSect critical section BOOL ProxyReceiveBytes(LPARAM lParam, char* buf, int* read, int index, BOOL isConnect, BOOL isListen, BOOL readOnlyToEOL); @@ -488,7 +492,7 @@ struct CMsgData // data for WM_APP_SOCKET_ADDR struct CTimerData // data for WM_TIMER (see CSocketsThread::AddTimer()) { - int SocketMsg; // message number used to receive events for the informed socket; if (WM_APP_SOCKET_MIN-1), it is a deleted timer in the locked section of the Timers array + int SocketMsg; // message number used to receive events for the notified socket; if (WM_APP_SOCKET_MIN-1), this is a deleted timer in the locked section of the Timers array int SocketUID; // UID of the informed socket DWORD TimeoutAbs; // absolute time in milliseconds; the timer fires only when GetTickCount() returns at least this value DWORD ID; // timer id @@ -507,7 +511,7 @@ struct CTimerData // data for WM_TIMER (see CSocketsThread::AddTimer()) struct CPostMsgData // data for WM_APP_SOCKET_POSTMSG { int SocketMsg; // message number used to receive events for the informed socket - int SocketUID; // UID of the informed socket + int SocketUID; // UID of the notified socket DWORD ID; // event id void* Param; // event parameter @@ -570,7 +574,7 @@ class CSocketsThread : public CThread // the socket that should be notified of the added timer timeout (see the CSocket::ReceiveTimer() method); // 'id' is the timer ID; 'param' is an optional timer parameter, if it contains any allocated // value, the CSocket object must take care of deallocation when receiving the timer, when adding the timer fails, - // or when unloading the plugin; returns TRUE when the timer is added successfully, otherwise returns FALSE + // or when unloading the plugin; returns TRUE when the timer is added successfully, returns FALSE on failure // (the only error is lack of memory) // callable from any thread BOOL AddTimer(int socketMsg, int socketUID, DWORD timeoutAbs, DWORD id, void* param); @@ -604,8 +608,8 @@ class CSocketsThread : public CThread BOOL AddSocket(CSocket* sock); // deallocates/detaches ('onlyDetach' is FALSE/TRUE) the socket object 'sock' from the array of handled - // objects (writes NULL to the position and sets FirstFreeIndexInSockets); if the object is not in the array - // and 'onlyDetach' is TRUE, it is deallocated + // objects (writes NULL to its slot and sets FirstFreeIndexInSockets); if the object is not in the array + // and 'onlyDetach' is FALSE, it is deallocated // callable from any thread void DeleteSocket(CSocket* sock, BOOL onlyDetach = FALSE) { diff --git a/src/plugins/ftp/ssl.cpp b/src/plugins/ftp/ssl.cpp index f2ea1fe60..35ff88a43 100644 --- a/src/plugins/ftp/ssl.cpp +++ b/src/plugins/ftp/ssl.cpp @@ -430,7 +430,7 @@ void WriteSSLErrorStackToLog(int logUID, const char* errSrc) { // log OpenSSL error stack int err2; - char buffer[256]; // they say: at least 120 bytes + char buffer[256]; // documentation says: at least 120 bytes while ((err2 = SSLLib.ERR_get_error()) != 0) { SSLLib.ERR_error_string(err2, buffer); @@ -471,10 +471,10 @@ BOOL CSocket::EncryptSocket(int logUID, int* sslErrorOccured, CCertificate** unv WSAAsyncSelect(Socket, hWnd, 0, 0); err = ioctlsocket(Socket, FIONBIO, &argp); - // On x64, SOCKET is a 64-bit value, but the OpenSSL folks assume it never exceeds 2^32 + // On x64, SOCKET is a 64-bit value, but the OpenSSL developers assume it never exceeds 2^32 // see http://comments.gmane.org/gmane.comp.encryption.openssl.devel/13621 // http://msdn.microsoft.com/en-us/library/ms724485%28VS.85%29.aspx - // if that happens and this condition starts failing, maybe an x64 version of SSL will already exist + // if that happens and this condition starts failing, perhaps an x64 version of SSL will already exist if (Socket > 0x00000000ffffffff) { DWORD* crash = NULL; @@ -606,7 +606,7 @@ BOOL CSocket::EncryptSocket(int logUID, int* sslErrorOccured, CCertificate** unv Logs.LogMessage(logUID, LoadStr(pCertificate->IsVerified() ? IDS_SSL_LOG_CERTVERIFIED : IDS_SSL_LOG_CERTACCEPTED), -1, TRUE); certAcceptedOrVerified = TRUE; } - else // Huh! The certificate has changed????? + else // The certificate has changed. { Logs.LogMessage(logUID, LoadStr(IDS_SSL_LOG_CERTCHANGED), -1, TRUE); pCertificate->Release(); @@ -626,8 +626,8 @@ BOOL CSocket::EncryptSocket(int logUID, int* sslErrorOccured, CCertificate** unv } if (!certAcceptedOrVerified) { - // The certificate was not verified nor previously accepted by user, so user should accept - // it before further using of this socket. + // The certificate was not verified and had not previously been accepted by the user, so the user should accept + // it before any further use of this socket. if (unverifiedCert != NULL) *unverifiedCert = new CCertificate(DERCert, DERCertLen, PKCS7Cert, PKCS7CertLen, false, HostAddress); else @@ -638,7 +638,7 @@ BOOL CSocket::EncryptSocket(int logUID, int* sslErrorOccured, CCertificate** unv free(PKCS7Cert); free(DERCert); if (sslErrorOccured != NULL) - *sslErrorOccured = SSLCONERR_UNVERIFIEDCERT; // The certificate was not verified nor previously accepted by user. + *sslErrorOccured = SSLCONERR_UNVERIFIEDCERT; // The certificate was not verified and was not previously accepted by the user. return FALSE; } } @@ -648,7 +648,7 @@ BOOL CSocket::EncryptSocket(int logUID, int* sslErrorOccured, CCertificate** unv WSAAsyncSelect(Socket, hWnd, Msg, FD_READ | FD_CLOSE | FD_WRITE); SSLConn = Conn; if (sslErrorOccured != NULL) - *sslErrorOccured = SSLCONERR_NOERROR; // But the certificate must not be verified nor previously accepted by user. + *sslErrorOccured = SSLCONERR_NOERROR; // But the certificate must not have been verified or previously accepted by the user. return TRUE; } else @@ -821,11 +821,11 @@ bool InitSSL(int logUID, int* errorID) { SSLLib.CRYPTO_set_locking_callback(/*(void (*)(int,int,const char *,int))*/ LockingCallback); - // NOTE: the pointer returned SSLv23_client_method is not to be freed + // NOTE: do not free the pointer returned by SSLv23_client_method() // - // SSLv23_client_method() is default method used in OpenSLL.exe and CURL. - // Unsafe SSL2 protocol is disabled using OPENSSL_NO_SSL2 define. - // SSLv3_client_method() didn't work with wedos server: https://forum.altap.cz/viewtopic.php?f=2&t=6667 + // SSLv23_client_method() is the default method used in OpenSSL.exe and CURL. + // The unsafe SSL2 protocol is disabled by the OPENSSL_NO_SSL2 define. + // SSLv3_client_method() did not work with the wedos server: https://forum.altap.cz/viewtopic.php?f=2&t=6667 // SSLLib.Meth = SSLLib.SSLv3_client_method(); SSLLib.Meth = SSLLib.SSLv23_client_method(); if (SSLLib.Meth) @@ -833,15 +833,15 @@ bool InitSSL(int logUID, int* errorID) SSLLib.Ctx = SSLLib.SSL_CTX_new(SSLLib.Meth); if (SSLLib.Ctx) { - /* also switch on all the interoperability and bug - * workarounds so that we will communicate with people - * that cannot read poorly written specs :-) - */ + /* also enable all the interoperability and bug + * workarounds so that we can communicate with implementations + * that cannot read poorly written specs + */ SSLLib.SSL_CTX_ctrl(SSLLib.Ctx, SSL_CTRL_OPTIONS, SSL_OP_ALL, NULL); bSSLInited = true; return true; } - } // if Meth <> NULL then + } // if Meth != NULL } } FreeSSL(loadStatus); diff --git a/src/plugins/ftp/ssl.h b/src/plugins/ftp/ssl.h index 0799074dd..407997973 100644 --- a/src/plugins/ftp/ssl.h +++ b/src/plugins/ftp/ssl.h @@ -96,7 +96,7 @@ typedef const char* (*TX509_verify_cert_error_string)(long n); typedef X509* (*TSSL_get_peer_certificate)(const SSL* SSL); typedef STACK_OF(X509) * (*TSSL_get_peer_cert_chain)(const SSL* s); typedef STACK_OF(SSL_COMP) * (*TSSL_COMP_get_compression_methods)(void); -typedef SSL_SESSION* (*TSSL_get1_session)(SSL* ssl); /* obtain a reference count */ +typedef SSL_SESSION* (*TSSL_get1_session)(SSL* ssl); /* obtain a session and increment its reference count */ typedef void (*TSSL_SESSION_free)(SSL_SESSION* ses); typedef long (*TSSL_ctrl)(SSL* ssl, int cmd, long larg, void* parg); typedef int (*TSSL_set_session)(SSL* to, SSL_SESSION* session); diff --git a/src/plugins/ieviewer/ieviewer.cpp b/src/plugins/ieviewer/ieviewer.cpp index d49a8b5bb..40a6a1269 100644 --- a/src/plugins/ieviewer/ieviewer.cpp +++ b/src/plugins/ieviewer/ieviewer.cpp @@ -103,7 +103,7 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { if (fdwReason == DLL_PROCESS_ATTACH) DLLInstance = hinstDLL; - return TRUE; // DLL can be loaded + return TRUE; // Allow the DLL to load } // @@ -157,7 +157,7 @@ void UpdateInternetFeatureControl() // MSDN mentions that FEATURE_96DPI_PIXEL is deprecated and replaced by DOCHOSTUIFLAG_DPI_AWARE // https://msdn.microsoft.com/en-us/library/aa753277%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 - // but it still works under W10/IE11, so I am ignoring it + // but it still works under W10/IE11, so it is left as is char exePath[MAX_PATH]; if (!GetModuleFileName(NULL, exePath, MAX_PATH)) @@ -197,12 +197,12 @@ CPluginInterfaceAbstract* WINAPI SalamanderPluginEntry(CSalamanderPluginEntryAbs { // reject older versions MessageBox(salamander->GetParentWindow(), REQUIRE_LAST_VERSION_OF_SALAMANDER, - "Internet Explorer Viewer" /* neprekladat! */, MB_OK | MB_ICONERROR); + "Internet Explorer Viewer" /* do not translate */, MB_OK | MB_ICONERROR); return NULL; } // let it load the language module (.slg) - HLanguage = salamander->LoadLanguageModule(salamander->GetParentWindow(), "Internet Explorer Viewer" /* neprekladat! */); + HLanguage = salamander->LoadLanguageModule(salamander->GetParentWindow(), "Internet Explorer Viewer" /* do not translate */); if (HLanguage == NULL) return NULL; @@ -394,7 +394,7 @@ unsigned WINAPI ThreadIEMessageLoop(void* param) lstrcpyn(name, data->Name, MAX_PATH); IStream* contentStream = data->ContentStream; BOOL openFile = data->Success; - SetEvent(data->Continue); // let the main thread continue; data are invalid from this point (=NULL) + SetEvent(data->Continue); // allow the main thread to continue; the data are invalid from this point on (=NULL) data = NULL; // if everything succeeded, open the requested file in the window @@ -421,10 +421,10 @@ unsigned WINAPI ThreadIEMessageLoop(void* param) } } - // probably a common bug in IE - the object was originally destroyed in response to WM_DESTROY - // but a message arrived before the message pump finished and hit the destroyed + // probably a common IE bug: the object was originally destroyed in response to WM_DESTROY + // but another message arrived before the message pump finished and accessed the destroyed // object - // therefore I moved the window destruction here - similar to ooStatic from WinLib + // therefore the window destruction was moved here, similar to ooStatic in WinLib CALL_STACK_MESSAGE1("ThreadIEMessageLoop::message_loop done"); delete window; @@ -1386,7 +1386,7 @@ CSite::CSite() //Object interfaces m_pIUnknown = NULL; m_pIWebBrowser = NULL; - m_pIWebBrowser2 = NULL; // !!! warning - for IE3.02 it can be NULL + m_pIWebBrowser2 = NULL; // Warning: may be NULL in IE 3.02 m_pIOleObject = NULL; m_pIOleInPlaceObject = NULL; m_pIOleInPlaceActiveObject = NULL; @@ -1533,7 +1533,7 @@ BOOL CSite::Create(HWND hParentWnd) CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER, IID_IUnknown, (void**)&m_pIUnknown); - if (hr == REGDB_E_CLASSNOTREG) // correct variant + if (hr == REGDB_E_CLASSNOTREG) // correct case { TRACE_E("A InternetExplorer class is not registered in the registration database"); return FALSE; diff --git a/src/plugins/ieviewer/ieviewer.h b/src/plugins/ieviewer/ieviewer.h index 9c9903fbc..1b38fea1a 100644 --- a/src/plugins/ieviewer/ieviewer.h +++ b/src/plugins/ieviewer/ieviewer.h @@ -453,7 +453,7 @@ class CIEMainWindow { public: HWND HWindow; // viewer window handle - HANDLE Lock; // 'lock' object or NULL (becomes signaled after we close the file) + HANDLE Lock; // 'lock' object or NULL (becomes signaled only after the file is closed) static CIEMainWindowQueue ViewerWindowQueue; // list of all viewer windows static CThreadQueue ThreadQueue; // list of all window threads diff --git a/src/plugins/ieviewer/markdown.cpp b/src/plugins/ieviewer/markdown.cpp index 8077e7a62..96c55ceed 100644 --- a/src/plugins/ieviewer/markdown.cpp +++ b/src/plugins/ieviewer/markdown.cpp @@ -116,7 +116,7 @@ IStream* ConvertMarkdownToHTML(const char* name) sprintf_s(buff, "