void QWinSettingsPrivate::set(const QString &uKey, const QVariant &value) { if (writeHandle() == 0) { setStatus(QSettings::AccessError); return; } QString rKey = escapedKey(uKey); HKEY handle = createOrOpenKey(writeHandle(), registryPermissions, keyPath(rKey)); if (handle == 0) { setStatus(QSettings::AccessError); return; } DWORD type; QByteArray regValueBuff; // Determine the type switch (value.type()) { case QVariant::List: case QVariant::StringList: { // If none of the elements contains '\0', we can use REG_MULTI_SZ, the // native registry string list type. Otherwise we use REG_BINARY. type = REG_MULTI_SZ; QStringList l = variantListToStringList(value.toList()); QStringList::const_iterator it = l.constBegin(); for (; it != l.constEnd(); ++it) { if ((*it).length() == 0 || stringContainsNullChar(*it)) { type = REG_BINARY; break; } } if (type == REG_BINARY) { QString s = variantToString(value); regValueBuff = QByteArray((const char*)s.utf16(), s.length() * 2); } else { QStringList::const_iterator it = l.constBegin(); for (; it != l.constEnd(); ++it) { const QString &s = *it; regValueBuff += QByteArray((const char*)s.utf16(), (s.length() + 1) * 2); } regValueBuff.append((char)0); regValueBuff.append((char)0); } break; } case QVariant::Int: case QVariant::UInt: { type = REG_DWORD; qint32 i = value.toInt(); regValueBuff = QByteArray((const char*)&i, sizeof(qint32)); break; } case QVariant::LongLong: case QVariant::ULongLong: { type = REG_QWORD; qint64 i = value.toLongLong(); regValueBuff = QByteArray((const char*)&i, sizeof(qint64)); break; } case QVariant::ByteArray: // fallthrough intended default: { // If the string does not contain '\0', we can use REG_SZ, the native registry // string type. Otherwise we use REG_BINARY. QString s = variantToString(value); type = stringContainsNullChar(s) ? REG_BINARY : REG_SZ; if (type == REG_BINARY) { regValueBuff = QByteArray((const char*)s.utf16(), s.length() * 2); } else { regValueBuff = QByteArray((const char*)s.utf16(), (s.length() + 1) * 2); } break; } } // set the value LONG res = RegSetValueEx(handle, reinterpret_cast<const wchar_t *>(keyName(rKey).utf16()), 0, type, reinterpret_cast<const unsigned char*>(regValueBuff.constData()), regValueBuff.size()); if (res == ERROR_SUCCESS) { deleteWriteHandleOnExit = false; } else { qWarning("QSettings: failed to set subkey \"%s\": %s", rKey.toLatin1().data(), errorCodeToString(res).toLatin1().data()); setStatus(QSettings::AccessError); } RegCloseKey(handle); }
QString qt_win_get_save_file_name(const QFileDialogArgs &args, QString *initialDirectory, QString *selectedFilter) { QString result; QString isel = args.selection; if (initialDirectory && initialDirectory->left(5) == QLatin1String("file:")) initialDirectory->remove(0, 5); QFileInfo fi(*initialDirectory); if (initialDirectory && !fi.isDir()) { *initialDirectory = fi.absolutePath(); if (isel.isEmpty()) isel = fi.fileName(); } if (!fi.exists()) *initialDirectory = QDir::homePath(); DWORD selFilIdx = 0; int idx = 0; if (selectedFilter) { QStringList filterLst = qt_win_make_filters_list(args.filter); idx = filterLst.indexOf(*selectedFilter); } QDialog modal_widget; modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true); modal_widget.setParent(args.parent, Qt::Window); QApplicationPrivate::enterModal(&modal_widget); bool hideFiltersDetails = args.options & QFileDialog::HideNameFilterDetails; // This block is used below for the lpstrDefExt member. // Note that the current MSDN docs document this member wrong. // It should rather be documented as "the default extension if no extension was given and if the // current filter does not have a extension (e.g (*)). If the current filter have an extension, use // the extension of the current filter" QString defaultSaveExt; if (selectedFilter && !selectedFilter->isEmpty()) { defaultSaveExt = qt_win_extract_filter(*selectedFilter); // make sure we only have the extension int firstDot = defaultSaveExt.indexOf(QLatin1Char('.')); if (firstDot != -1) { defaultSaveExt.remove(0, firstDot + 1); } else { defaultSaveExt.clear(); } } OPENFILENAME *ofn = qt_win_make_OFN(args.parent, args.selection, args.directory, args.caption, qt_win_filter(args.filter, hideFiltersDetails), QFileDialog::AnyFile, args.options); ofn->lpstrDefExt = (wchar_t*)defaultSaveExt.utf16(); if (idx) ofn->nFilterIndex = idx + 1; if (GetSaveFileName(ofn)) { result = QString::fromWCharArray(ofn->lpstrFile); selFilIdx = ofn->nFilterIndex; } qt_win_clean_up_OFN(&ofn); #if defined(Q_WS_WINCE) int semIndex = result.indexOf(QLatin1Char(';')); if (semIndex >= 0) result = result.left(semIndex); #endif QApplicationPrivate::leaveModal(&modal_widget); qt_win_eatMouseMove(); if (result.isEmpty()) return result; fi = result; *initialDirectory = fi.path(); if (selectedFilter) *selectedFilter = qt_win_selected_filter(args.filter, selFilIdx); return fi.absoluteFilePath(); }
QString qt_win_get_existing_directory(const QFileDialogArgs &args) { #ifndef Q_WS_WINCE if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)) return qt_win_CID_get_existing_directory(args); #endif QString currentDir = QDir::currentPath(); QString result; QWidget *parent = args.parent; if (parent) parent = parent->window(); else parent = QApplication::activeWindow(); if (parent) parent->createWinId(); QDialog modal_widget; modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true); modal_widget.setParent(parent, Qt::Window); QApplicationPrivate::enterModal(&modal_widget); QString initDir = QDir::toNativeSeparators(args.directory); wchar_t path[MAX_PATH]; wchar_t initPath[MAX_PATH]; initPath[0] = 0; path[0] = 0; tTitle = args.caption; qt_BROWSEINFO bi; Q_ASSERT(!parent ||parent->testAttribute(Qt::WA_WState_Created)); bi.hwndOwner = (parent ? parent->winId() : 0); bi.pidlRoot = NULL; //### This does not seem to be respected? - the dialog always displays "Browse for folder" bi.lpszTitle = (wchar_t*)tTitle.utf16(); bi.pszDisplayName = initPath; bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT | BIF_NEWDIALOGSTYLE; bi.lpfn = winGetExistDirCallbackProc; bi.lParam = LPARAM(&initDir); qt_win_resolve_libs(); if (ptrSHBrowseForFolder) { qt_LPITEMIDLIST pItemIDList = ptrSHBrowseForFolder(&bi); if (pItemIDList) { ptrSHGetPathFromIDList(pItemIDList, path); IMalloc *pMalloc; if (ptrSHGetMalloc(&pMalloc) == NOERROR) { pMalloc->Free(pItemIDList); pMalloc->Release(); result = QString::fromWCharArray(path); } } } tTitle = QString(); QApplicationPrivate::leaveModal(&modal_widget); qt_win_eatMouseMove(); if (!result.isEmpty()) result.replace(QLatin1Char('\\'), QLatin1Char('/')); return result; }
void WindowsPlatform::syncFolderAdded(QString syncPath, QString syncName, QString syncID) { if (syncPath.startsWith(QString::fromAscii("\\\\?\\"))) { syncPath = syncPath.mid(4); } if (!syncPath.size()) { return; } QDir syncDir(syncPath); if (!syncDir.exists()) { return; } if (!Preferences::instance()->leftPaneIconsDisabled()) { addSyncToLeftPane(syncPath, syncName, syncID); } DWORD dwVersion = GetVersion(); DWORD dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion))); int iconIndex = (dwMajorVersion<6) ? 2 : 3; QString infoTip = QCoreApplication::translate("WindowsPlatform", "MEGA synced folder"); SHFOLDERCUSTOMSETTINGS fcs = {0}; fcs.dwSize = sizeof(SHFOLDERCUSTOMSETTINGS); fcs.dwMask = FCSM_ICONFILE | FCSM_INFOTIP; fcs.pszIconFile = (LPWSTR)MegaApplication::applicationFilePath().utf16(); fcs.iIconIndex = iconIndex; fcs.pszInfoTip = (LPWSTR)infoTip.utf16(); SHGetSetFolderCustomSettings(&fcs, (LPCWSTR)syncPath.utf16(), FCS_FORCEWRITE); WCHAR path[MAX_PATH]; HRESULT res = SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, path); if (res != S_OK) { return; } QString linksPath = QString::fromWCharArray(path); linksPath += QString::fromAscii("\\Links"); QFileInfo info(linksPath); if (!info.isDir()) { return; } QString linkPath = linksPath + QString::fromAscii("\\") + syncName + QString::fromAscii(".lnk"); if (QFile(linkPath).exists()) { return; } WCHAR wDescription[]=L"MEGAsync synchronized folder"; linkPath = QDir::toNativeSeparators(linkPath); WCHAR *wLinkPath = (WCHAR *)linkPath.utf16(); syncPath = QDir::toNativeSeparators(syncPath); WCHAR *wSyncPath = (WCHAR *)syncPath.utf16(); QString exec = MegaApplication::applicationFilePath(); exec = QDir::toNativeSeparators(exec); WCHAR *wExecPath = (WCHAR *)exec.utf16(); res = CreateLink(wSyncPath, wLinkPath, wDescription, wExecPath); SHChangeNotify(SHCNE_CREATE, SHCNF_PATH | SHCNF_FLUSHNOWAIT, wLinkPath, NULL); WCHAR *wLinksPath = (WCHAR *)linksPath.utf16(); SHChangeNotify(SHCNE_UPDATEDIR, SHCNF_PATH | SHCNF_FLUSHNOWAIT, wLinksPath, NULL); SHChangeNotify(SHCNE_UPDATEITEM, SHCNF_PATH | SHCNF_FLUSHNOWAIT, syncPath.utf16(), NULL); }
void QProcessPrivate::startProcess() { Q_Q(QProcess); bool success = false; if (pid) { CloseHandle(pid->hThread); CloseHandle(pid->hProcess); delete pid; pid = 0; } pid = new PROCESS_INFORMATION; memset(pid, 0, sizeof(PROCESS_INFORMATION)); q->setProcessState(QProcess::Starting); if (!createChannel(stdinChannel) || !createChannel(stdoutChannel) || !createChannel(stderrChannel)) return; QString args = qt_create_commandline(program, arguments); QByteArray envlist; if (environment.d.constData()) envlist = qt_create_environment(environment.d.constData()->hash); if (!nativeArguments.isEmpty()) { if (!args.isEmpty()) args += QLatin1Char(' '); args += nativeArguments; } #if defined QPROCESS_DEBUG qDebug("Creating process"); qDebug(" program : [%s]", program.toLatin1().constData()); qDebug(" args : %s", args.toLatin1().constData()); qDebug(" pass environment : %s", environment.isEmpty() ? "no" : "yes"); #endif // We cannot unconditionally set the CREATE_NO_WINDOW flag, because this // will render the stdout/stderr handles connected to a console useless // (this typically affects ForwardedChannels mode). // However, we also do not want console tools launched from a GUI app to // create new console windows (behavior consistent with UNIX). DWORD dwCreationFlags = (GetConsoleWindow() ? 0 : CREATE_NO_WINDOW); dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT; STARTUPINFOW startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, 0, 0, 0, STARTF_USESTDHANDLES, 0, 0, 0, stdinChannel.pipe[0], stdoutChannel.pipe[1], stderrChannel.pipe[1] }; success = CreateProcess(0, (wchar_t*)args.utf16(), 0, 0, TRUE, dwCreationFlags, environment.isEmpty() ? 0 : envlist.data(), workingDirectory.isEmpty() ? 0 : (wchar_t*)QDir::toNativeSeparators(workingDirectory).utf16(), &startupInfo, pid); if (!success) { // Capture the error string before we do CloseHandle below q->setErrorString(QProcess::tr("Process failed to start: %1").arg(qt_error_string())); } if (stdinChannel.pipe[0] != INVALID_Q_PIPE) { CloseHandle(stdinChannel.pipe[0]); stdinChannel.pipe[0] = INVALID_Q_PIPE; } if (stdoutChannel.pipe[1] != INVALID_Q_PIPE) { CloseHandle(stdoutChannel.pipe[1]); stdoutChannel.pipe[1] = INVALID_Q_PIPE; } if (stderrChannel.pipe[1] != INVALID_Q_PIPE) { CloseHandle(stderrChannel.pipe[1]); stderrChannel.pipe[1] = INVALID_Q_PIPE; } if (!success) { cleanup(); processError = QProcess::FailedToStart; emit q->error(processError); q->setProcessState(QProcess::NotRunning); return; } q->setProcessState(QProcess::Running); // User can call kill()/terminate() from the stateChanged() slot // so check before proceeding if (!pid) return; if (threadData->hasEventDispatcher()) { processFinishedNotifier = new QWinEventNotifier(pid->hProcess, q); QObject::connect(processFinishedNotifier, SIGNAL(activated(HANDLE)), q, SLOT(_q_processDied())); processFinishedNotifier->setEnabled(true); notifier = new QTimer(q); QObject::connect(notifier, SIGNAL(timeout()), q, SLOT(_q_notified())); notifier->start(NOTIFYTIMEOUT); } _q_startupNotification(); }
static void qt_wce_insert_action(HMENU menu, QWceMenuAction *action) { Q_ASSERT_X(menu, "AppendMenu", "menu is 0"); if (action->action->isVisible()) { int flags; action->action->isEnabled() ? flags = MF_ENABLED : flags = MF_GRAYED; QString text = action->action->iconText(); text.remove(QChar::fromLatin1('&')); if (action->action->isSeparator()) { AppendMenu (menu, MF_SEPARATOR , 0, 0); } else if (action->action->menu()) { text.remove(QChar::fromLatin1('&')); AppendMenu (menu, MF_STRING | flags | MF_POPUP, (UINT) action->action->menu()->wceMenu(), reinterpret_cast<const wchar_t *> (text.utf16())); } else { AppendMenu (menu, MF_STRING | flags, action->command, reinterpret_cast<const wchar_t *> (text.utf16())); } if (action->action->isCheckable()) if (action->action->isChecked()) CheckMenuItem(menu, action->command, MF_BYCOMMAND | MF_CHECKED); else CheckMenuItem(menu, action->command, MF_BYCOMMAND | MF_UNCHECKED); } }
DocumentManager::instance()->recentFileManager()->addRecent(fileName); } connect(DocumentManager::instance(), SIGNAL(documentChanged()), SLOT(resetWindowTitle())); connect(DocumentManager::instance(), SIGNAL(documentSaved()), SLOT(resetWindowTitle())); QDeclarativeView* view = new SketchDeclarativeView(); QmlGlobalEngine::instance()->setEngine(view->engine()); view->engine()->rootContext()->setContextProperty("mainWindow", this); #ifdef Q_OS_WIN QDir appdir(qApp->applicationDirPath()); // Corrects for mismatched case errors in path (qtdeclarative fails to load) wchar_t buffer[1024]; QString absolute = appdir.absolutePath(); DWORD rv = ::GetShortPathName((wchar_t*)absolute.utf16(), buffer, 1024); rv = ::GetLongPathName(buffer, buffer, 1024); QString correctedPath((QChar *)buffer); appdir.setPath(correctedPath); // for now, the app in bin/ and we still use the env.bat script appdir.cdUp(); view->engine()->addImportPath(appdir.canonicalPath() + "/lib/calligra/imports"); view->engine()->addImportPath(appdir.canonicalPath() + "/lib64/calligra/imports"); QString mainqml = appdir.canonicalPath() + "/share/apps/kritasketch/kritasketch.qml"; #else view->engine()->addImportPath(KoResourcePaths::findDirs("lib", "calligra/imports").value(0)); QString mainqml = KoResourcePaths::findResource("data", "kritasketch/kritasketch.qml"); #endif
bool QSharedMemoryPrivate::create(int size) { // Get a windows acceptable key QString safeKey = makePlatformSafeKey(key); QString function = QLatin1String("QSharedMemory::create"); if (safeKey.isEmpty()) { error = QSharedMemory::KeyError; errorString = QSharedMemory::tr("%1: key error").arg(function); return false; } // Create the file mapping. hand = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, size, (wchar_t*)safeKey.utf16()); setErrorString(function); // hand is valid when it already exists unlike unix so explicitly check if (error == QSharedMemory::AlreadyExists || !hand) return false; return true; }
void QProcessPrivate::startProcess() { Q_Q(QProcess); bool success = false; if (pid) { CloseHandle(pid->hThread); CloseHandle(pid->hProcess); delete pid; pid = 0; } pid = new PROCESS_INFORMATION; memset(pid, 0, sizeof(PROCESS_INFORMATION)); q->setProcessState(QProcess::Starting); if (!createChannel(stdinChannel) || !createChannel(stdoutChannel) || !createChannel(stderrChannel)) return; #if defined(Q_OS_WINCE) QString args = qt_create_commandline(QString(), arguments); #else QString args = qt_create_commandline(program, arguments); QByteArray envlist; if (environment.d.constData()) envlist = qt_create_environment(environment.d.constData()->hash); #endif if (!nativeArguments.isEmpty()) { if (!args.isEmpty()) args += QLatin1Char(' '); args += nativeArguments; } #if defined QPROCESS_DEBUG qDebug("Creating process"); qDebug(" program : [%s]", program.toLatin1().constData()); qDebug(" args : %s", args.toLatin1().constData()); qDebug(" pass environment : %s", environment.isEmpty() ? "no" : "yes"); #endif #if defined(Q_OS_WINCE) QString fullPathProgram = program; if (!QDir::isAbsolutePath(fullPathProgram)) fullPathProgram = QFileInfo(fullPathProgram).absoluteFilePath(); fullPathProgram.replace(QLatin1Char('/'), QLatin1Char('\\')); success = CreateProcess((wchar_t*)fullPathProgram.utf16(), (wchar_t*)args.utf16(), 0, 0, false, 0, 0, 0, 0, pid); #else DWORD dwCreationFlags = CREATE_NO_WINDOW; dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT; STARTUPINFOW startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, 0, 0, 0, STARTF_USESTDHANDLES, 0, 0, 0, stdinChannel.pipe[0], stdoutChannel.pipe[1], stderrChannel.pipe[1] }; success = CreateProcess(0, (wchar_t*)args.utf16(), 0, 0, TRUE, dwCreationFlags, environment.isEmpty() ? 0 : envlist.data(), workingDirectory.isEmpty() ? 0 : (wchar_t*)QDir::toNativeSeparators(workingDirectory).utf16(), &startupInfo, pid); if (!success) { // Capture the error string before we do CloseHandle below q->setErrorString(QProcess::tr("Process failed to start: %1").arg(qt_error_string())); } if (stdinChannel.pipe[0] != INVALID_Q_PIPE) { CloseHandle(stdinChannel.pipe[0]); stdinChannel.pipe[0] = INVALID_Q_PIPE; } if (stdoutChannel.pipe[1] != INVALID_Q_PIPE) { CloseHandle(stdoutChannel.pipe[1]); stdoutChannel.pipe[1] = INVALID_Q_PIPE; } if (stderrChannel.pipe[1] != INVALID_Q_PIPE) { CloseHandle(stderrChannel.pipe[1]); stderrChannel.pipe[1] = INVALID_Q_PIPE; } #endif // Q_OS_WINCE if (!success) { cleanup(); processError = QProcess::FailedToStart; emit q->error(processError); q->setProcessState(QProcess::NotRunning); return; } q->setProcessState(QProcess::Running); // User can call kill()/terminate() from the stateChanged() slot // so check before proceeding if (!pid) return; if (threadData->eventDispatcher) { processFinishedNotifier = new QWinEventNotifier(pid->hProcess, q); QObject::connect(processFinishedNotifier, SIGNAL(activated(HANDLE)), q, SLOT(_q_processDied())); processFinishedNotifier->setEnabled(true); notifier = new QTimer(q); QObject::connect(notifier, SIGNAL(timeout()), q, SLOT(_q_notified())); notifier->start(NOTIFYTIMEOUT); } // give the process a chance to start ... Sleep(SLEEPMIN * 2); _q_startupNotification(); }
bool isCDDevice(QString drive) { unsigned int r = GetDriveTypeW((LPCWSTR) drive.utf16()); qDebug("isCDDevice: '%s' r: %d", drive.toUtf8().data(), r); return (r == DRIVE_CDROM); }
void QAccessibleWidgetEx_QtDShell::setText(QAccessible::Text t0, int child1, const QString& text2) { qtd_QAccessibleInterface_setText_Text_int_string_dispatch(this->dId, (QAccessible::Text )t0, (int )child1, text2.utf16(), text2.size()); }
/*! Executes the command described in \a arguments, in the environment inherited from the parent process, with the \a additionalEnv settings applied. \a removeEnv removes the specified environment variables from the environment of the executed process. Returns the exit value of the process, or -1 if the command could not be executed. This function uses _(w)spawnvpe to spawn a process by searching through the PATH environment variable. */ int Environment::execute(QStringList arguments, const QStringList &additionalEnv, const QStringList &removeEnv) { #ifdef CONFIGURE_DEBUG_EXECUTE qDebug() << "About to Execute: " << arguments; qDebug() << " " << QDir::currentPath(); qDebug() << " " << additionalEnv; qDebug() << " " << removeEnv; #endif // Create the full environment from the current environment and // the additionalEnv strings, then remove all variables defined // in removeEnv QMap<QString, QString> fullEnvMap; LPWSTR envStrings = GetEnvironmentStrings(); if (envStrings) { int strLen = 0; for (LPWSTR envString = envStrings; *(envString); envString += strLen + 1) { strLen = wcslen(envString); QString str = QString((const QChar*)envString, strLen); if (!str.startsWith("=")) { // These are added by the system int sepIndex = str.indexOf('='); fullEnvMap.insert(str.left(sepIndex).toUpper(), str.mid(sepIndex +1)); } } } FreeEnvironmentStrings(envStrings); // Add additionalEnv variables for (int i = 0; i < additionalEnv.count(); ++i) { const QString &str = additionalEnv.at(i); int sepIndex = str.indexOf('='); fullEnvMap.insert(str.left(sepIndex).toUpper(), str.mid(sepIndex +1)); } // Remove removeEnv variables for (int j = 0; j < removeEnv.count(); ++j) fullEnvMap.remove(removeEnv.at(j).toUpper()); // Add all variables to a QStringList QStringList fullEnv; QMapIterator<QString, QString> it(fullEnvMap); while (it.hasNext()) { it.next(); fullEnv += QString(it.key() + "=" + it.value()); } // ---------------------------- QString program = arguments.takeAt(0); QString args = qt_create_commandline(program, arguments); QByteArray envlist = qt_create_environment(fullEnv); DWORD exitCode = -1; PROCESS_INFORMATION procInfo; memset(&procInfo, 0, sizeof(procInfo)); STARTUPINFO startInfo; memset(&startInfo, 0, sizeof(startInfo)); startInfo.cb = sizeof(startInfo); bool couldExecute = CreateProcess(0, (wchar_t*)args.utf16(), 0, 0, true, CREATE_UNICODE_ENVIRONMENT, envlist.isEmpty() ? 0 : envlist.data(), 0, &startInfo, &procInfo); if (couldExecute) { WaitForSingleObject(procInfo.hProcess, INFINITE); GetExitCodeProcess(procInfo.hProcess, &exitCode); CloseHandle(procInfo.hThread); CloseHandle(procInfo.hProcess); } if (exitCode == -1) { switch(GetLastError()) { case E2BIG: cerr << "execute: Argument list exceeds 1024 bytes" << endl; foreach(QString arg, arguments) cerr << " (" << arg.toLocal8Bit().constData() << ")" << endl; break; case ENOENT: cerr << "execute: File or path is not found (" << program.toLocal8Bit().constData() << ")" << endl; break; case ENOEXEC: cerr << "execute: Specified file is not executable or has invalid executable-file format (" << program.toLocal8Bit().constData() << ")" << endl; break; case ENOMEM: cerr << "execute: Not enough memory is available to execute new process." << endl; break; default: cerr << "execute: Unknown error" << endl; foreach(QString arg, arguments) cerr << " (" << arg.toLocal8Bit().constData() << ")" << endl; break; } } return exitCode; }
string real_path(string const & path) { // See http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx QString const qpath = get_long_path(toqstr(path)); HANDLE hpath = CreateFileW((wchar_t *) qpath.utf16(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (hpath == INVALID_HANDLE_VALUE) { // The file cannot be accessed. return path; } // Get the file size. DWORD size_hi = 0; DWORD size_lo = GetFileSize(hpath, &size_hi); if (size_lo == 0 && size_hi == 0) { // A zero-length file cannot be mapped. CloseHandle(hpath); return path; } // Create a file mapping object. HANDLE hmap = CreateFileMapping(hpath, NULL, PAGE_READONLY, 0, 1, NULL); if (!hmap) { CloseHandle(hpath); return path; } // Create a file mapping to get the file name. void * pmem = MapViewOfFile(hmap, FILE_MAP_READ, 0, 0, 1); if (!pmem) { CloseHandle(hmap); CloseHandle(hpath); return path; } TCHAR realpath[MAX_PATH + 1]; if (!GetMappedFileName(GetCurrentProcess(), pmem, realpath, MAX_PATH)) { UnmapViewOfFile(pmem); CloseHandle(hmap); CloseHandle(hpath); return path; } // Translate device name to UNC prefix or drive letters. TCHAR tmpbuf[MAX_PATH] = TEXT("\\Device\\Mup\\"); UINT namelen = _tcslen(tmpbuf); if (_tcsnicmp(realpath, tmpbuf, namelen) == 0) { // UNC path _snprintf(tmpbuf, MAX_PATH, "\\\\%s", realpath + namelen); strncpy(realpath, tmpbuf, MAX_PATH); realpath[MAX_PATH] = '\0'; } else if (GetLogicalDriveStrings(MAX_PATH - 1, tmpbuf)) { // Check whether device name corresponds to some local drive. TCHAR name[MAX_PATH]; TCHAR drive[3] = TEXT(" :"); bool found = false; TCHAR * p = tmpbuf; do { // Copy the drive letter to the template string drive[0] = *p; // Look up each device name if (QueryDosDevice(drive, name, MAX_PATH)) { namelen = _tcslen(name); if (namelen < MAX_PATH) { found = _tcsnicmp(realpath, name, namelen) == 0; if (found) { // Repl. device spec with drive TCHAR tempfile[MAX_PATH]; _snprintf(tempfile, MAX_PATH, "%s%s", drive, realpath + namelen); strncpy(realpath, tempfile, MAX_PATH); realpath[MAX_PATH] = '\0'; } } } // Advance p to the next NULL character. while (*p++) ; } while (!found && *p); } UnmapViewOfFile(pmem); CloseHandle(hmap); CloseHandle(hpath); string const retpath = subst(string(realpath), '\\', '/'); return FileName::fromFilesystemEncoding(retpath).absFileName(); }
QPair<QString,QString> pathOwnerDomain( const QString & _path, QString * errorMessage ) { DWORD dwRtnCode = 0; PSID pSidOwner = NULL; BOOL bRtnBool = TRUE; LPTSTR AcctName = 0, DomainName = 0; DWORD dwAcctName = 1, dwDomainName = 1; SID_NAME_USE eUse = SidTypeUnknown; HANDLE hFile; PSECURITY_DESCRIPTOR pSD = NULL; QString host; LPTSTR fileHost = 0; QString path(_path); path.replace( "/", "\\" ); // Get the handle of the file or path hFile = CreateFile( (WCHAR*)path.utf16(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); // Check GetLastError for CreateFile error code. if (hFile == INVALID_HANDLE_VALUE) { if( errorMessage ) *errorMessage = QString( "Error opening file to get security info: %1" ).arg( GetLastError() ); return qMakePair(QString(),QString()); } // Get the owner SID of the file. dwRtnCode = GetSecurityInfo( hFile, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, &pSidOwner, NULL, NULL, NULL, &pSD); // Check GetLastError for GetSecurityInfo error condition. if (dwRtnCode != ERROR_SUCCESS) { if( errorMessage ) *errorMessage = QString( "GetSecurityInfo failed: %1" ).arg( GetLastError() ); CloseHandle(hFile); return qMakePair(QString(),QString()); } if( path.startsWith( "\\\\" ) ) host = hostFromUnc( path ); else host = hostFromUnc( driveMapping( path[0].toLatin1() ) ); if( !host.isEmpty() ) fileHost = (LPTSTR)host.utf16(); // First call to LookupAccountSid to get the buffer sizes. bRtnBool = LookupAccountSid( fileHost /* local computer */, pSidOwner, AcctName, (LPDWORD)&dwAcctName, DomainName, (LPDWORD)&dwDomainName, &eUse); // Allocate memory for the buffers. AcctName = (LPTSTR)GlobalAlloc( GMEM_FIXED, dwAcctName * sizeof(TCHAR)); if( dwDomainName ) DomainName = (LPTSTR)GlobalAlloc( GMEM_FIXED, dwDomainName * sizeof(TCHAR) ); // Check GetLastError for GlobalAlloc error condition. if (AcctName == NULL || (dwDomainName && !DomainName)) { if( errorMessage ) *errorMessage = QString( "Failed to allocate space for LookupAccountSid: %1" ).arg( GetLastError() ); GlobalFree((HGLOBAL)AcctName); GlobalFree((HGLOBAL)DomainName); CloseHandle(hFile); LocalFree(pSD); return qMakePair(QString(),QString()); } // Second call to LookupAccountSid to get the account name. bRtnBool = LookupAccountSid( fileHost /* local computer */, pSidOwner, AcctName, (LPDWORD)&dwAcctName, DomainName, (LPDWORD)&dwDomainName, &eUse); // Check GetLastError for LookupAccountSid error condition. if (bRtnBool == FALSE) { if( errorMessage ) { DWORD dwErrorCode = GetLastError(); if (dwErrorCode == ERROR_NONE_MAPPED) *errorMessage = QString( "Account owner not found for specified SID." ); else *errorMessage = QString( "Failed to allocate space for LookupAccountSid: %1" ).arg( dwErrorCode ); } GlobalFree((HGLOBAL)AcctName); GlobalFree((HGLOBAL)DomainName); CloseHandle(hFile); LocalFree(pSD); return qMakePair(QString(),QString()); } QPair<QString,QString> ret = qMakePair( QString::fromWCharArray( AcctName ), QString::fromWCharArray( DomainName ) ); GlobalFree((HGLOBAL)AcctName); GlobalFree((HGLOBAL)DomainName); CloseHandle(hFile); LocalFree(pSD); return ret; }
QRect QCommonStyle_QtDShell::itemTextRect(const QFontMetrics& fm0, const QRect& r1, int flags2, bool enabled3, const QString& text4) const { QRect __d_return_value; qtd_QStyle_itemTextRect_QFontMetrics_QRect_int_bool_string_const_dispatch(QObjectLink::getLink(this)->dId, &__d_return_value, &(QFontMetrics& )fm0, &(QRect& )r1, (int )flags2, (bool )enabled3, text4.utf16(), text4.size()); return __d_return_value; }
#else return false; #endif } QTCREATOR_UTILS_EXPORT bool is64BitWindowsBinary(const QString &binaryIn) { QTC_ASSERT(!binaryIn.isEmpty(), return false); #ifdef Q_OS_WIN32 # ifdef __GNUC__ // MinGW lacking some definitions/winbase.h # define SCS_64BIT_BINARY 6 # endif bool isAmd64 = false; DWORD binaryType = 0; const QString binary = QDir::toNativeSeparators(binaryIn); bool success = GetBinaryTypeW(reinterpret_cast<const TCHAR*>(binary.utf16()), &binaryType) != 0; if (success && binaryType == SCS_64BIT_BINARY) isAmd64=true; return isAmd64; #else return false; #endif } WindowsCrashDialogBlocker::WindowsCrashDialogBlocker() #ifdef Q_OS_WIN : silenceErrorMode(SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS), originalErrorMode(SetErrorMode(silenceErrorMode)) #endif { }
QString Q3FileDialog::winGetExistingDirectory(const QString& initialDirectory, QWidget *parent, const char* /*name*/, const QString& caption) { #ifndef Q_OS_WINCE QString currentDir = QDir::currentDirPath(); QString result; if (parent) parent = parent->window(); else parent = qApp->activeWindow(); QString title = caption; if (title.isNull()) title = tr("Select a Directory"); if (parent) { QEvent e(QEvent::WindowBlocked); QApplication::sendEvent(parent, &e); QApplicationPrivate::enterModal(parent); } QString initDir = QDir::toNativeSeparators(initialDirectory); wchar_t path[MAX_PATH]; wchar_t initPath[MAX_PATH]; initPath[0] = 0; path[0] = 0; tTitle = title; BROWSEINFO bi; bi.hwndOwner = (parent ? parent->winId() : 0); bi.pidlRoot = NULL; bi.lpszTitle = (wchar_t*)tTitle.utf16(); bi.pszDisplayName = initPath; bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT | BIF_NEWDIALOGSTYLE; bi.lpfn = winGetExistDirCallbackProc; bi.lParam = Q_ULONG(&initDir); LPITEMIDLIST pItemIDList = SHBrowseForFolder(&bi); if (pItemIDList) { SHGetPathFromIDList(pItemIDList, path); IMalloc *pMalloc; if (SHGetMalloc(&pMalloc) != NOERROR) result.clear(); else { pMalloc->Free(pItemIDList); pMalloc->Release(); result = QString::fromWCharArray(path); } } else result.clear(); tTitle.clear(); if (parent) { QApplicationPrivate::leaveModal(parent); QEvent e(QEvent::WindowUnblocked); QApplication::sendEvent(parent, &e); } if (!result.isEmpty()) result.replace(QLatin1Char('\\'), QLatin1Char('/')); return result; #else return QString(); #endif }
QTCREATOR_UTILS_EXPORT QString winGetDLLVersion(WinDLLVersionType t, const QString &name, QString *errorMessage) { #ifdef Q_OS_WIN // Resolve required symbols from the version.dll typedef DWORD (APIENTRY *GetFileVersionInfoSizeProtoType)(LPCTSTR, LPDWORD); typedef BOOL (APIENTRY *GetFileVersionInfoWProtoType)(LPCWSTR, DWORD, DWORD, LPVOID); typedef BOOL (APIENTRY *VerQueryValueWProtoType)(const LPVOID, LPWSTR lpSubBlock, LPVOID, PUINT); const char *versionDLLC = "version.dll"; QLibrary versionLib(QLatin1String(versionDLLC), 0); if (!versionLib.load()) { *errorMessage = msgCannotLoad(versionDLLC, versionLib.errorString()); return QString(); } // MinGW requires old-style casts GetFileVersionInfoSizeProtoType getFileVersionInfoSizeW = (GetFileVersionInfoSizeProtoType)(versionLib.resolve("GetFileVersionInfoSizeW")); GetFileVersionInfoWProtoType getFileVersionInfoW = (GetFileVersionInfoWProtoType)(versionLib.resolve("GetFileVersionInfoW")); VerQueryValueWProtoType verQueryValueW = (VerQueryValueWProtoType)(versionLib.resolve("VerQueryValueW")); if (!getFileVersionInfoSizeW || !getFileVersionInfoW || !verQueryValueW) { *errorMessage = msgCannotResolve(versionDLLC); return QString(); } // Now go ahead, read version info resource DWORD dummy = 0; const LPCTSTR fileName = reinterpret_cast<LPCTSTR>(name.utf16()); // MinGWsy const DWORD infoSize = (*getFileVersionInfoSizeW)(fileName, &dummy); if (infoSize == 0) { *errorMessage = QString::fromLatin1("Unable to determine the size of the version information of %1: %2").arg(name, winErrorMessage(GetLastError())); return QString(); } QByteArray dataV(infoSize + 1, '\0'); char *data = dataV.data(); if (!(*getFileVersionInfoW)(fileName, dummy, infoSize, data)) { *errorMessage = QString::fromLatin1("Unable to determine the version information of %1: %2").arg(name, winErrorMessage(GetLastError())); return QString(); } VS_FIXEDFILEINFO *versionInfo; const LPCWSTR backslash = TEXT("\\"); UINT len = 0; if (!(*verQueryValueW)(data, const_cast<LPWSTR>(backslash), &versionInfo, &len)) { *errorMessage = QString::fromLatin1("Unable to determine version string of %1: %2").arg(name, winErrorMessage(GetLastError())); return QString(); } QString rc; switch (t) { case WinDLLFileVersion: QTextStream(&rc) << HIWORD(versionInfo->dwFileVersionMS) << '.' << LOWORD(versionInfo->dwFileVersionMS); break; case WinDLLProductVersion: QTextStream(&rc) << HIWORD(versionInfo->dwProductVersionMS) << '.' << LOWORD(versionInfo->dwProductVersionMS); break; } return rc; #endif Q_UNUSED(t); Q_UNUSED(name); Q_UNUSED(errorMessage); return QString(); }
QVariant QSystemLocalePrivate::toCurrencyString(const QSystemLocale::CurrencyToStringArgument &arg) { QString value; switch (arg.value.type()) { case QVariant::Int: value = QLocaleData::longLongToString(QLatin1Char('0'), QLatin1Char(','), QLatin1Char('+'), QLatin1Char('-'), arg.value.toInt(), -1, 10, -1, QLocale::OmitGroupSeparator); break; case QVariant::UInt: value = QLocaleData::unsLongLongToString(QLatin1Char('0'), QLatin1Char(','), QLatin1Char('+'), arg.value.toUInt(), -1, 10, -1, QLocale::OmitGroupSeparator); break; case QVariant::Double: value = QLocaleData::doubleToString(QLatin1Char('0'), QLatin1Char('+'), QLatin1Char('-'), QLatin1Char(' '), QLatin1Char(','), QLatin1Char('.'), arg.value.toDouble(), -1, QLocaleData::DFDecimal, -1, QLocale::OmitGroupSeparator); break; case QVariant::LongLong: value = QLocaleData::longLongToString(QLatin1Char('0'), QLatin1Char(','), QLatin1Char('+'), QLatin1Char('-'), arg.value.toLongLong(), -1, 10, -1, QLocale::OmitGroupSeparator); break; case QVariant::ULongLong: value = QLocaleData::unsLongLongToString(QLatin1Char('0'), QLatin1Char(','), QLatin1Char('+'), arg.value.toULongLong(), -1, 10, -1, QLocale::OmitGroupSeparator); break; default: return QVariant(); } QVarLengthArray<wchar_t, 64> out(64); QString decimalSep; QString thousandSep; CURRENCYFMT format; CURRENCYFMT *pformat = NULL; if (!arg.symbol.isEmpty()) { format.NumDigits = getLocaleInfo_int(LOCALE_ICURRDIGITS); format.LeadingZero = getLocaleInfo_int(LOCALE_ILZERO); decimalSep = getLocaleInfo(LOCALE_SMONDECIMALSEP); format.lpDecimalSep = (wchar_t *)decimalSep.utf16(); thousandSep = getLocaleInfo(LOCALE_SMONTHOUSANDSEP); format.lpThousandSep = (wchar_t *)thousandSep.utf16(); format.NegativeOrder = getLocaleInfo_int(LOCALE_INEGCURR); format.PositiveOrder = getLocaleInfo_int(LOCALE_ICURRENCY); format.lpCurrencySymbol = (wchar_t *)arg.symbol.utf16(); // grouping is complicated and ugly: // int(0) == "123456789.00" == string("0") // int(3) == "123,456,789.00" == string("3;0") // int(30) == "123456,789.00" == string("3;0;0") // int(32) == "12,34,56,789.00" == string("3;2;0") // int(320)== "1234,56,789.00" == string("3;2") QString groupingStr = getLocaleInfo(LOCALE_SMONGROUPING); format.Grouping = groupingStr.remove(QLatin1Char(';')).toInt(); if (format.Grouping % 10 == 0) // magic format.Grouping /= 10; else format.Grouping *= 10; pformat = &format; } int ret = getCurrencyFormat(0, reinterpret_cast<const wchar_t *>(value.utf16()), pformat, out.data(), out.size()); if (ret == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER) { ret = getCurrencyFormat(0, reinterpret_cast<const wchar_t *>(value.utf16()), pformat, out.data(), 0); out.resize(ret); getCurrencyFormat(0, reinterpret_cast<const wchar_t *>(value.utf16()), pformat, out.data(), out.size()); } value = QString::fromWCharArray(out.data()); if (substitution() == SAlways) substituteDigits( value); return value; }
void QAccessible::updateAccessibility(QObject *o, int who, Event reason) { Q_ASSERT(o); if (updateHandler) { updateHandler(o, who, reason); return; } QString soundName; switch (reason) { case PopupMenuStart: soundName = QLatin1String("MenuPopup"); break; case MenuCommand: soundName = QLatin1String("MenuCommand"); break; case Alert: { #ifndef QT_NO_MESSAGEBOX QMessageBox *mb = qobject_cast<QMessageBox*>(o); if (mb) { switch (mb->icon()) { case QMessageBox::Warning: soundName = QLatin1String("SystemExclamation"); break; case QMessageBox::Critical: soundName = QLatin1String("SystemHand"); break; case QMessageBox::Information: soundName = QLatin1String("SystemAsterisk"); break; default: break; } } else #endif // QT_NO_MESSAGEBOX { soundName = QLatin1String("SystemAsterisk"); } } break; default: break; } if (soundName.size()) { #ifndef QT_NO_SETTINGS QSettings settings(QLatin1String("HKEY_CURRENT_USER\\AppEvents\\Schemes\\Apps\\.Default\\") + soundName, QSettings::NativeFormat); QString file = settings.value(QLatin1String(".Current/.")).toString(); #else QString file; #endif if (!file.isEmpty()) { PlaySound(reinterpret_cast<const wchar_t *>(soundName.utf16()), 0, SND_ALIAS | SND_ASYNC | SND_NODEFAULT | SND_NOWAIT); } } if (!isActive()) return; typedef void (WINAPI *PtrNotifyWinEvent)(DWORD, HWND, LONG, LONG); #if defined(Q_WS_WINCE) // ### TODO: check for NotifyWinEvent in CE 6.0 // There is no user32.lib nor NotifyWinEvent for CE return; #else static PtrNotifyWinEvent ptrNotifyWinEvent = 0; static bool resolvedNWE = false; if (!resolvedNWE) { ptrNotifyWinEvent = (PtrNotifyWinEvent)QSystemLibrary::resolve(QLatin1String("user32"), "NotifyWinEvent"); resolvedNWE = true; } if (!ptrNotifyWinEvent) return; // An event has to be associated with a window, // so find the first parent that is a widget. QWidget *w = 0; QObject *p = o; do { if (p->isWidgetType()) { w = static_cast<QWidget*>(p); if (w->internalWinId()) break; } if (QGraphicsObject *gfxObj = qobject_cast<QGraphicsObject*>(p)) { QGraphicsItem *parentItem = gfxObj->parentItem(); if (parentItem) { p = parentItem->toGraphicsObject(); } else { QGraphicsView *view = 0; if (QGraphicsScene *scene = gfxObj->scene()) { QWidget *fw = QApplication::focusWidget(); const QList<QGraphicsView*> views = scene->views(); for (int i = 0 ; i < views.count() && view != fw; ++i) { view = views.at(i); } } p = view; } } else { p = p->parent(); } } while (p); //qDebug() << "updateAccessibility(), hwnd:" << w << ", object:" << o << "," << eventString(reason); if (!w) { if (reason != QAccessible::ContextHelpStart && reason != QAccessible::ContextHelpEnd) w = QApplication::focusWidget(); if (!w) { w = QApplication::activeWindow(); if (!w) return; // ### Fixme // if (!w) { // w = qApp->mainWidget(); // if (!w) // return; // } } } WId wid = w->internalWinId(); if (reason != MenuCommand) { // MenuCommand is faked if (w != o) { // See comment "SENDING EVENTS TO OBJECTS WITH NO WINDOW HANDLE" if (reason != QAccessible::ObjectDestroyed) { /* In some rare occasions, the server (Qt) might get a ::get_accChild call with a childId that references an entry in the cache where there was a dangling QObject-pointer. Previously we crashed on this. There is no point in actually notifying the AT client that the object got destroyed, because the AT client won't query for get_accChild if the event is ObjectDestroyed anyway, and we have no other way of mapping the eventId argument to the actual child/descendant object. (Firefox seems to simply completely ignore EVENT_OBJECT_DESTROY). We therefore guard each QObject in the cache with a QPointer, and only notify the AT client if the type is not ObjectDestroyed. */ eventNum %= 50; //[0..49] int eventId = - eventNum - 1; qAccessibleRecentSentEvents()->insert(eventId, qMakePair(QPointer<QObject>(o), who)); ptrNotifyWinEvent(reason, wid, OBJID_CLIENT, eventId ); ++eventNum; } } else { ptrNotifyWinEvent(reason, wid, OBJID_CLIENT, who); } } #endif // Q_WS_WINCE }
void WindowsPlatform::addSyncToLeftPane(QString syncPath, QString syncName, QString uuid) { typedef LONG MEGANTSTATUS; typedef struct _MEGAOSVERSIONINFOW { DWORD dwOSVersionInfoSize; DWORD dwMajorVersion; DWORD dwMinorVersion; DWORD dwBuildNumber; DWORD dwPlatformId; WCHAR szCSDVersion[ 128 ]; // Maintenance string for PSS usage } MEGARTL_OSVERSIONINFOW, *PMEGARTL_OSVERSIONINFOW; typedef MEGANTSTATUS (WINAPI* RtlGetVersionPtr)(PMEGARTL_OSVERSIONINFOW); MEGARTL_OSVERSIONINFOW version = { 0 }; HMODULE hMod = GetModuleHandleW(L"ntdll.dll"); if (!hMod) { return; } RtlGetVersionPtr RtlGetVersion = (RtlGetVersionPtr)GetProcAddress(hMod, "RtlGetVersion"); if (!RtlGetVersion) { return; } RtlGetVersion(&version); if (version.dwMajorVersion < 10) { return; } DWORD value; QString sValue; QString key = QString::fromUtf8("Software\\Classes\\CLSID\\%1").arg(uuid); REGSAM samDesired = 0; int it = 1; if (IsWow64()) { samDesired = KEY_WOW64_64KEY; it++; } for (int i = 0; i < it; i++) { sValue = syncName; SetRegistryKeyAndValue(HKEY_CURRENT_USER, (LPTSTR)key.utf16(), REG_SZ, L"", (const BYTE *)sValue.utf16(), sValue.size() * 2, samDesired); sValue = MegaApplication::applicationFilePath(); SetRegistryKeyAndValue(HKEY_CURRENT_USER, (LPTSTR)(key + QString::fromUtf8("\\DefaultIcon")).utf16(), REG_EXPAND_SZ, L"", (const BYTE *)sValue.utf16(), sValue.size() * 2, samDesired); value = 0x1; SetRegistryKeyAndValue(HKEY_CURRENT_USER, (LPTSTR)key.utf16(), REG_DWORD, L"System.IsPinnedToNameSpaceTree", (const BYTE *)&value, sizeof(DWORD), samDesired); value = 0x0; SetRegistryKeyAndValue(HKEY_CURRENT_USER, (LPTSTR)key.utf16(), REG_DWORD, L"SortOrderIndex", (const BYTE *)&value, sizeof(DWORD), samDesired); sValue = QString::fromUtf8("%systemroot%\\system32\\shell32.dll"); SetRegistryKeyAndValue(HKEY_CURRENT_USER, (LPTSTR)(key + QString::fromUtf8("\\InProcServer32")).utf16(), REG_EXPAND_SZ, L"", (const BYTE *)sValue.utf16(), sValue.size() * 2, samDesired); sValue = QString::fromUtf8("{0E5AAE11-A475-4c5b-AB00-C66DE400274E}"); SetRegistryKeyAndValue(HKEY_CURRENT_USER, (LPTSTR)(key + QString::fromUtf8("\\Instance")).utf16(), REG_SZ, L"CLSID", (const BYTE *)sValue.utf16(), sValue.size() * 2, samDesired); value = 0x10; SetRegistryKeyAndValue(HKEY_CURRENT_USER, (LPTSTR)(key + QString::fromUtf8("\\Instance\\InitPropertyBag")).utf16(), REG_DWORD, L"Attributes", (const BYTE *)&value, sizeof(DWORD), samDesired); sValue = QDir::toNativeSeparators(syncPath); SetRegistryKeyAndValue(HKEY_CURRENT_USER, (LPTSTR)(key + QString::fromUtf8("\\Instance\\InitPropertyBag")).utf16(), REG_EXPAND_SZ, L"TargetFolderPath", (const BYTE *)sValue.utf16(), sValue.size() * 2, samDesired); value = 0x28; SetRegistryKeyAndValue(HKEY_CURRENT_USER, (LPTSTR)(key + QString::fromUtf8("\\ShellFolder")).utf16(), REG_DWORD, L"FolderValueFlags", (const BYTE *)&value, sizeof(DWORD), samDesired); value = 0xF080004D; SetRegistryKeyAndValue(HKEY_CURRENT_USER, (LPTSTR)(key + QString::fromUtf8("\\ShellFolder")).utf16(), REG_DWORD, L"Attributes", (const BYTE *)&value, sizeof(DWORD), samDesired); samDesired = 0; } sValue = QString::fromUtf8("MEGA"); SetRegistryKeyAndValue(HKEY_CURRENT_USER, (LPTSTR) QString::fromUtf8("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Desktop\\NameSpace\\%1").arg(uuid).utf16(), REG_SZ, L"", (const BYTE *)sValue.utf16(), sValue.size() * 2, samDesired); value = 0x1; SetRegistryKeyAndValue(HKEY_CURRENT_USER, (LPTSTR) QString::fromUtf8("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\HideDesktopIcons\\NewStartPanel").utf16(), REG_DWORD, (LPTSTR)uuid.utf16(), (const BYTE *)&value, sizeof(DWORD), samDesired); }
static QVariant getValue(IWMHeaderInfo *header, const wchar_t *key) { WORD streamNumber = 0; WMT_ATTR_DATATYPE type = WMT_TYPE_DWORD; WORD size = 0; if (header->GetAttributeByName(&streamNumber, key, &type, 0, &size) == S_OK) { switch (type) { case WMT_TYPE_DWORD: if (size == sizeof(DWORD)) { DWORD word; if (header->GetAttributeByName( &streamNumber, key, &type, reinterpret_cast<BYTE *>(&word), &size) == S_OK) { return int(word); } } break; case WMT_TYPE_STRING: { QString string; string.resize(size / 2 - 1); if (header->GetAttributeByName( &streamNumber, key, &type, reinterpret_cast<BYTE *>(const_cast<ushort *>(string.utf16())), &size) == S_OK) { return string; } } break; case WMT_TYPE_BINARY: { QByteArray bytes; bytes.resize(size); if (header->GetAttributeByName( &streamNumber, key, &type, reinterpret_cast<BYTE *>(bytes.data()), &size) == S_OK) { return bytes; } } break; case WMT_TYPE_BOOL: if (size == sizeof(DWORD)) { DWORD word; if (header->GetAttributeByName( &streamNumber, key, &type, reinterpret_cast<BYTE *>(&word), &size) == S_OK) { return bool(word); } } break; case WMT_TYPE_QWORD: if (size == sizeof(QWORD)) { QWORD word; if (header->GetAttributeByName( &streamNumber, key, &type, reinterpret_cast<BYTE *>(&word), &size) == S_OK) { return qint64(word); } } break; case WMT_TYPE_WORD: if (size == sizeof(WORD)){ WORD word; if (header->GetAttributeByName( &streamNumber, key, &type, reinterpret_cast<BYTE *>(&word), &size) == S_OK) { return short(word); } } break; case WMT_TYPE_GUID: if (size == 16) { } break; default: break; } } return QVariant(); }
bool FileSystem::openAndSeekFileSharedRead(QFile* file, QString* errorOrNull, qint64 seek) { QString errorDummy; // avoid many if (errorOrNull) later. QString& error = errorOrNull ? *errorOrNull : errorDummy; error.clear(); #ifdef Q_OS_WIN // // The following code is adapted from Qt's QFSFileEnginePrivate::nativeOpen() // by including the FILE_SHARE_DELETE share mode. // // Enable full sharing. DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; int accessRights = GENERIC_READ; DWORD creationDisp = OPEN_EXISTING; // Create the file handle. SECURITY_ATTRIBUTES securityAtts = { sizeof(SECURITY_ATTRIBUTES), NULL, FALSE }; QString fName = longWinPath(file->fileName()); HANDLE fileHandle = CreateFileW( (const wchar_t*)fName.utf16(), accessRights, shareMode, &securityAtts, creationDisp, FILE_ATTRIBUTE_NORMAL, NULL); // Bail out on error. if (fileHandle == INVALID_HANDLE_VALUE) { error = qt_error_string(); return false; } // Convert the HANDLE to an fd and pass it to QFile's foreign-open // function. The fd owns the handle, so when QFile later closes // the fd the handle will be closed too. int fd = _open_osfhandle((intptr_t)fileHandle, _O_RDONLY); if (fd == -1) { error = "could not make fd from handle"; return false; } if (!file->open(fd, QIODevice::ReadOnly, QFile::AutoCloseHandle)) { error = file->errorString(); return false; } // Seek to the right spot LARGE_INTEGER *li = reinterpret_cast<LARGE_INTEGER*>(&seek); DWORD newFilePointer = SetFilePointer(fileHandle, li->LowPart, &li->HighPart, FILE_BEGIN); if (newFilePointer == 0xFFFFFFFF && GetLastError() != NO_ERROR) { error = qt_error_string(); return false; } return true; #else if (!file->open(QFile::ReadOnly)) { error = file->errorString(); return false; } if (!file->seek(seek)) { error = file->errorString(); return false; } return true; #endif }
static bool launchWebBrowser(const QUrl &url) { if (url.scheme() == QLatin1String("mailto")) { //Retrieve the commandline for the default mail client //the default key used below is the command line for the mailto: shell command DWORD bufferSize = sizeof(wchar_t) * MAX_PATH; long returnValue = -1; QString command; HKEY handle; LONG res; wchar_t keyValue[MAX_PATH] = {0}; QString keyName(QLatin1String("mailto")); //Check if user has set preference, otherwise use default. res = RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\mailto\\UserChoice", 0, KEY_READ, &handle); if (res == ERROR_SUCCESS) { returnValue = RegQueryValueEx(handle, L"Progid", 0, 0, reinterpret_cast<unsigned char*>(keyValue), &bufferSize); if (!returnValue) keyName = QString::fromUtf16((const ushort*)keyValue); RegCloseKey(handle); } keyName += QLatin1String("\\Shell\\Open\\Command"); res = RegOpenKeyExW(HKEY_CLASSES_ROOT, (const wchar_t*)keyName.utf16(), 0, KEY_READ, &handle); if (res != ERROR_SUCCESS) return false; bufferSize = sizeof(wchar_t) * MAX_PATH; returnValue = RegQueryValueEx(handle, L"", 0, 0, reinterpret_cast<unsigned char*>(keyValue), &bufferSize); if (!returnValue) command = QString::fromRawData((QChar*)keyValue, bufferSize); RegCloseKey(handle); if (returnValue) return false; command = expandEnvStrings(command); command = command.trimmed(); //Make sure the path for the process is in quotes int index = -1 ; if (command[0]!= QLatin1Char('\"')) { index = command.indexOf(QLatin1String(".exe "), 0, Qt::CaseInsensitive); command.insert(index+4, QLatin1Char('\"')); command.insert(0, QLatin1Char('\"')); } //pass the url as the parameter index = command.lastIndexOf(QLatin1String("%1")); if (index != -1){ command.replace(index, 2, url.toString()); } //start the process PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); STARTUPINFO si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); returnValue = CreateProcess(NULL, (wchar_t*)command.utf16(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); if (!returnValue) return false; CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return true; } if (!url.isValid()) return false; if (url.scheme().isEmpty()) return openDocument(url); quintptr returnValue = (quintptr)ShellExecute(0, 0, (wchar_t *)QString::fromUtf8(url.toEncoded().constData()).utf16(), 0, 0, SW_SHOWNORMAL); return (returnValue > 32); }
void CMessageLog::CreateLogWindow() { #ifdef CONFIG_MESSAGE_LOG_WIN32 LPCWSTR pszwClassMessageLog = (LPCWSTR)c_sMessageLog.utf16(); LPCWSTR pszwWindowName = (LPCWSTR)m_sNameMessageLog.utf16(); if (g_atomMessageLogRegistration == 0) { // Register the class of the MessageLog WNDCLASS wc = { CS_BYTEALIGNCLIENT | CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW, WndProcMessageLog, 0, 0, g_hInstance, NULL, NULL, NULL, NULL, pszwClassMessageLog }; g_atomMessageLogRegistration = ::RegisterClass(IN &wc); Assert(g_atomMessageLogRegistration != 0); (void)::LoadLibrary(L"RICHED20"); // Make sure the RichEdit DLL is loaded, otherwise the MessageLog won't be able to create its RichEdit control } Assert(m_hwndMessageLog == NULL); Assert(m_hwndRichEdit == NULL); RECT rcLogWindow; HKEY haKey = NULL; (void)RegOpenKeyEx(HKEY_CURRENT_USER, c_szwRegPathMessageLog, 0, KEY_READ, PA_OUT &haKey); DWORD dwType; DWORD cbData = sizeof(rcLogWindow); LONG lRetCode = ::RegQueryValueEx(haKey, IN pszwWindowName, d_zNA, OUT IGNORED &dwType, OUT (BYTE *)&rcLogWindow, INOUT &cbData); (void)RegCloseKey(PA_DELETING haKey); if (lRetCode != ERROR_SUCCESS || cbData != sizeof(rcLogWindow)) { // We were unable to the position of the window, so attempt to fit on the screen QRect rc = QApplication::desktop()->screenGeometry(); rc.adjust(rc.right() / 2, 50, -50, -100); int y = rc.bottom() * 3 / 4; if (m_sNameMessageLog == c_sMessageLog) rc.setBottom(y - 50); // Position the MessageLog at the top else rc.setTop(y); // Position the ErrorLog at the bottom Assert(sizeof(rc) == sizeof(rcLogWindow)); memcpy(OUT &rcLogWindow, IN &rc, sizeof(rcLogWindow)); // The implementation of QRect is the same as RECT } else { // Make sure the Chat Log fits within the screen WindowRectEnsurePartiallyVisibleWithinScreen(INOUT &rcLogWindow); } // Create the message log m_hwndMessageLog = ::CreateWindowEx( WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW, pszwClassMessageLog, pszwWindowName, WS_SIZEBOX | WS_TILEDWINDOW, rcLogWindow.left, rcLogWindow.top, rcLogWindow.right - rcLogWindow.left, rcLogWindow.bottom - rcLogWindow.top, g_hwndMainWindow, NULL, g_hInstance, NULL); m_hwndRichEdit = MessageLog_HGetRichEdit(m_hwndMessageLog); if (!IsWindow(m_hwndRichEdit)) { ::OutputDebugStringA("Unable to create Rich Editor!"); if (g_pwMainWindow != NULL) g_pwMainWindow->setWindowTitle("Unable to create Rich Editor!"); } #else // Create the chat debug window m_pwChatDebugger = new WChatDebugger(m_sNameMessageLog); g_pwMainWindow->addDockWidget(Qt::BottomDockWidgetArea, m_pwChatDebugger); m_pwTextBrowser = m_pwChatDebugger->m_pwTextBrowserMessageLog; Assert(m_pwTextBrowser != NULL); #endif } // CreateLogWindow()
QString readRegistryKey(HKEY parentHandle, const QString &rSubkey) { QString result; #ifdef Q_OS_WIN32 QString rSubkeyName = keyName(rSubkey); QString rSubkeyPath = keyPath(rSubkey); HKEY handle = 0; LONG res = RegOpenKeyEx(parentHandle, (wchar_t*)rSubkeyPath.utf16(), 0, KEY_READ, &handle); if (res != ERROR_SUCCESS) return QString(); // get the size and type of the value DWORD dataType; DWORD dataSize; res = RegQueryValueEx(handle, (wchar_t*)rSubkeyName.utf16(), 0, &dataType, 0, &dataSize); if (res != ERROR_SUCCESS) { RegCloseKey(handle); return QString(); } // get the value QByteArray data(dataSize, 0); res = RegQueryValueEx(handle, (wchar_t*)rSubkeyName.utf16(), 0, 0, reinterpret_cast<unsigned char*>(data.data()), &dataSize); if (res != ERROR_SUCCESS) { RegCloseKey(handle); return QString(); } switch (dataType) { case REG_EXPAND_SZ: case REG_SZ: { result = QString::fromWCharArray(((const wchar_t *)data.constData())); break; } case REG_MULTI_SZ: { QStringList l; int i = 0; for (;;) { QString s = QString::fromWCharArray((const wchar_t *)data.constData() + i); i += s.length() + 1; if (s.isEmpty()) break; l.append(s); } result = l.join(", "); break; } case REG_NONE: case REG_BINARY: { result = QString::fromWCharArray((const wchar_t *)data.constData(), data.size() / 2); break; } case REG_DWORD_BIG_ENDIAN: case REG_DWORD: { Q_ASSERT(data.size() == sizeof(int)); int i; memcpy((char*)&i, data.constData(), sizeof(int)); result = QString::number(i); break; } default: qWarning("QSettings: unknown data %u type in windows registry", quint32(dataType)); break; } RegCloseKey(handle); #endif return result; }
static bool qt_win_set_IFileDialogOptions(IFileDialog *pfd, const QString& initialSelection, const QString& initialDirectory, const QString& title, const QStringList& filterLst, QFileDialog::FileMode mode, QFileDialog::Options options) { if (!pSHCreateItemFromParsingName) { // This function is available only in Vista & above. QSystemLibrary shellLib(QLatin1String("Shell32")); pSHCreateItemFromParsingName = (PtrSHCreateItemFromParsingName) shellLib.resolve("SHCreateItemFromParsingName"); if (!pSHCreateItemFromParsingName) return false; } HRESULT hr; QString winfilters; int numFilters = 0; quint32 currentOffset = 0; QList<quint32> offsets; QStringList::ConstIterator it = filterLst.begin(); // Create the native filter string and save offset to each entry. for (; it != filterLst.end(); ++it) { QString subfilter = *it; if (!subfilter.isEmpty()) { offsets<<currentOffset; //Here the COMMON_ITEM_DIALOG API always add the details for the filter (e.g. *.txt) //so we don't need to handle the flag HideNameFilterDetails. winfilters += subfilter; // The name of the filter. winfilters += QChar(); currentOffset += subfilter.size()+1; offsets<<currentOffset; QString spec = qt_win_extract_filter(subfilter); winfilters += spec; // The actual filter spec. winfilters += QChar(); currentOffset += spec.size()+1; numFilters++; } } // Add the filters to the file dialog. if (numFilters) { wchar_t *szData = (wchar_t*)winfilters.utf16(); qt_COMDLG_FILTERSPEC *filterSpec = new qt_COMDLG_FILTERSPEC[numFilters]; for(int i = 0; i<numFilters; i++) { filterSpec[i].pszName = szData+offsets[i*2]; filterSpec[i].pszSpec = szData+offsets[(i*2)+1]; } hr = pfd->SetFileTypes(numFilters, filterSpec); delete []filterSpec; } // Set the starting folder. tInitDir = QDir::toNativeSeparators(initialDirectory); if (!tInitDir.isEmpty()) { IShellItem *psiDefaultFolder; hr = pSHCreateItemFromParsingName((wchar_t*)tInitDir.utf16(), NULL, QT_IID_IShellItem, reinterpret_cast<void**>(&psiDefaultFolder)); if (SUCCEEDED(hr)) { hr = pfd->SetFolder(psiDefaultFolder); psiDefaultFolder->Release(); } } // Set the currently selected file. QString initSel = QDir::toNativeSeparators(initialSelection); if (!initSel.isEmpty()) { initSel.remove(QLatin1Char('<')); initSel.remove(QLatin1Char('>')); initSel.remove(QLatin1Char('\"')); initSel.remove(QLatin1Char('|')); } if (!initSel.isEmpty()) { hr = pfd->SetFileName((wchar_t*)initSel.utf16()); } // Set the title for the file dialog. if (!title.isEmpty()) { hr = pfd->SetTitle((wchar_t*)title.utf16()); } // Set other flags for the dialog. DWORD newOptions; hr = pfd->GetOptions(&newOptions); if (SUCCEEDED(hr)) { newOptions |= FOS_NOCHANGEDIR; if (mode == QFileDialog::ExistingFile || mode == QFileDialog::ExistingFiles) newOptions |= (FOS_FILEMUSTEXIST | FOS_PATHMUSTEXIST); if (mode == QFileDialog::ExistingFiles) newOptions |= FOS_ALLOWMULTISELECT; if (!(options & QFileDialog::DontConfirmOverwrite)) newOptions |= FOS_OVERWRITEPROMPT; hr = pfd->SetOptions(newOptions); } return SUCCEEDED(hr); }
void QCommonStyle_QtDShell::drawItemText(QPainter* painter0, const QRect& rect1, int flags2, const QPalette& pal3, bool enabled4, const QString& text5, QPalette::ColorRole textRole6) const { qtd_QStyle_drawItemText_QPainter_QRect_int_QPalette_bool_string_ColorRole_const_dispatch(QObjectLink::getLink(this)->dId, (QPainter* )painter0, &(QRect& )rect1, (int )flags2, &(QPalette& )pal3, (bool )enabled4, text5.utf16(), text5.size(), (QPalette::ColorRole )textRole6); }
int VerbyPlugin::launchItem(QList<InputData>* inputData, CatItem* item) { item = item; // Compiler Warning if (inputData->count() != 2) { // Tell Launchy to handle the command return MSG_CONTROL_LAUNCHITEM; } QString noun = inputData->first().getTopResult().fullPath; CatItem& verbItem = inputData->last().getTopResult(); QString verb = verbItem.shortName; qDebug() << "Verby launchItem" << verb; if (verb == "Run") { runProgram(noun, ""); } else if (verb == "Open containing folder") { QFileInfo info(noun); if (info.isSymLink()) { info.setFile(info.symLinkTarget()); } #ifdef Q_WS_WIN runProgram("explorer.exe", "\"" + QDir::toNativeSeparators(info.absolutePath()) + "\""); #endif } else if (verb == "Open shortcut folder") { QFileInfo info(noun); #ifdef Q_WS_WIN runProgram("explorer.exe", "\"" + QDir::toNativeSeparators(info.absolutePath()) + "\""); #endif } else if (verb == "Run as") { #ifdef Q_WS_WIN SHELLEXECUTEINFO shellExecInfo; shellExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); shellExecInfo.fMask = SEE_MASK_FLAG_NO_UI; shellExecInfo.hwnd = NULL; shellExecInfo.lpVerb = L"runas"; shellExecInfo.lpFile = (LPCTSTR)noun.utf16(); shellExecInfo.lpParameters = NULL; QDir dir(noun); QFileInfo info(noun); if (!info.isDir() && info.isFile()) dir.cdUp(); QString filePath = QDir::toNativeSeparators(dir.absolutePath()); shellExecInfo.lpDirectory = (LPCTSTR)filePath.utf16(); shellExecInfo.nShow = SW_NORMAL; shellExecInfo.hInstApp = NULL; ShellExecuteEx(&shellExecInfo); #endif } else if (verb == "File properties") { #ifdef Q_WS_WIN SHELLEXECUTEINFO shellExecInfo; shellExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); shellExecInfo.fMask = SEE_MASK_FLAG_NO_UI | SEE_MASK_INVOKEIDLIST; shellExecInfo.hwnd = NULL; shellExecInfo.lpVerb = L"properties"; QString filePath = QDir::toNativeSeparators(noun); shellExecInfo.lpFile = (LPCTSTR)filePath.utf16(); shellExecInfo.lpIDList = NULL; shellExecInfo.lpParameters = NULL; shellExecInfo.lpDirectory = NULL; shellExecInfo.nShow = SW_NORMAL; shellExecInfo.hInstApp = NULL; ShellExecuteEx(&shellExecInfo); #endif } else if (verb == "Copy path to clipboard") { QFileInfo info(noun); if (info.isSymLink()) { info.setFile(info.symLinkTarget()); } QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(QDir::toNativeSeparators(info.canonicalFilePath())); } else { // Tell Launchy to handle the command return MSG_CONTROL_LAUNCHITEM; } updateUsage(verbItem); return true; }
bool QWinSettingsPrivate::readKey(HKEY parentHandle, const QString &rSubKey, QVariant *value) const { QString rSubkeyName = keyName(rSubKey); QString rSubkeyPath = keyPath(rSubKey); // open a handle on the subkey HKEY handle = openKey(parentHandle, KEY_READ, rSubkeyPath); if (handle == 0) return false; // get the size and type of the value DWORD dataType; DWORD dataSize; LONG res = RegQueryValueEx(handle, reinterpret_cast<const wchar_t *>(rSubkeyName.utf16()), 0, &dataType, 0, &dataSize); if (res != ERROR_SUCCESS) { RegCloseKey(handle); return false; } // get the value QByteArray data(dataSize, 0); res = RegQueryValueEx(handle, reinterpret_cast<const wchar_t *>(rSubkeyName.utf16()), 0, 0, reinterpret_cast<unsigned char*>(data.data()), &dataSize); if (res != ERROR_SUCCESS) { RegCloseKey(handle); return false; } switch (dataType) { case REG_EXPAND_SZ: case REG_SZ: { QString s; if (dataSize) { s = QString::fromWCharArray(((const wchar_t *)data.constData())); } if (value != 0) *value = stringToVariant(s); break; } case REG_MULTI_SZ: { QStringList l; if (dataSize) { int i = 0; for (;;) { QString s = QString::fromWCharArray((const wchar_t *)data.constData() + i); i += s.length() + 1; if (s.isEmpty()) break; l.append(s); } } if (value != 0) *value = stringListToVariantList(l); break; } case REG_NONE: case REG_BINARY: { QString s; if (dataSize) { s = QString::fromWCharArray((const wchar_t *)data.constData(), data.size() / 2); } if (value != 0) *value = stringToVariant(s); break; } case REG_DWORD_BIG_ENDIAN: case REG_DWORD: { Q_ASSERT(data.size() == sizeof(int)); int i; memcpy((char*)&i, data.constData(), sizeof(int)); if (value != 0) *value = i; break; } case REG_QWORD: { Q_ASSERT(data.size() == sizeof(qint64)); qint64 i; memcpy((char*)&i, data.constData(), sizeof(qint64)); if (value != 0) *value = i; break; } default: qWarning("QSettings: Unknown data %d type in Windows registry", static_cast<int>(dataType)); if (value != 0) *value = QVariant(); break; } RegCloseKey(handle); return true; }