bool FileRename(const TChar *oldName, const TChar *newName) { TChar oldBuffer[MAX_PATH + 1]; TChar newBuffer[MAX_PATH + 1]; SHFILEOPSTRUCT shFileOpStruct; errno_t error; size_t oldLength, newLength; oldLength = _tcsnlen(oldName, MAX_PATH + 1); newLength = _tcsnlen(newName, MAX_PATH + 1); if (oldLength >= MAX_PATH || newLength >= MAX_PATH) { #ifdef UNICODE return ::MoveFileEx(oldName, newName, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED) != FALSE; #else return false; #endif } error = _tcscpy_s(oldBuffer, MAX_PATH + 1, oldName); if(error != 0) return false; oldBuffer[oldLength + 1] = 0; error = _tcscpy_s(newBuffer, MAX_PATH + 1, newName); if(error != 0) return false; newBuffer[newLength + 1] = 0; ZeroMemory(&shFileOpStruct, sizeof(shFileOpStruct)); shFileOpStruct.wFunc = FO_MOVE; shFileOpStruct.pFrom = oldBuffer; shFileOpStruct.pTo = newBuffer; shFileOpStruct.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI; return (SHFileOperation(&shFileOpStruct) == 0); }
/* * OnClickedOK */ LRESULT PasswdDialog::OnClickedOK(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { TCHAR passwdconfirm[MAX_PASSWD_LEN+2]; GetDlgItemText( IDC_PASSWD, passwd, MAX_PASSWD_LEN); // If we are encrypting files, check to make sure that the // password entered into the conformation field matches. // If decrypting, the confirmation is not necessary. if (encrypting) { GetDlgItemText( IDC_PASSWDCONFIRM, passwdconfirm, MAX_PASSWD_LEN); if (_tcscmp(passwd,passwdconfirm)) { MessageBox( _T("Password confirmation check failed.\nVerify that the passwords match."), _T("AES Crypt"), MB_OK); } else if (_tcsnlen(passwd, MAX_PASSWD_LEN) == 0) { MessageBox( _T("You failed to enter a password."), _T("AES Crypt"), MB_OK); } else { EndDialog(wID); } } else { if (_tcsnlen(passwd, MAX_PASSWD_LEN) == 0) { MessageBox( _T("You failed to enter a password."), _T("AES Crypt"), MB_OK); } else { EndDialog(wID); } } return 0; }
bool FileDelete(const TChar *fileName, bool toRecycle) { TChar buffer[MAX_PATH + 1]; SHFILEOPSTRUCT shFileOpStruct; errno_t error; size_t length; length = _tcsnlen(fileName, MAX_PATH + 1); if (length >= MAX_PATH) { #ifdef UNICODE return ::DeleteFile(fileName) != FALSE; #else return false; #endif } error = _tcscpy_s(buffer, MAX_PATH + 1, fileName); if(error != 0) return false; buffer[length + 1] = 0; ZeroMemory(&shFileOpStruct, sizeof(shFileOpStruct)); shFileOpStruct.wFunc = FO_DELETE; shFileOpStruct.pTo = NULL; shFileOpStruct.pFrom = buffer; shFileOpStruct.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI; if(toRecycle) shFileOpStruct.fFlags |= FOF_ALLOWUNDO; else shFileOpStruct.fFlags &= ~FOF_ALLOWUNDO; return (SHFileOperation(&shFileOpStruct) == 0); }
// Local version of the FileSaved() function not accessable to the outside. void FileSaved(FILE_INFO *fi, BOOL FileChanged, HWND DisplayWindow, const TCHAR* szFileExtension) { TCHAR szDisplay[BUFFERED_MAX_PATH]; size_t len; // _tcsnlen() returns zero if larger than the buffer length passed into it. memset(szDisplay, 0, sizeof(szDisplay)); len = _tcsnlen(fi->szFileName, TCHARBFLEN(fi->szFileName)); // Set the title to be displayed at the top of the window if a window handle was passed in. if(DisplayWindow != NULL) { if(fi->bNamed == FALSE) { if(szFileExtension != NULL) _stprintf_s(szDisplay, TCHARBFLEN(szDisplay), TEXT("Untitled.%s"), szFileExtension); else _stprintf_s(szDisplay, TCHARBFLEN(szDisplay), TEXT("Untitled")); } else { // Later on make the size that variable 'len' is compared to (currently 1 to force just // showing file title for now) variable and based on the size of the dialog box. // File title includes the file extension if(len == 0 || len > 1) _stprintf_s(szDisplay, TCHARBFLEN(szDisplay), TEXT("%s"), fi->szTitleName); else _stprintf_s(szDisplay, TCHARBFLEN(szDisplay), TEXT("%s"), fi->szFileName); } } // Handle if the file was changed. if(FileChanged == FALSE) { fi->bNeedSave = FALSE; } else { _tcscat_s(szDisplay, TCHARBFLEN(szDisplay), TEXT("*")); fi->bNeedSave = TRUE; } // Finally, set the dialog box display to show the file name/title. if(DisplayWindow != NULL) SetWindowText(DisplayWindow, szDisplay); }
BOOL IsPureDigital(TCHAR * str, INT maxLength) { BOOL Result= TRUE; int strLength = _tcsnlen(str, maxLength); for (int i = 0; i < strLength; ++i ) { if( str[i] < L'0' || str[i] > L'9') { Result = FALSE; break; } } return Result; }
BOOL IsPureSpace(TCHAR * str, INT maxLength) { BOOL Result= TRUE; int strLength = _tcsnlen(str, maxLength); for (int i = 0; i < strLength; ++i ) { if( str[i] != L' ') { Result = FALSE; break; } } return Result; }
//============================================================================== // Brief : ファイル名抽出処理 // Return : void : なし // Arg : TCHAR* pOut : 出力先 // Arg : const TCHAR* pSrc : ソース //============================================================================== void CManagerMotion::PickOutFileName( TCHAR* pOut, const TCHAR* pSrc ) { int nIdxSrc = 0; // ソースの文字番号 // ソースの文字数取得 nIdxSrc = _tcsnlen( pSrc, 256 ); // ファイル名の場所を決定 for( nIdxSrc -= 1; nIdxSrc >= 0; --nIdxSrc ) { if( pSrc[ nIdxSrc ] == _T( '\\' ) || pSrc[ nIdxSrc ] == _T( '/' ) ) { break; } } // ファイル名を設定 _tcscpy_s( pOut, 256, &pSrc[ nIdxSrc + 1 ] ); }
LPCTSTR SnarlInterface::GetIconsPath() { TCHAR* szIconPath = NULL; LPCTSTR szPath = GetAppPath(); if (!szPath) return NULL; size_t nLen = 0; nLen = _tcsnlen(szPath, MAX_PATH); if (nLen > 0) { nLen += 10 + 1; // etc\\icons\\ + NULL szIconPath = AllocateString(nLen); _tcsncpy(szIconPath, szPath, nLen); _tcsncat(szIconPath, _T("etc\\icons\\"), nLen); } FreeString(szPath); return szIconPath; }
regValueList_t ParseValues(const multiSzBuffer_t& data, DWORD aRegType) { regValueList_t values; const TCHAR* p = reinterpret_cast<const TCHAR*>(data.value); size_t bytes = static_cast<size_t>(data.cbBytes); size_t count = bytes / sizeof(TCHAR); if (aRegType == REG_SZ || aRegType == REG_EXPAND_SZ) { values.push_back(regValue_t(p, count - 1)); } else if (aRegType == REG_MULTI_SZ ) { while (count > 0) { size_t len = _tcsnlen(p, count); if (!len) { // empty, meaning end of strings break; } values.push_back(regValue_t(p, len)); p += len + 1; // include null terminator } } return values; }
int _tmain(int argc, _TCHAR* argv[]) { dbgtprintf(_T("%d parameter(s)\n"), argc - 1 ); TCHAR command[CMD_BUF_SIZE] = {0}; for(int i = 0; i< argc; i++) { dbgtprintf(_T("%s\n"),argv[i]); } if( argc == 1 ) { _tprintf(_T("Usage:\n")); _tprintf(_T("\t%s <command>\n"), argv[0]); return 0; } else if(argc >= 2) { // Append commands ULONG position = 0; for(int i = 0; i < argc; i++) { if( 0 == i ) { _stprintf_s(command + position, CMD_BUF_SIZE-position-1, _T("%s "), BASE_CMD); position += _tcsnlen(BASE_CMD, CMD_PARAMETER_LENGTH_LIMIT) + 1; } else { _stprintf_s(command + position, CMD_BUF_SIZE-position-1, _T("%s "), argv[i]); position += _tcsnlen(argv[i], CMD_PARAMETER_LENGTH_LIMIT) + 1; } } dbgtprintf(_T("%s\n"),command); } else { _tprintf(_T("Invalid parameter(s)!\n")); return -1; } SECURITY_ATTRIBUTES sa={sizeof ( sa ),NULL,TRUE}; HANDLE hWritePipe = INVALID_HANDLE_VALUE; HANDLE hReadPipe = INVALID_HANDLE_VALUE; BOOL bResult = CreatePipe(&hReadPipe, &hWritePipe, &sa, 0); if ( !bResult || hWritePipe == INVALID_HANDLE_VALUE || hReadPipe == INVALID_HANDLE_VALUE) { _tprintf(TEXT("CreatePipe failed, GLE=%d.\n"), GetLastError()); return -1; } else { dbgtprintf(TEXT("CreatePipe is successful.\n")); } // CreateProcess dbgtprintf(TEXT("Try to CreateProcess.\n")); STARTUPINFO si={0}; si.cb = sizeof(STARTUPINFO); si.dwFlags =STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES; //使用标准柄和显示窗口 si.hStdOutput = hWritePipe;//将文件作为标准输出句柄 si.hStdError = hWritePipe;//将文件作为标准输出句柄 si.wShowWindow = SW_HIDE;//隐藏控制台窗口 PROCESS_INFORMATION pi={0}; PROCESS_WAITING_THREAD_CONTEXT pwi = {0}; pwi.hReadPipe = hReadPipe; pwi.hWritePipe = hWritePipe; if ( CreateProcess ( NULL, command, &sa, &sa, TRUE, NORMAL_PRIORITY_CLASS,NULL,NULL,&si,&pi) ) { pwi.ppi = π dbgtprintf(TEXT("OK to CreateProcess.\n")); HANDLE hThread = CreateThread(&sa, 0, ProcessWaitingThread, &pwi, 0, NULL ); if( 0 != hThread ) { dbgtprintf(TEXT("OK to CreateThread.\n")); SYSTEMTIME st; GetSystemTime(&st); TCHAR logFileName[MAX_PATH] = {0}; _stprintf_s(logFileName, MAX_PATH - 1, _T("RC_%04d%02d%02d-%d-%02d%02d%02d-%03d.log"), st.wYear,st.wMonth,st.wDay,st.wDayOfWeek,st.wHour,st.wMinute,st.wSecond,st.wMilliseconds); dbgtprintf(logFileName); dbgtprintf(L"\n"); HANDLE hLogFile = CreateFile(logFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(INVALID_HANDLE_VALUE == hLogFile) { _tprintf(_T("Failed to CreateFile, st = 0x%x\n"), GetLastError()); goto ErrorExit; } else { dbgtprintf(TEXT("OK to CreateFile.\n")); } BOOL bReadable = TRUE; BOOL bWrite = FALSE; while (bReadable) { CHAR strCmdFeedbackBuffer[1024] = {0}; DWORD dwRead = 0; DWORD dwToWrite = 0; DWORD dwWritten = 0; bReadable = ReadFile( hReadPipe, strCmdFeedbackBuffer, 1024-1, &dwRead, NULL); printf(strCmdFeedbackBuffer); dwToWrite = dwRead; bWrite = WriteFile( hLogFile, strCmdFeedbackBuffer, dwToWrite, &dwWritten, NULL); if(!bWrite) { _tprintf(_T("Write to log file error, st=0x%x\n"), GetLastError()); assert(false); } assert(dwToWrite == dwWritten); } CloseHandle(hLogFile); } else { _tprintf(_T("Failed to CreateThread, st = 0x%x\n"), GetLastError()); goto ErrorExit; } } else { _tprintf(_T("Failed to CreateProcess, st = 0x%x\n"), GetLastError()); goto ErrorExit; } // waitThread // goto OkExit; ErrorExit: if (!CloseHandle(hWritePipe)) { _tprintf(_T("Close hWritePipe False, st = 0x%x\n"), GetLastError()); } if (!CloseHandle(hReadPipe)) { _tprintf(_T("Close hWritePipe False, st = 0x%x\n"), GetLastError()); } return -1; OkExit: return 0; }
/////////////////////////////////////////////////////////////////////////////// // // ohci adapter info // /////////////////////////////////////////////////////////////////////////////// // int ohci_info(bool bVerbose=false, bool bShowInactive=false, bool bSearchOnline=false) { char tmp[0x100]; DWORD size = sizeof tmp; memset (tmp, 0, size); long lResult = 0; int index = 0; int numFound = 0; int nOSMajor = -1; // int nOSMinor = -1; // int nOSServicePack = -1; fwi::OHCI1394_DEV_INFO devInfo = { 0 }; while ((lResult==FWI_NO_ERROR) || (lResult==FWI_FILTERED)) { lResult = g_fwi.get1394OHCIControllerInfo(index++, bSearchOnline ? fwi::kLookOnline : fwi::kUseBuiltIn, bShowInactive ? fwi::kAllAdapters : fwi::kActiveAdaptersOnly, &devInfo ); switch (lResult) { case FWI_ERROR_FILE_NOT_FOUND: { _tprintf(TEXT("\n\n*** Could not get online data.\nThe online source may not be available, or your computer may not be connected to the Internet.")); break; } case FWI_ERROR_BAD_FILE_FORMAT: { _tprintf(TEXT("\n\n*** The online data source is not available.")); break; } case FWI_ACCESS_ERROR: { _tprintf(TEXT("\n\n*** Could not access the Registry. Make sure to run this program with Administrator privileges.")); break; } case FWI_FILTERED: break; case FWI_NO_ERROR: { if (devInfo.bValid) { ++numFound; if (!bVerbose) { _tprintf(TEXT("#%d (%s:%s) %s : %s\n"), numFound, devInfo.vendorId, devInfo.deviceId, devInfo.vendorName, devInfo.chipset); } else { _tprintf(TEXT("#%d\n"), numFound); _tprintf(TEXT(" Vendor : (%s) %s\n"), devInfo.vendorId, devInfo.vendorName); _tprintf(TEXT(" Chipset: (%s) %s\n"), devInfo.deviceId, devInfo.chipset); _tprintf(TEXT(" Revision: %s\n"), devInfo.revision); if (nOSMajor == 5) { switch (devInfo.sidSpeed) { case 0: _tprintf(TEXT(" **** Warning speed=S100. 1394 devices will have limited channel count.\n")); break; case 1: _tprintf(TEXT(" **** Warning speed=S200. 1394 devices will have limited channel count.\n")); break; case 2: _tprintf(TEXT(" Speed: S400 (ok).\n")); break; case 3: _tprintf(TEXT(" Speed: S400/S800 (ok).\n")); break; default: _tprintf(TEXT(" **** Warning SidSpeed registry entry is missing or illegal.\n 1394 devices may not work, or will have limited channel count.\n")); break; } } if (bShowInactive) { _tprintf(TEXT(" Status : %s\n"), devInfo.bActive ? TEXT("Active") : TEXT("No longer present, or disabled.")); } _tprintf(TEXT(" Details:\n")); _tprintf(TEXT(" Subsysten VendorId: %04x\n"), devInfo.subsysVendorId); _tprintf(TEXT(" Subsystem DeviceId: %04x\n"), devInfo.subsysDeviceId); if (devInfo.bFound) { _tprintf(TEXT(" Max # isoch Rx contexts: %s\n"), devInfo.maxRx); _tprintf(TEXT(" Max # isoch Tx contexts: %s\n"), devInfo.maxTx); } _tprintf(TEXT(" Support: ")); if (devInfo.bFound) { switch (devInfo.support) { case FW_INTERFACES_SUPPORT_LEVEL_NONE: _tprintf(TEXT("Not compatible with DICE drivers.\n")); break; case FW_INTERFACES_SUPPORT_LEVEL_FULL: _tprintf(TEXT("Compatible, no known issues.\n")); break; case FW_INTERFACES_SUPPORT_LEVEL_LIMITED: _tprintf(TEXT("Limited support.\n")); break; case FW_INTERFACES_SUPPORT_LEVEL_UNKNOWN: // case fall-through default: _tprintf(TEXT("This controller has not been qualified yet.\n")); break; } if (_tcsnlen( devInfo.notes, NOTES_SIZE ) != 0) { _tprintf(TEXT(" Notes: %s\n"), devInfo.notes); } } else { _tprintf(TEXT("No support data available.\n")); } _tprintf(TEXT("\n")); } } break; } default: break; } } return 0; }
//=========================================================================== void PaintToolbar(HDC hdc, RECT *rcPaint) { RECT r; int i; const TCHAR *label = Toolbar_CurrentWindow; StyleItem *pSI; #ifdef BBOPT_MEMCHECK // Display some statistics. #pragma message("\n"__FILE__ "(397) : warning 0: MEMCHECK enabled.\n") /* if (NULL==Toolbar_hFont) { LOGFONT logFont; SystemParametersInfo(SPI_GETICONTITLELOGFONT, 0, &logFont, 0); Toolbar_hFont = CreateFontIndirect(&logFont); } */ extern int g_menu_count; extern int g_menu_item_count; TCHAR temp[256]; if (alloc_size && false == Toolbar_ShowingExternalLabel) { _stprintf(temp,_T("Menus %d MenuItems %d Memory %d"), g_menu_count, g_menu_item_count, alloc_size); label = temp; } #endif int tbW = TBInfo.width; int tbH = TBInfo.height; HDC buf = CreateCompatibleDC(NULL); HGDIOBJ bufother = SelectObject(buf, CreateCompatibleBitmap(hdc, tbW, tbH)); if (NULL==Toolbar_hFont) Toolbar_hFont = CreateStyleFont(&mStyle.Toolbar); HGDIOBJ other_font = SelectObject(buf, Toolbar_hFont); // Get width of clock... SIZE size; GetTextExtentPoint32(buf, Toolbar_CurrentTime, (int)_tcsnlen(Toolbar_CurrentTime,0x7FFFFFFFUL), &size); size.cx += 6; if (tbClockW < size.cx) tbClockW = size.cx + 6; GetTextExtentPoint32(buf, Toolbar_WorkspaceName, (int)_tcsnlen(Toolbar_WorkspaceName,0x7FFFFFFFUL), &size); int tbLabelW = size.cx + 6; // The widest sets the width! tbLabelW = tbClockW = (int)imax(tbH * 2, imax(tbLabelW, tbClockW)); int margin = tbMargin; int border = mStyle.Toolbar.borderWidth; int border_margin = margin + border; int button_padding = (tbH - tbButtonWH) / 2 - border; int tbLabelX = border_margin; int tbClockX = tbW - tbClockW - border_margin; int two_buttons = 2*tbButtonWH + 3*button_padding; int tbWinLabelX = tbLabelX + tbLabelW + two_buttons; int tbWinLabelW = tbClockX - tbWinLabelX - two_buttons; if (tbWinLabelW < 0) tbWinLabelW = 0; Toolbar_Button[0].r.left = tbLabelX + tbLabelW + button_padding; Toolbar_Button[1].r.left = Toolbar_Button[0].r.left + tbButtonWH + button_padding; Toolbar_Button[2].r.left = tbClockX - 2*tbButtonWH - 2*button_padding; Toolbar_Button[3].r.left = Toolbar_Button[2].r.left + tbButtonWH + button_padding; Toolbar_Button[4].r.left = tbClockX; for (i = 0; i<5; i++) { Toolbar_Button[i].r.top = (tbH - tbButtonWH) / 2; Toolbar_Button[i].r.bottom = Toolbar_Button[i].r.top + tbButtonWH; Toolbar_Button[i].r.right = Toolbar_Button[i].r.left + tbButtonWH; } Toolbar_Button[4].r.right = tbClockX + tbClockW; //==================== // Paint toolbar Style _SetRect(&r, 0, 0, tbW, tbH); pSI = &mStyle.Toolbar; MakeStyleGradient(buf, &r, pSI, true); //==================== // Paint unpressed workspace/task buttons... r.left = r.top = 0; r.right = r.bottom = tbButtonWH; { HPEN activePen = CreatePen(PS_SOLID, 1, mStyle.ToolbarButtonPressed.picColor); HPEN inactivePen = CreatePen(PS_SOLID, 1, mStyle.ToolbarButton.picColor); HDC src = CreateCompatibleDC(NULL); HGDIOBJ srcother = SelectObject(src, CreateCompatibleBitmap(hdc, tbButtonWH, tbButtonWH)); int yOffset = tbH / 2; int xOffset; int f1 = -1; for (i=0; i<4; i++) { int f2 = Toolbar_Button[i].pressed || (Toolbar_force_button_pressed && i&1); pSI = f2 ? &mStyle.ToolbarButtonPressed : &mStyle.ToolbarButton; if (pSI->parentRelative) { CreateBorder(buf, &r, pSI->borderColor, pSI->borderWidth); } else { if (f1 != f2) MakeStyleGradient(src, &r, pSI, pSI->bordered), f1 = f2; BitBlt(buf, Toolbar_Button[i].r.left, Toolbar_Button[i].r.top, tbButtonWH, tbButtonWH, src, 0, 0, SRCCOPY ); } xOffset = Toolbar_Button[i].r.left + (tbButtonWH / 2); HGDIOBJ penother = SelectObject(buf, f2 ? activePen : inactivePen); arrow_bullet(buf, xOffset, yOffset, (i&1)*2-1); SelectObject(buf, penother); } DeleteObject(SelectObject(src, srcother)); DeleteDC(src); DeleteObject(inactivePen); DeleteObject(activePen); } //==================== r.top = (tbH - tbLabelH)/2; r.bottom = r.top + tbLabelH; SetBkMode(buf, TRANSPARENT); int justify = mStyle.Toolbar.Justify | (DT_VCENTER|DT_SINGLELINE|DT_WORD_ELLIPSIS|DT_NOPREFIX); // Paint workspaces background... r.right = (r.left = tbLabelX) + tbLabelW; pSI = &mStyle.ToolbarLabel; MakeStyleGradient(buf, &r, pSI, pSI->bordered); _InflateRect(&r, -3, 0); BBDrawText(buf, Toolbar_WorkspaceName, -1, &r, justify, pSI); // Paint window label background... r.right = (r.left = tbWinLabelX) + tbWinLabelW; pSI = &mStyle.ToolbarWindowLabel; MakeStyleGradient(buf, &r, pSI, pSI->bordered); _InflateRect(&r, -3, 0); BBDrawText(buf, label, -1, &r, justify, pSI); // Paint clock background... r.right = (r.left = tbClockX) + tbClockW; pSI = &mStyle.ToolbarClock; MakeStyleGradient(buf, &r, pSI, pSI->bordered); _InflateRect(&r, -3, 0); BBDrawText(buf, Toolbar_CurrentTime, -1, &r, justify, pSI); //==================== BitBltRect(hdc, buf, rcPaint); SelectObject(buf, other_font); DeleteObject(SelectObject(buf, bufother)); DeleteDC(buf); }
int _tmain(int argc, _TCHAR* argv[]) { UINT loop_times = 0; BOOL loop_endless = FALSE; DWORD ms_between_loop = 0; BOOL enable_logs = FALSE; TCHAR command[CMD_BUF_SIZE] = {0}; if ( ParameterCheck(argc, argv, loop_times, ms_between_loop, enable_logs, command, CMD_BUF_SIZE) ) { loop_endless = ( 0 == loop_times ); } else { PrintUsage(argv[0]); return 1; } HANDLE hLogFile = INVALID_HANDLE_VALUE; if( TRUE == enable_logs) { SYSTEMTIME st; GetSystemTime(&st); TCHAR logFileName[MAX_PATH] = {0}; _stprintf_s(logFileName, MAX_PATH - 1, _T("loop_trace_%04d%02d%02d-%d-%02d%02d%02d-%03d.log"), st.wYear,st.wMonth,st.wDay,st.wDayOfWeek,st.wHour,st.wMinute,st.wSecond,st.wMilliseconds); dbgtprintf(logFileName); dbgtprintf(L"\n"); hLogFile = CreateFile(logFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(INVALID_HANDLE_VALUE == hLogFile) { _tprintf(_T("Failed to Create Log File, st = 0x%x\n"), GetLastError()); return 1; } else { dbgtprintf(TEXT("OK to CreateFile.\n")); } } while( loop_endless || loop_times > 0 ) { if(!loop_endless) { --loop_times; } CHAR printedCommand[CMD_BUF_SIZE] = {0}; sprintf_s(printedCommand, CMD_BUF_SIZE - 1, "\n-> %S\n\n", command + _tcsnlen(BASE_CMD, CMD_BUF_SIZE) + 1); printf(printedCommand); if (INVALID_HANDLE_VALUE != hLogFile) { DWORD dwToWrite = sizeof(CHAR) * strnlen(printedCommand, CMD_BUF_SIZE); DWORD dwWritten = 0; BOOL bWrite = WriteFile( hLogFile, printedCommand, dwToWrite, &dwWritten, NULL); if(!bWrite) { _tprintf(_T("Write to log file error, st=0x%x\n"), GetLastError()); assert(false); } assert(dwToWrite == dwWritten); } ExecuteCommand(command, CMD_BUF_SIZE, enable_logs, hLogFile); Sleep(ms_between_loop); } if (INVALID_HANDLE_VALUE != hLogFile) { CloseHandle(hLogFile); } return 0; }
ArrayBlock<RawMouse> getRawMouseArray() { UINT nDevices; PRAWINPUTDEVICELIST pRawInputDeviceList; list<RawMouse> rawMiceList; if (GetRawInputDeviceList(NULL, &nDevices, sizeof(RAWINPUTDEVICELIST)) != 0) { showErrorMessageAndExit(L"GetRawInputDeviceList() count"); } pRawInputDeviceList = safeMallocExitOnFailure<RAWINPUTDEVICELIST>(nDevices); if (((INT) GetRawInputDeviceList(pRawInputDeviceList, &nDevices, sizeof(RAWINPUTDEVICELIST))) < 0) { showErrorMessageAndExit(L"GetRawInputDeviceList() get"); } for (UINT currentDeviceIndex = 0; currentDeviceIndex < nDevices; currentDeviceIndex++) { DWORD currentDeviceType = pRawInputDeviceList[currentDeviceIndex].dwType; HANDLE hDevice = pRawInputDeviceList[currentDeviceIndex].hDevice; if (currentDeviceType == RIM_TYPEMOUSE) { UINT cbSize; TCHAR* psName; if (GetRawInputDeviceInfo(hDevice, RIDI_DEVICENAME, NULL, &cbSize) != 0) { showErrorMessageAndExit(L"GetRawInputDeviceInfo() count"); } psName = safeMallocExitOnFailure<TCHAR>(cbSize); if (((INT) GetRawInputDeviceInfo(hDevice, RIDI_DEVICENAME, psName, &cbSize)) < 0) { safe_free(&psName); showErrorMessageAndExit(L"GetRawInputDeviceInfo() get"); } assert(_tcsnlen(psName, cbSize) == cbSize - 1); // We want to ignore RDP mice { TCHAR rdpMouseName[] = _T("\\\\?\\Root#RDP_MOU#0000#"); size_t rdpMouseNameStrlen = _tcslen(rdpMouseName); if (_tcslen(psName) >= rdpMouseNameStrlen && _tcsncmp(rdpMouseName, psName, rdpMouseNameStrlen) == 0) { safe_free(&psName); continue; } } safe_free(&psName); if (GetRawInputDeviceInfo(hDevice, RIDI_DEVICEINFO, NULL, &cbSize) != 0) { showErrorMessageAndExit(L"GetRawInputDeviceInfo() count"); } PRID_DEVICE_INFO pDeviceInfo = safeMallocBytesExitOnFailure<RID_DEVICE_INFO>(cbSize); pDeviceInfo->cbSize = cbSize; if (((INT) GetRawInputDeviceInfo(hDevice, RIDI_DEVICEINFO, pDeviceInfo, &cbSize)) < 0) { showErrorMessageAndExit(L"GetRawInputDeviceInfo() get"); } assert(pDeviceInfo->dwType == RIM_TYPEMOUSE); RawMouse currentMouse; currentMouse.deviceHandle = pRawInputDeviceList[currentDeviceIndex].hDevice; currentMouse.x = 0; currentMouse.y = 0; currentMouse.z = 0; currentMouse.buttonsPressed = ArrayBlock<bool>(); currentMouse.buttonsPressed.allocate(pDeviceInfo->mouse.dwNumberOfButtons); memset(currentMouse.buttonsPressed.data(), 0, sizeof(bool)*currentMouse.buttonsPressed.count()); rawMiceList.push_back(currentMouse); } } safe_free(&pRawInputDeviceList); ArrayBlock<RawMouse> out_rawMiceArray; out_rawMiceArray.allocate(rawMiceList.size()); size_t currentPos = 0; for (list<RawMouse>::iterator rawMouseIt = rawMiceList.begin(); rawMouseIt != rawMiceList.end(); rawMouseIt++) { out_rawMiceArray.data()[currentPos] = *rawMouseIt; currentPos++; } return out_rawMiceArray; }
void show_cmdname(const TCHAR* name_) { if (_tcsnlen(name_, CMD_NAME_SIZE) != CMD_NAME_SIZE) { elist.set_last_item(name_); } else { elist.set_last_item(INIT_COMMAND); } }
BOOL ParameterCheck(int argc, _TCHAR* argv[], UINT & loop_times, DWORD & ms_between_loop, BOOL & enable_logs, TCHAR * p_command_buf, ULONG command_buf_size) // loop -cmd "dir *.exe" -times 5 -sleep 2 -log // loop -c "dir *.exe" -t 5 -s 2 -l // loop dir *.exe { assert(argv); assert(p_command_buf); BOOL result = FALSE; loop_times = 0; ms_between_loop = 1000; enable_logs = FALSE; dbgtprintf(_T("%d parameter(s)\n"), argc - 1 ); for(int i = 0; i< argc; i++) { dbgtprintf(_T("%s\n"),argv[i]); } if ( 1 == argc ) { // Do nothing here, To Invoke PrintUsage(argv[0]); } else { int len = _tcsnlen(argv[1],CMD_OPTION_LENGTH); dbgtprintf(_T("len of argv[1] = %d\n"), len); if ( 0 < len ) { _tcslwr_s(argv[1], len+1); //_tcsdup } else { // do nothing } if ( 0 == _tcsncmp(OPTION_CMD,argv[1], _tcslen(OPTION_CMD)) || 0 == _tcsncmp(OPTION_C,argv[1],_tcslen(OPTION_C)) || 0 == _tcsncmp(OPTION_TIMES,argv[1], _tcslen(OPTION_TIMES)) || 0 == _tcsncmp(OPTION_T,argv[1],_tcslen(OPTION_T)) || 0 == _tcsncmp(OPTION_SLEEP,argv[1], _tcslen(OPTION_SLEEP)) || 0 == _tcsncmp(OPTION_S,argv[1],_tcslen(OPTION_S)) || 0 == _tcsncmp(OPTION_LOG,argv[1], _tcslen(OPTION_LOG)) || 0 == _tcsncmp(OPTION_L,argv[1],_tcslen(OPTION_L)) ) { dbgtprintf(_T("Parameters Mode.\n")); int iExpectedParameters = 0; BOOL bGetCmdFromOpt = FALSE; BOOL bGetTimesFromOpt = FALSE; BOOL bGetSleepFromOpt = FALSE; BOOL bGetLogFromOpt = FALSE; result = TRUE; for( int i = 1; i < argc; i++ ) { int len = _tcsnlen(argv[i],CMD_OPTION_LENGTH); dbgtprintf(_T("len of argv[%d] = %d"), i, len); if ( 0 < len ) { _tcslwr_s(argv[i], len+1); //_tcsdup } else { // do nothing } if ( !bGetCmdFromOpt && ( 0 == _tcsncmp(OPTION_CMD,argv[i], _tcslen(OPTION_CMD)) || 0 == _tcsncmp(OPTION_C, argv[i], _tcslen(OPTION_C)) ) ) { dbgtprintf(_T("Get Command From Option\n")); if ( i + 1 < argc && !IsPureSpace(argv[i+1], CMD_PARAMETER_LENGTH_LIMIT) && _tcsnlen(argv[i+1], CMD_PARAMETER_LENGTH_LIMIT) > 0 ) { dbgtprintf(_T("Command Length, %d\n"), _tcsnlen(argv[i+1], CMD_PARAMETER_LENGTH_LIMIT)); bGetCmdFromOpt = TRUE; iExpectedParameters += 2; ULONG position = 0; _stprintf_s(p_command_buf, command_buf_size-position-1, _T("%s "), BASE_CMD); position += _tcsnlen(BASE_CMD, CMD_PARAMETER_LENGTH_LIMIT) + 1; _stprintf_s(p_command_buf + position, command_buf_size-position-1, _T("%s"), argv[i+1]); dbgtprintf(_T("Command: %s\n"),p_command_buf); } else { bGetCmdFromOpt = FALSE; result = FALSE; _tprintf(_T("Invalid \"command\" Parameter!\n") ); } } else if ( !bGetTimesFromOpt && ( 0 == _tcsncmp(OPTION_TIMES,argv[i], _tcslen(OPTION_TIMES)) || 0 == _tcsncmp(OPTION_T, argv[i], _tcslen(OPTION_T)) ) ) { dbgtprintf(_T("Get Times From Option\n")); if ( i + 1 < argc && IsPureDigital(argv[i+1], CMD_PARAMETER_LENGTH_LIMIT) ) { bGetTimesFromOpt = TRUE; iExpectedParameters += 2; // to-do loop_times = _tcstoul(argv[i+1], NULL, 10 ); if ( loop_times >= TIMES_MIN && loop_times <= TIMES_MAX ) { dbgtprintf(_T("Times: %d\n"), loop_times); } else { result = FALSE; _tprintf(_T("Invalid Range of \"times\" Parameter!\n")); } } else { bGetTimesFromOpt = FALSE; result = FALSE; _tprintf(_T("Invalid \"times\" Parameter!\n")); } } else if ( !bGetSleepFromOpt && ( 0 == _tcsncmp(OPTION_SLEEP, argv[i], _tcslen(OPTION_SLEEP)) || 0 == _tcsncmp(OPTION_S, argv[i], _tcslen(OPTION_S)) ) ) { dbgtprintf(_T("Get Sleep From Option\n")); if ( i + 1 < argc && IsPureDigital(argv[i+1], CMD_PARAMETER_LENGTH_LIMIT) ) { bGetSleepFromOpt = TRUE; iExpectedParameters += 2; // to-do DWORD s_between_loop = _tcstoul(argv[i+1], NULL, 10 ); if (s_between_loop >= SLEEP_MIN && s_between_loop <= SLEEP_MAX) { ms_between_loop = s_between_loop * 1000; dbgtprintf(_T("Sleep: %d\n"),ms_between_loop); } else { result = FALSE; _tprintf(_T("Invalid Range of \"sleep\" Parameter!\n")); } } else { bGetSleepFromOpt = FALSE; result = FALSE; _tprintf(_T("Invalid \"sleep\" Parameter!\n")); } } else if ( !bGetLogFromOpt && ( 0 == _tcsncmp(OPTION_LOG, argv[i], _tcslen(OPTION_LOG)) || 0 == _tcsncmp(OPTION_L, argv[i], _tcslen(OPTION_L)) ) ) { dbgtprintf(_T("Get Log From Option\n")); bGetLogFromOpt = TRUE; enable_logs = TRUE; iExpectedParameters++; } else { dbgtprintf(_T("Other parameters from command line: %s\n"), argv[i]); } if ( FALSE == result ) { break; } } if ( result == TRUE && FALSE == bGetCmdFromOpt ) { result = FALSE; _tprintf(_T("The \"cmd\" Parameter is Mandantory!\n") ); } if ( result == TRUE && iExpectedParameters != argc - 1) { result = FALSE; dbgtprintf(_T("iExpectedParameters = %d, argc - 1 = %d\n"), iExpectedParameters, argc - 1); _tprintf(_T("Too many parameters!\n"), iExpectedParameters, argc - 1); } } else { result = TRUE; dbgtprintf(_T("Always Loop Mode.\n")); dbgtprintf(_T("%p, %p\n"), p_command_buf, p_command_buf+1); ULONG position = 0; for(int i = 0; i < argc; i++) { if( 0 == i ) { dbgtprintf(_T("s,%d\n"),i); _stprintf_s(p_command_buf + position, command_buf_size-position-1, _T("%s "), BASE_CMD); position += _tcsnlen(BASE_CMD, CMD_PARAMETER_LENGTH_LIMIT) + 1; dbgtprintf(_T("e,%d\n"),i); } else { dbgtprintf(_T("s,%d\n"),i); dbgtprintf(_T("%s\n"),argv[i]); _stprintf_s(p_command_buf + position, command_buf_size-position-1, _T("%s "), argv[i]); position += _tcsnlen(argv[i], CMD_PARAMETER_LENGTH_LIMIT) + 1; dbgtprintf(_T("e,%d\n"),i); } } dbgtprintf(_T("Command: %s\n"),p_command_buf); } } return result; }
BOOL Notepad_plus::notify(SCNotification *notification) { //Important, keep track of which element generated the message bool isFromPrimary = (_mainEditView.getHSelf() == notification->nmhdr.hwndFrom || _mainDocTab.getHSelf() == notification->nmhdr.hwndFrom); bool isFromSecondary = !isFromPrimary && (_subEditView.getHSelf() == notification->nmhdr.hwndFrom || _subDocTab.getHSelf() == notification->nmhdr.hwndFrom); ScintillaEditView * notifyView = isFromPrimary?&_mainEditView:&_subEditView; DocTabView *notifyDocTab = isFromPrimary?&_mainDocTab:&_subDocTab; TBHDR * tabNotification = (TBHDR*) notification; switch (notification->nmhdr.code) { case SCN_MODIFIED: { static bool prevWasEdit = false; if (notification->modificationType & (SC_MOD_DELETETEXT | SC_MOD_INSERTTEXT)) { _pEditView->updateBeginEndSelectPosition(notification->modificationType & SC_MOD_INSERTTEXT, notification->position, notification->length); prevWasEdit = true; _linkTriggered = true; ::InvalidateRect(notifyView->getHSelf(), NULL, TRUE); } if (notification->modificationType & SC_MOD_CHANGEFOLD) { if (prevWasEdit) { notifyView->foldChanged(notification->line, notification->foldLevelNow, notification->foldLevelPrev); prevWasEdit = false; } } else if (!(notification->modificationType & (SC_MOD_DELETETEXT | SC_MOD_INSERTTEXT))) { prevWasEdit = false; } } break; case SCN_SAVEPOINTREACHED: case SCN_SAVEPOINTLEFT: { Buffer * buf = 0; if (isFromPrimary) { buf = _mainEditView.getCurrentBuffer(); } else if (isFromSecondary) { buf = _subEditView.getCurrentBuffer(); } else { //Done by invisibleEditView? BufferID id = BUFFER_INVALID; if (notification->nmhdr.hwndFrom == _invisibleEditView.getHSelf()) { id = MainFileManager->getBufferFromDocument(_invisibleEditView.execute(SCI_GETDOCPOINTER)); } else if (notification->nmhdr.hwndFrom == _fileEditView.getHSelf()) { id = MainFileManager->getBufferFromDocument(_fileEditView.execute(SCI_GETDOCPOINTER)); } else { break; //wrong scintilla } if (id != BUFFER_INVALID) { buf = MainFileManager->getBufferByID(id); } else { break; } } bool isDirty = notification->nmhdr.code == SCN_SAVEPOINTLEFT; buf->setDirty(isDirty); break; } case SCN_MODIFYATTEMPTRO : // on fout rien break; case SCN_KEY: break; case TCN_TABDROPPEDOUTSIDE: case TCN_TABDROPPED: { TabBarPlus *sender = reinterpret_cast<TabBarPlus *>(notification->nmhdr.idFrom); bool isInCtrlStat = (::GetKeyState(VK_LCONTROL) & 0x80000000) != 0; if (notification->nmhdr.code == TCN_TABDROPPEDOUTSIDE) { POINT p = sender->getDraggingPoint(); //It's the coordinate of screen, so we can call //"WindowFromPoint" function without converting the point HWND hWin = ::WindowFromPoint(p); if (hWin == _pEditView->getHSelf()) // In the same view group { if (!_tabPopupDropMenu.isCreated()) { TCHAR goToView[32] = TEXT("Move to other view"); TCHAR cloneToView[32] = TEXT("Clone to other View"); vector<MenuItemUnit> itemUnitArray; itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_GOTO_ANOTHER_VIEW, goToView)); itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_CLONE_TO_ANOTHER_VIEW, cloneToView)); _tabPopupDropMenu.create(_pPublicInterface->getHSelf(), itemUnitArray, _mainMenuHandle); _nativeLangSpeaker.changeLangTabDrapContextMenu(_tabPopupDropMenu.getMenuHandle()); } _tabPopupDropMenu.display(p); } else if ((hWin == _pNonDocTab->getHSelf()) || (hWin == _pNonEditView->getHSelf())) // In the another view group { docGotoAnotherEditView(isInCtrlStat?TransferClone:TransferMove); }/* else if ((hWin == _pProjectPanel_1->getTreeHandle())) { //printStr(TEXT("IN!!!")); }*/ else { RECT nppZone; ::GetWindowRect(_pPublicInterface->getHSelf(), &nppZone); bool isInNppZone = (((p.x >= nppZone.left) && (p.x <= nppZone.right)) && (p.y >= nppZone.top) && (p.y <= nppZone.bottom)); if (isInNppZone) { // Do nothing return TRUE; } generic_string quotFileName = TEXT("\""); quotFileName += _pEditView->getCurrentBuffer()->getFullPathName(); quotFileName += TEXT("\""); COPYDATASTRUCT fileNamesData; fileNamesData.dwData = COPYDATA_FILENAMES; fileNamesData.lpData = (void *)quotFileName.c_str(); fileNamesData.cbData = long(quotFileName.length() + 1)*(sizeof(TCHAR)); HWND hWinParent = ::GetParent(hWin); TCHAR className[MAX_PATH]; ::GetClassName(hWinParent,className, sizeof(className)); if (lstrcmp(className, _pPublicInterface->getClassName()) == 0 && hWinParent != _pPublicInterface->getHSelf()) // another Notepad++ { int index = _pDocTab->getCurrentTabIndex(); BufferID bufferToClose = notifyDocTab->getBufferByIndex(index); Buffer * buf = MainFileManager->getBufferByID(bufferToClose); int iView = isFromPrimary?MAIN_VIEW:SUB_VIEW; if (buf->isDirty()) { generic_string msg, title; _nativeLangSpeaker.messageBox("CannotMoveDoc", _pPublicInterface->getHSelf(), TEXT("Document is modified, save it then try again."), TEXT("Move to new Notepad++ Instance"), MB_OK); } else { ::SendMessage(hWinParent, NPPM_INTERNAL_SWITCHVIEWFROMHWND, 0, (LPARAM)hWin); ::SendMessage(hWinParent, WM_COPYDATA, (WPARAM)_pPublicInterface->getHinst(), (LPARAM)&fileNamesData); if (!isInCtrlStat) { fileClose(bufferToClose, iView); if (noOpenedDoc()) ::SendMessage(_pPublicInterface->getHSelf(), WM_CLOSE, 0, 0); } } } else // Not Notepad++, we open it here { docOpenInNewInstance(isInCtrlStat?TransferClone:TransferMove, p.x, p.y); } } } //break; sender->resetDraggingPoint(); return TRUE; } case TCN_TABDELETE: { int index = tabNotification->tabOrigin; BufferID bufferToClose = notifyDocTab->getBufferByIndex(index); Buffer * buf = MainFileManager->getBufferByID(bufferToClose); int iView = isFromPrimary?MAIN_VIEW:SUB_VIEW; if (buf->isDirty()) { //activate and use fileClose() (for save and abort) activateBuffer(bufferToClose, iView); fileClose(bufferToClose, iView); break; } int open = 1; if (isFromPrimary || isFromSecondary) open = notifyDocTab->nbItem(); doClose(bufferToClose, iView); //if (open == 1 && canHideView(iView)) // hideView(iView); break; } case TCN_SELCHANGE: { int iView = -1; if (notification->nmhdr.hwndFrom == _mainDocTab.getHSelf()) { iView = MAIN_VIEW; } else if (notification->nmhdr.hwndFrom == _subDocTab.getHSelf()) { iView = SUB_VIEW; } else { break; } switchEditViewTo(iView); BufferID bufid = _pDocTab->getBufferByIndex(_pDocTab->getCurrentTabIndex()); if (bufid != BUFFER_INVALID) activateBuffer(bufid, iView); break; } case NM_CLICK : { if (notification->nmhdr.hwndFrom == _statusBar.getHSelf()) { LPNMMOUSE lpnm = (LPNMMOUSE)notification; if (lpnm->dwItemSpec == DWORD(STATUSBAR_TYPING_MODE)) { bool isOverTypeMode = (_pEditView->execute(SCI_GETOVERTYPE) != 0); _pEditView->execute(SCI_SETOVERTYPE, !isOverTypeMode); _statusBar.setText((_pEditView->execute(SCI_GETOVERTYPE))?TEXT("OVR"):TEXT("INS"), STATUSBAR_TYPING_MODE); } } else if (notification->nmhdr.hwndFrom == _mainDocTab.getHSelf()) { switchEditViewTo(MAIN_VIEW); } else if (notification->nmhdr.hwndFrom == _subDocTab.getHSelf()) { switchEditViewTo(SUB_VIEW); } break; } case NM_DBLCLK : { if (notification->nmhdr.hwndFrom == _statusBar.getHSelf()) { LPNMMOUSE lpnm = (LPNMMOUSE)notification; if (lpnm->dwItemSpec == DWORD(STATUSBAR_CUR_POS)) { bool isFirstTime = !_goToLineDlg.isCreated(); _goToLineDlg.doDialog(_nativeLangSpeaker.isRTL()); if (isFirstTime) _nativeLangSpeaker.changeDlgLang(_goToLineDlg.getHSelf(), "GoToLine"); } else if (lpnm->dwItemSpec == DWORD(STATUSBAR_DOC_SIZE)) { command(IDM_VIEW_SUMMARY); } } break; } case NM_RCLICK : { POINT p; ::GetCursorPos(&p); if (notification->nmhdr.hwndFrom == _mainDocTab.getHSelf()) { switchEditViewTo(MAIN_VIEW); } else if (notification->nmhdr.hwndFrom == _subDocTab.getHSelf()) { switchEditViewTo(SUB_VIEW); } else if (_pFileSwitcherPanel && notification->nmhdr.hwndFrom == _pFileSwitcherPanel->getHSelf()) { // Already switched, so do nothing here. if (_pFileSwitcherPanel->nbSelectedFiles() > 1) { if (!_fileSwitcherMultiFilePopupMenu.isCreated()) { vector<MenuItemUnit> itemUnitArray; itemUnitArray.push_back(MenuItemUnit(IDM_FILESWITCHER_FILESCLOSE, TEXT("Close Selected files"))); itemUnitArray.push_back(MenuItemUnit(IDM_FILESWITCHER_FILESCLOSEOTHERS, TEXT("Close others files"))); _fileSwitcherMultiFilePopupMenu.create(_pPublicInterface->getHSelf(), itemUnitArray); _nativeLangSpeaker.changeLangTabContextMenu(_fileSwitcherMultiFilePopupMenu.getMenuHandle()); } _fileSwitcherMultiFilePopupMenu.display(p); return TRUE; } } else // From tool bar or Status Bar return TRUE; //break; if (!_tabPopupMenu.isCreated()) { vector<MenuItemUnit> itemUnitArray; itemUnitArray.push_back(MenuItemUnit(IDM_FILE_CLOSE, TEXT("Close"))); itemUnitArray.push_back(MenuItemUnit(IDM_FILE_CLOSEALL_BUT_CURRENT, TEXT("Close All BUT This"))); itemUnitArray.push_back(MenuItemUnit(IDM_FILE_CLOSEALL_TOLEFT, TEXT("Close All to the Left"))); itemUnitArray.push_back(MenuItemUnit(IDM_FILE_CLOSEALL_TORIGHT, TEXT("Close All to the Right"))); itemUnitArray.push_back(MenuItemUnit(IDM_FILE_SAVE, TEXT("Save"))); itemUnitArray.push_back(MenuItemUnit(IDM_FILE_SAVEAS, TEXT("Save As..."))); itemUnitArray.push_back(MenuItemUnit(IDM_FILE_RENAME, TEXT("Rename"))); itemUnitArray.push_back(MenuItemUnit(IDM_FILE_DELETE, TEXT("Move to Recycle Bin"))); itemUnitArray.push_back(MenuItemUnit(IDM_FILE_RELOAD, TEXT("Reload"))); itemUnitArray.push_back(MenuItemUnit(IDM_FILE_PRINT, TEXT("Print"))); itemUnitArray.push_back(MenuItemUnit(0, NULL)); itemUnitArray.push_back(MenuItemUnit(IDM_FILE_OPEN_FOLDER, TEXT("Open Containing Folder in Explorer"))); itemUnitArray.push_back(MenuItemUnit(IDM_FILE_OPEN_CMD, TEXT("Open Containing Folder in cmd"))); itemUnitArray.push_back(MenuItemUnit(0, NULL)); itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_SETREADONLY, TEXT("Read-Only"))); itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_CLEARREADONLY, TEXT("Clear Read-Only Flag"))); itemUnitArray.push_back(MenuItemUnit(0, NULL)); itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_FULLPATHTOCLIP, TEXT("Full File Path to Clipboard"))); itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_FILENAMETOCLIP, TEXT("Filename to Clipboard"))); itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_CURRENTDIRTOCLIP, TEXT("Current Dir. Path to Clipboard"))); itemUnitArray.push_back(MenuItemUnit(0, NULL)); itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_GOTO_ANOTHER_VIEW, TEXT("Move to Other View"))); itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_CLONE_TO_ANOTHER_VIEW, TEXT("Clone to Other View"))); itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_GOTO_NEW_INSTANCE, TEXT("Move to New Instance"))); itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_LOAD_IN_NEW_INSTANCE, TEXT("Open in New Instance"))); _tabPopupMenu.create(_pPublicInterface->getHSelf(), itemUnitArray); _nativeLangSpeaker.changeLangTabContextMenu(_tabPopupMenu.getMenuHandle()); } bool isEnable = ((::GetMenuState(_mainMenuHandle, IDM_FILE_SAVE, MF_BYCOMMAND)&MF_DISABLED) == 0); _tabPopupMenu.enableItem(IDM_FILE_SAVE, isEnable); Buffer * buf = _pEditView->getCurrentBuffer(); bool isUserReadOnly = buf->getUserReadOnly(); _tabPopupMenu.checkItem(IDM_EDIT_SETREADONLY, isUserReadOnly); bool isSysReadOnly = buf->getFileReadOnly(); _tabPopupMenu.enableItem(IDM_EDIT_SETREADONLY, !isSysReadOnly); _tabPopupMenu.enableItem(IDM_EDIT_CLEARREADONLY, isSysReadOnly); bool isFileExisting = PathFileExists(buf->getFullPathName()) != FALSE; _tabPopupMenu.enableItem(IDM_FILE_DELETE, isFileExisting); _tabPopupMenu.enableItem(IDM_FILE_RENAME, isFileExisting); bool isDirty = buf->isDirty(); bool isUntitled = buf->isUntitled(); _tabPopupMenu.enableItem(IDM_VIEW_GOTO_NEW_INSTANCE, !(isDirty||isUntitled)); _tabPopupMenu.enableItem(IDM_VIEW_LOAD_IN_NEW_INSTANCE, !(isDirty||isUntitled)); _tabPopupMenu.display(p); return TRUE; } case SCN_MARGINCLICK: { if (notification->nmhdr.hwndFrom == _mainEditView.getHSelf()) switchEditViewTo(MAIN_VIEW); else if (notification->nmhdr.hwndFrom == _subEditView.getHSelf()) switchEditViewTo(SUB_VIEW); int lineClick = int(_pEditView->execute(SCI_LINEFROMPOSITION, notification->position)); if (notification->margin == ScintillaEditView::_SC_MARGE_FOLDER) { _pEditView->marginClick(notification->position, notification->modifiers); if (_pDocMap) _pDocMap->fold(lineClick, _pEditView->isFolded(lineClick)); } else if ((notification->margin == ScintillaEditView::_SC_MARGE_SYBOLE) && !notification->modifiers) { if (!_pEditView->markerMarginClick(lineClick)) bookmarkToggle(lineClick); } break; } case SCN_FOLDINGSTATECHANGED : { if ((notification->nmhdr.hwndFrom == _mainEditView.getHSelf()) || (notification->nmhdr.hwndFrom == _subEditView.getHSelf())) { int lineClicked = notification->line; if (!_isFolding) { int urlAction = (NppParameters::getInstance())->getNppGUI()._styleURL; if ((urlAction == 1) || (urlAction == 2)) addHotSpot(); } if (_pDocMap) _pDocMap->fold(lineClicked, _pEditView->isFolded(lineClicked)); } return TRUE; } case SCN_CHARADDED: { const NppGUI & nppGui = NppParameters::getInstance()->getNppGUI(); bool indentMaintain = nppGui._maitainIndent; if (indentMaintain) MaintainIndentation(static_cast<TCHAR>(notification->ch)); AutoCompletion * autoC = isFromPrimary?&_autoCompleteMain:&_autoCompleteSub; if (nppGui._matchedPairConf.hasAnyPairsPair()) autoC->insertMatchedChars(notification->ch, nppGui._matchedPairConf); autoC->update(notification->ch); break; } case SCN_DOUBLECLICK : { if(notification->modifiers == SCMOD_CTRL) { const NppGUI & nppGUI = NppParameters::getInstance()->getNppGUI(); std::string bufstring; unsigned int position_of_click; // Anonymous scope to limit use of the buf pointer (much easier to deal with std::string). { char *buf; int length; if(nppGUI._delimiterSelectionOnEntireDocument) { // Get entire document. length = notifyView->execute(SCI_GETLENGTH); buf = new char[length + 1]; notifyView->execute(SCI_GETTEXT, (LPARAM)(length + 1), (WPARAM)buf); // For some reason Ctrl+DoubleClick on an empty line means that notification->position == 1. // In that case we use SCI_GETCURRENTPOS to get the position. if(notification->position != -1) position_of_click = notification->position; else position_of_click = int(_pEditView->execute(SCI_GETCURRENTPOS)); } else { // Get single line. length = notifyView->execute(SCI_GETCURLINE); buf = new char[length + 1]; notifyView->execute(SCI_GETCURLINE, (WPARAM)length, (LPARAM)buf); // Compute the position of the click (relative to the beginning of the line). const int line_position = notifyView->execute(SCI_POSITIONFROMLINE, notifyView->getCurrentLineNumber()); position_of_click = notification->position - line_position; } bufstring = buf; delete [] buf; } int leftmost_position = -1; int rightmost_position = -1; if(nppGUI._rightmostDelimiter == nppGUI._leftmostDelimiter) { // If the delimiters are the same (e.g. they are both a quotation mark), choose the ones // which are closest to the clicked position. for(unsigned int i = position_of_click; i >= 0; --i) { if(bufstring.at(i) == nppGUI._leftmostDelimiter) { // Respect escaped quotation marks. if(nppGUI._leftmostDelimiter == '"') { if(! (i > 0 && bufstring.at(i - 1) == '\\')) { leftmost_position = i; break; } } else { leftmost_position = i; break; } } } if(leftmost_position == -1) break; // Scan for right delimiter. for(unsigned int i = position_of_click; i < bufstring.length(); ++i) { if(bufstring.at(i) == nppGUI._rightmostDelimiter) { // Respect escaped quotation marks. if(nppGUI._rightmostDelimiter == '"') { if(! (i > 0 && bufstring.at(i - 1) == '\\')) { rightmost_position = i; break; } } else { rightmost_position = i; break; } } } } else { // Find matching pairs of delimiters (e.g. parantheses). // The pair where the distance from the left delimiter to position_of_click is at a minimum is the one we're looking for. // Of course position_of_click must lie between the delimiters. // This logic is required to handle cases like this: // (size_t i = function(); i < _buffers.size(); i++) std::stack<unsigned int> leftmost_delimiter_positions; for(unsigned int i = 0; i < bufstring.length(); ++i) { if(bufstring.at(i) == nppGUI._leftmostDelimiter) leftmost_delimiter_positions.push(i); else if(bufstring.at(i) == nppGUI._rightmostDelimiter && ! leftmost_delimiter_positions.empty()) { unsigned int matching_leftmost = leftmost_delimiter_positions.top(); leftmost_delimiter_positions.pop(); // We have either 1) chosen neither the left- or rightmost position, or 2) chosen both left- and rightmost position. assert( (leftmost_position == -1 && rightmost_position == -1) || (leftmost_position >= 0 && rightmost_position >= 0) ); // Note: cast of leftmost_position to unsigned int is safe, since if leftmost_position is not -1 then it is guaranteed to be positive. // If it was possible, leftmost_position and rightmost_position should be of type optional<unsigned int>. if( matching_leftmost <= position_of_click && i >= position_of_click && (leftmost_position == -1 || matching_leftmost > (unsigned int)leftmost_position) ) { leftmost_position = matching_leftmost; rightmost_position = i; } } } } // Set selection to the position we found (if any). if(rightmost_position != -1 && leftmost_position != -1) { if(nppGUI._delimiterSelectionOnEntireDocument) { notifyView->execute(SCI_SETCURRENTPOS, rightmost_position); notifyView->execute(SCI_SETANCHOR, leftmost_position + 1); } else { const int line_position = notifyView->execute(SCI_POSITIONFROMLINE, notifyView->getCurrentLineNumber()); notifyView->execute(SCI_SETCURRENTPOS, line_position + rightmost_position); notifyView->execute(SCI_SETANCHOR, line_position + leftmost_position + 1); } } } else if (_isHotspotDblClicked) { int pos = notifyView->execute(SCI_GETCURRENTPOS); notifyView->execute(SCI_SETCURRENTPOS, pos); notifyView->execute(SCI_SETANCHOR, pos); _isHotspotDblClicked = false; } } break; case SCN_UPDATEUI: { NppParameters *nppParam = NppParameters::getInstance(); // replacement for obsolete custom SCN_SCROLLED if (notification->updated & SC_UPDATE_V_SCROLL) { int urlAction = (NppParameters::getInstance())->getNppGUI()._styleURL; if ((urlAction == 1) || (urlAction == 2)) addHotSpot(); } // if it's searching/replacing, then do nothing if (nppParam->_isFindReplacing) break; if (notification->nmhdr.hwndFrom != _pEditView->getHSelf()) break; braceMatch(); NppGUI & nppGui = (NppGUI &)nppParam->getNppGUI(); if (nppGui._enableTagsMatchHilite) { XmlMatchedTagsHighlighter xmlTagMatchHiliter(_pEditView); xmlTagMatchHiliter.tagMatch(nppGui._enableTagAttrsHilite); } if (nppGui._enableSmartHilite) { if (nppGui._disableSmartHiliteTmp) nppGui._disableSmartHiliteTmp = false; else _smartHighlighter.highlightView(notifyView); } updateStatusBar(); AutoCompletion * autoC = isFromPrimary?&_autoCompleteMain:&_autoCompleteSub; autoC->update(0); break; } case TTN_GETDISPINFO: { try { LPTOOLTIPTEXT lpttt = (LPTOOLTIPTEXT)notification; //Joce's fix lpttt->hinst = NULL; POINT p; ::GetCursorPos(&p); ::ScreenToClient(_pPublicInterface->getHSelf(), &p); HWND hWin = ::RealChildWindowFromPoint(_pPublicInterface->getHSelf(), p); const int tipMaxLen = 1024; static TCHAR docTip[tipMaxLen]; docTip[0] = '\0'; generic_string tipTmp(TEXT("")); int id = int(lpttt->hdr.idFrom); if (hWin == _rebarTop.getHSelf()) { getNameStrFromCmd(id, tipTmp); if (tipTmp.length() >= 80) return FALSE; lstrcpy(lpttt->szText, tipTmp.c_str()); return TRUE; } else if (hWin == _mainDocTab.getHSelf()) { BufferID idd = _mainDocTab.getBufferByIndex(id); Buffer * buf = MainFileManager->getBufferByID(idd); tipTmp = buf->getFullPathName(); if (tipTmp.length() >= tipMaxLen) return FALSE; lstrcpy(docTip, tipTmp.c_str()); lpttt->lpszText = docTip; return TRUE; } else if (hWin == _subDocTab.getHSelf()) { BufferID idd = _subDocTab.getBufferByIndex(id); Buffer * buf = MainFileManager->getBufferByID(idd); tipTmp = buf->getFullPathName(); if (tipTmp.length() >= tipMaxLen) return FALSE; lstrcpy(docTip, tipTmp.c_str()); lpttt->lpszText = docTip; return TRUE; } else { return FALSE; } } catch (...) { //printStr(TEXT("ToolTip crash is caught!")); } } break; case SCN_ZOOM: break; case SCN_MACRORECORD: _macro.push_back(recordedMacroStep(notification->message, notification->wParam, notification->lParam, _pEditView->execute(SCI_GETCODEPAGE))); break; case SCN_PAINTED: { //--FLS: ViewMoveAtWrappingDisableFix: Disable wrapping messes up visible lines. Therefore save view position before in IDM_VIEW_WRAP and restore after SCN_PAINTED, as doc. says if (_mainEditView.isWrapRestoreNeeded()) { _mainEditView.restoreCurrentPos(); _mainEditView.setWrapRestoreNeeded(false); } if (_subEditView.isWrapRestoreNeeded()) { _subEditView.restoreCurrentPos(); _subEditView.setWrapRestoreNeeded(false); } notifyView->updateLineNumberWidth(); if (_syncInfo.doSync()) doSynScorll(HWND(notification->nmhdr.hwndFrom)); NppParameters *nppParam = NppParameters::getInstance(); // if it's searching/replacing, then do nothing if ((_linkTriggered && !nppParam->_isFindReplacing) || notification->wParam == LINKTRIGGERED) { int urlAction = (NppParameters::getInstance())->getNppGUI()._styleURL; if ((urlAction == 1) || (urlAction == 2)) addHotSpot(); _linkTriggered = false; } if (_pDocMap) { _pDocMap->wrapMap(); _pDocMap->scrollMap(); } break; } case SCN_HOTSPOTDOUBLECLICK : { notifyView->execute(SCI_SETWORDCHARS, 0, (LPARAM)"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-+.,:?&@=/%#()"); int pos = notifyView->execute(SCI_GETCURRENTPOS); int startPos = static_cast<int>(notifyView->execute(SCI_WORDSTARTPOSITION, pos, false)); int endPos = static_cast<int>(notifyView->execute(SCI_WORDENDPOSITION, pos, false)); notifyView->execute(SCI_SETTARGETSTART, startPos); notifyView->execute(SCI_SETTARGETEND, endPos); int posFound = notifyView->execute(SCI_SEARCHINTARGET, strlen(URL_REG_EXPR), (LPARAM)URL_REG_EXPR); if (posFound != -2) { if (posFound != -1) { startPos = int(notifyView->execute(SCI_GETTARGETSTART)); endPos = int(notifyView->execute(SCI_GETTARGETEND)); } // Prevent buffer overflow in getGenericText(). if(endPos - startPos > 2*MAX_PATH) endPos = startPos + 2*MAX_PATH; TCHAR currentWord[2*MAX_PATH]; notifyView->getGenericText(currentWord, MAX_PATH*2, startPos, endPos); // This treatment would fail on some valid URLs where there's actually supposed to be a comma or parenthesis at the end. int lastCharIndex = _tcsnlen(currentWord, MAX_PATH*2) - 1; if(lastCharIndex >= 0 && (currentWord[lastCharIndex] == ',' || currentWord[lastCharIndex] == ')' || currentWord[lastCharIndex] == '(')) currentWord[lastCharIndex] = '\0'; ::ShellExecute(_pPublicInterface->getHSelf(), TEXT("open"), currentWord, NULL, NULL, SW_SHOW); _isHotspotDblClicked = true; notifyView->execute(SCI_SETCHARSDEFAULT); } break; } case SCN_NEEDSHOWN : { int begin = notifyView->execute(SCI_LINEFROMPOSITION, notification->position); int end = notifyView->execute(SCI_LINEFROMPOSITION, notification->position + notification->length); int firstLine = begin < end ? begin : end; int lastLine = begin > end ? begin : end; for (int line = firstLine; line <= lastLine; ++line) { notifyView->execute(SCI_ENSUREVISIBLE, line, 0); } break; } case SCN_CALLTIPCLICK: { AutoCompletion * autoC = isFromPrimary?&_autoCompleteMain:&_autoCompleteSub; autoC->callTipClick(notification->position); break; } case RBN_HEIGHTCHANGE: { SendMessage(_pPublicInterface->getHSelf(), WM_SIZE, 0, 0); break; } case RBN_CHEVRONPUSHED: { NMREBARCHEVRON * lpnm = (NMREBARCHEVRON*) notification; ReBar * notifRebar = &_rebarTop; if (_rebarBottom.getHSelf() == lpnm->hdr.hwndFrom) notifRebar = &_rebarBottom; //If N++ ID, use proper object switch(lpnm->wID) { case REBAR_BAR_TOOLBAR: { POINT pt; pt.x = lpnm->rc.left; pt.y = lpnm->rc.bottom; ClientToScreen(notifRebar->getHSelf(), &pt); _toolBar.doPopop(pt); return TRUE; break; } } //Else forward notification to window of rebarband REBARBANDINFO rbBand; ZeroMemory(&rbBand, REBARBAND_SIZE); rbBand.cbSize = REBARBAND_SIZE; rbBand.fMask = RBBIM_CHILD; ::SendMessage(notifRebar->getHSelf(), RB_GETBANDINFO, lpnm->uBand, (LPARAM)&rbBand); ::SendMessage(rbBand.hwndChild, WM_NOTIFY, 0, (LPARAM)lpnm); break; } default : break; } return FALSE; }