/*! Эта реализация writeResults только для League! */ void League::writeResults() { //проверяем, мб мы уже записали QSettings stg (workdir + "/settings.ini", QSettings::IniFormat, this); bool isbonus = QFile::exists(workdir+"/bonus.ini"); QSettings bonus (workdir +"/bonus.ini", QSettings::IniFormat, this); qDebug() << "writing final!"; stg.beginGroup("Tournament"); bool wrote = false; wrote = stg.value("stored", false).toBool(); qDebug() << wrote; QSqlDatabase db = QSqlDatabase::database("players"); QSqlQuery q(db) ; QSqlQuery sq; QString team, nick; sq.prepare("SELECT nick, displayname, points FROM Teams ORDER by ABS (points)"); if (!sq.exec()) {qDebug() << "write result error!" << sq.lastError().text();} else {qDebug() << "Query done! " << sq.lastQuery();} int rank = 0; while (sq.next()) { qDebug() << rank; rank ++; QString result; if (rank == 1) result.append("Чемпион, "); else result.append(QVariant (rank).toString() + " место, "); result.append(sq.value(2).toString() + " очко(а, ов)"); nick = sq.value(0).toString(); team = sq.value(1).toString(); qDebug() << nick << team << result; q.prepare("SELECT smallname FROM Players WHERE nick=:nick"); q.bindValue(":nick", nick); if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();} else {qDebug() << "Query done: " + q.executedQuery();} q.first(); QString table = q.value(0).toString(); //проверяем q.prepare("SELECT COUNT (*) FROM "+ table + " WHERE team=:team AND trn=:trn"); if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();} else {qDebug() << "Query done: " + q.executedQuery();} q.first(); if (q.value(0).toInt() == 0) { q.prepare("INSERT INTO " + table + "(team, result) VALUES (:team, :result)"); q.bindValue(":team", team); q.bindValue(":trn", _title); if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();} else {qDebug() << "Query done: " + q.executedQuery();} //здесь будет выдача бонусов if (isbonus) { int bpoints = bonus.value(QVariant(rank).toString(), -1).toInt(); if (bpoints != -1){ q.prepare("UPDATE Rating SET bonus=(SELECT bonus FROM Rating WHERE nick=:nick)+"+QVariant(bpoints).toString()+" WHERE nick=:nick"); q.bindValue(":nick", nick); if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();} else {qDebug() << "Query done: " + q.executedQuery();} syncPoints(nick); } } } } stg.setValue("stored", true); stg.endGroup(); stg.sync(); }
// 修改项目名称 bool ProjectManager::renameProject(const QString &oldName, const QString &newName, bool changePath) { // 如果项目列表中没有oldName项目, 则返回false if (!allProjectMap.contains(oldName)) return false; // 如果项目列表中有项目newName项目, 新项目名称重名了, 则返回false if (allProjectMap.contains(newName)) return false; if (changePath) { // 如果选择重命名文件夹 QString oldPath = allProjectMap[oldName]; QDir dir(oldPath); if(dir.cdUp() && dir.rename(oldName, newName)) { // 如果重命名文件夹成功 QString newPath = dir.path() + "/" + newName; allProjectMap.remove(oldName); allProjectMap[newName] = newPath; pathList.removeAll(oldPath); pathList << newPath; if (openedProjectList.contains(oldName)) { openedProjectList.removeAll(oldName); openedProjectList << newName; } if (closedProjectList.contains(oldName)) { closedProjectList.removeAll(oldName); closedProjectList << newName; } deleteProjectObject(oldName); // 暂存historySettings中项目oldName配置 historySettings->beginGroup(oldName); QString status = historySettings->value("Status", "On").toString(); QString isCurrent = historySettings->value("IsCurrent", "False").toString(); historySettings->endGroup(); // 移除 historySettings中的oldName配置, 加入newName的配置 historySettings->remove(oldName); historySettings->setValue(newName + "/Status", status); historySettings->setValue(newName + "/IsCurrent", isCurrent); historySettings->setValue(newName + "/RootPath", newPath); historySettings->sync(); // 更新项目配置文件 QSettings *projectSettings = new QSettings(newPath + "/project.small", QSettings::IniFormat); projectSettings->setValue("Name", newName); projectSettings->sync(); delete projectSettings; emit projectRenamed(oldName, newName); return true; } else { // 如果重命名文件夹不成功 return false; } } else { // 如果不重命名文件夹 allProjectMap[newName] = allProjectMap[oldName]; allProjectMap.remove(oldName); if (openedProjectList.contains(oldName)) { openedProjectList.removeAll(oldName); openedProjectList << newName; } if (closedProjectList.contains(oldName)) { closedProjectList.removeAll(oldName); closedProjectList << newName; } if (projectObjectMap.contains(oldName)) { projectObjectMap[newName] = projectObjectMap[oldName]; projectObjectMap[newName]->setName(newName); } else { // 更新项目配置文件 QSettings *projectSettings = new QSettings( projectPath(newName) + "/project.small", QSettings::IniFormat); projectSettings->setValue("Name", newName); projectSettings->sync(); delete projectSettings; } // 暂存historySettings中项目oldName配置 historySettings->beginGroup(oldName); QString status = historySettings->value("Status", "On").toString(); QString isCurrent = historySettings->value("IsCurrent", "False").toString(); QString path = historySettings->value("RootPath").toString(); historySettings->endGroup(); // 移除 historySettings中的oldName配置, 加入newName的配置 historySettings->remove(oldName); historySettings->setValue(newName + "/Status", status); historySettings->setValue(newName + "/IsCurrent", isCurrent); historySettings->setValue(newName + "/RootPath", path); historySettings->sync(); return true; } }
void QDetaliiTabDialog::loadConfiguration() { QString fileName = QFileDialog::getOpenFileName(this, tr("Load layout"),"./","App Config(*.ccf)"); if (fileName.isEmpty()) return; QFile file(fileName); if (!file.open(QFile::ReadOnly)) { QString msg = tr("Failed to open %1\n%2") .arg(fileName) .arg(file.errorString()); QMessageBox::warning(this, tr("Error"), msg); return; } bool ok = true; QTextStream in(&file); QString line; QString variable; QString value; QStringList sl; QFont font; QString typeSetting; QSettings settings; int i, k; while (!in.atEnd()) { line = in.readLine(); //line = line.simplified(); //line = line.remove(" "); sl = line.split("="); variable = sl.at(0); if (sl.size() == 2) { value = sl.at(1); } else if (sl.size() > 2) { value = ""; for (i = 1; i < sl.size(); ++i) { value += sl.at(i); value += "="; } k = value.size(); value.truncate(k-1); } value = value.mid(1); k = value.length(); value.truncate(k-1); sl = value.split("("); typeSetting = sl.at(0); k = value.indexOf("("); value = value.mid(k+1); if (typeSetting == "Int") { settings.setValue(variable, value.toInt()); } else if (typeSetting == "Bool") { if (value == "true") settings.setValue(variable, true); else if (value == "false") settings.setValue(variable, false); } else if (typeSetting == "String") { k = value.length(); value.truncate(k-1); value = value.mid(1); settings.setValue(variable, value); } else if (typeSetting == "Point") { sl = value.split(","); settings.setValue(variable, QPoint(sl.at(0).toInt(), sl.at(1).toInt())); } else if (typeSetting == "Size") { sl = value.split(","); settings.setValue(variable, QSize(sl.at(0).toInt(), sl.at(1).toInt())); } } settings.sync(); if (!ok) { QString msg = tr("Error reading %1") .arg(fileName); QMessageBox::warning(this, tr("Error"), msg); return; } }
void Preferences::save() { qDebug("Preferences::save"); QSettings *set = settings; /* ******* General ******* */ set->beginGroup("general"); set->setValue("mplayer_bin", mplayer_bin); set->setValue("driver/vo", vo); set->setValue("driver/audio_output", ao); set->setValue("screenshot_directory", screenshot_directory); set->setValue("dont_remember_media_settings", dont_remember_media_settings); set->setValue("dont_remember_time_pos", dont_remember_time_pos); set->setValue("audio_lang", audio_lang); set->setValue("subtitle_lang", subtitle_lang); set->setValue("use_soft_video_eq", use_soft_video_eq); set->setValue("add_blackborders_on_fullscreen", add_blackborders_on_fullscreen); #ifdef Q_OS_WIN set->setValue("turn_screensaver_off", turn_screensaver_off); set->setValue("avoid_screensaver", avoid_screensaver); #else set->setValue("disable_screensaver", disable_screensaver); #endif #ifndef Q_OS_WIN set->setValue("vdpau_ffh264vdpau", vdpau.ffh264vdpau); set->setValue("vdpau_ffmpeg12vdpau", vdpau.ffmpeg12vdpau); set->setValue("vdpau_ffwmv3vdpau", vdpau.ffwmv3vdpau); set->setValue("vdpau_ffvc1vdpau", vdpau.ffvc1vdpau); set->setValue("vdpau_ffodivxvdpau", vdpau.ffodivxvdpau); set->setValue("vdpau_disable_video_filters", vdpau.disable_video_filters); #endif set->setValue("use_soft_vol", use_soft_vol); set->setValue("softvol_max", softvol_max); set->setValue("use_scaletempo", use_scaletempo); set->setValue("use_hwac3", use_hwac3); set->setValue("gapless_audio", gapless_audio); set->setValue("use_audio_equalizer", use_audio_equalizer); set->setValue("global_volume", global_volume); set->setValue("volume", volume); set->setValue("mute", mute); set->setValue("autosync", autosync); set->setValue("autosync_factor", autosync_factor); set->setValue("use_mc", use_mc); set->setValue("mc_value", mc_value); set->setValue("osd", osd); set->setValue("osd_delay", osd_delay); set->setValue("file_settings_method", file_settings_method); set->endGroup(); // general /* *************** Drives (CD/DVD) *************** */ set->beginGroup("drives"); set->setValue("dvd_device", dvd_device); set->setValue("cdrom_device", cdrom_device); #ifdef Q_OS_WIN set->setValue("enable_audiocd_on_windows", enable_audiocd_on_windows); #endif set->setValue("vcd_initial_title", vcd_initial_title); #if DVDNAV_SUPPORT set->setValue("use_dvdnav", use_dvdnav); #endif set->endGroup(); // drives /* *********** Performance *********** */ set->beginGroup("performance"); set->setValue("priority", priority); set->setValue("frame_drop", frame_drop); set->setValue("hard_frame_drop", hard_frame_drop); set->setValue("h264_skip_loop_filter", h264_skip_loop_filter); set->setValue("HD_height", HD_height); set->setValue("lavdthreads", threads); set->setValue("cache_for_files", cache_for_files); set->setValue("cache_for_streams", cache_for_streams); set->setValue("cache_for_dvds", cache_for_dvds); set->setValue("cache_for_vcds", cache_for_vcds); set->setValue("cache_for_audiocds", cache_for_audiocds); set->setValue("cache_for_tv", cache_for_tv); set->endGroup(); // performance /* ********* Subtitles ********* */ set->beginGroup("subtitles"); set->setValue("sub_use_mplayer2_defaults", sub_use_mplayer2_defaults); set->setValue("sub_encoding", sub_encoding); set->setValue("use_enca", use_enca); set->setValue("enca_lang", enca_lang); set->setValue("subfuzziness", subfuzziness); set->setValue("autoload_sub", autoload_sub); set->setValue("prefer_external", prefer_external); set->setValue("ass_line_spacing", ass_line_spacing); set->setValue("use_forced_subs_only", use_forced_subs_only); set->setValue("sub_visibility", sub_visibility); set->setValue("subtitles_on_screenshots", subtitles_on_screenshots); // ASS styles ass_styles.save(set); set->setValue("force_ass_styles", force_ass_styles); set->setValue("user_forced_ass_style", user_forced_ass_style); set->endGroup(); // subtitles /* ******** Advanced ******** */ set->beginGroup("advanced"); #if USE_ADAPTER set->setValue("adapter", adapter); #endif #if USE_COLORKEY set->setValue("color_key", QString::number(color_key, 16)); #endif set->setValue("use_mplayer_window", use_mplayer_window); set->setValue("monitor_aspect", monitor_aspect); set->setValue("use_idx", use_idx); set->setValue("mplayer_additional_options", mplayer_additional_options); set->setValue("mplayer_additional_video_filters", mplayer_additional_video_filters); set->setValue("mplayer_additional_audio_filters", mplayer_additional_audio_filters); set->setValue("log_mplayer", log_mplayer); set->setValue("log_smplayer2", log_smplayer2); set->setValue("log_filter", log_filter); set->setValue("verbose_log", verbose_log); set->setValue("save_smplayer2_log", save_smplayer2_log); //mplayer log autosaving set->setValue("autosave_mplayer_log", autosave_mplayer_log); set->setValue("mplayer_log_saveto", mplayer_log_saveto); //mplayer log autosaving end #if REPAINT_BACKGROUND_OPTION set->setValue("repaint_video_background", repaint_video_background); #endif set->setValue("use_edl_files", use_edl_files); set->setValue("prefer_ipv4", prefer_ipv4); set->setValue("change_video_equalizer_on_startup", change_video_equalizer_on_startup); set->setValue("use_pausing_keep_force", use_pausing_keep_force); set->setValue("correct_pts", use_correct_pts); set->setValue("actions_to_run", actions_to_run); set->setValue("show_tag_in_window_title", show_tag_in_window_title); set->endGroup(); // advanced /* ********* GUI stuff ********* */ set->beginGroup("gui"); set->setValue("fullscreen", fullscreen); set->setValue("start_in_fullscreen", start_in_fullscreen); set->setValue("compact_mode", compact_mode); set->setValue("stay_on_top", (int) stay_on_top); set->setValue("size_factor", size_factor); set->setValue("resize_method", resize_method); #if STYLE_SWITCHING set->setValue("style", style); #endif set->setValue("show_motion_vectors", show_motion_vectors); set->setValue("mouse_left_click_function", mouse_left_click_function); set->setValue("mouse_right_click_function", mouse_right_click_function); set->setValue("mouse_double_click_function", mouse_double_click_function); set->setValue("mouse_middle_click_function", mouse_middle_click_function); set->setValue("mouse_xbutton1_click_function", mouse_xbutton1_click_function); set->setValue("mouse_xbutton2_click_function", mouse_xbutton2_click_function); set->setValue("mouse_wheel_function", wheel_function); set->setValue("wheel_function_cycle", (int) wheel_function_cycle); set->setValue("wheel_function_seeking_reverse", wheel_function_seeking_reverse); set->setValue("seeking1", seeking1); set->setValue("seeking2", seeking2); set->setValue("seeking3", seeking3); set->setValue("seeking4", seeking4); set->setValue("update_while_seeking", update_while_seeking); set->setValue("language", language); set->setValue("iconset", iconset); set->setValue("balloon_count", balloon_count); set->setValue("restore_pos_after_fullscreen", restore_pos_after_fullscreen); set->setValue("save_window_size_on_exit", save_window_size_on_exit); set->setValue("close_on_finish", close_on_finish); set->setValue("default_font", default_font); set->setValue("pause_when_hidden", pause_when_hidden); set->setValue("allow_video_movement", allow_video_movement); set->setValue("gui", gui); #if USE_MINIMUMSIZE set->setValue("gui_minimum_width", gui_minimum_width); #endif set->setValue("default_size", default_size); #if ALLOW_TO_HIDE_VIDEO_WINDOW_ON_AUDIO_FILES set->setValue("hide_video_window_on_audio_files", hide_video_window_on_audio_files); #endif set->setValue("report_mplayer_crashes", report_mplayer_crashes); set->setValue("auto_add_to_playlist", auto_add_to_playlist); set->setValue("add_to_playlist_consecutive_files", add_to_playlist_consecutive_files); set->endGroup(); // gui /* ******** TV (dvb) ******** */ set->beginGroup("tv"); set->setValue("check_channels_conf_on_startup", check_channels_conf_on_startup); set->setValue("initial_tv_deinterlace", initial_tv_deinterlace); set->setValue("last_dvb_channel", last_dvb_channel); set->setValue("last_tv_channel", last_tv_channel); set->endGroup(); // tv /* *********** Directories *********** */ set->beginGroup("directories"); set->setValue("latest_dir", latest_dir); set->setValue("last_dvd_directory", last_dvd_directory); set->endGroup(); // directories /* ************** Initial values ************** */ set->beginGroup("defaults"); set->setValue("initial_sub_scale_ass", initial_sub_scale_ass); set->setValue("initial_volume", initial_volume); set->setValue("initial_contrast", initial_contrast); set->setValue("initial_brightness", initial_brightness); set->setValue("initial_hue", initial_hue); set->setValue("initial_saturation", initial_saturation); set->setValue("initial_gamma", initial_gamma); set->setValue("initial_audio_equalizer", initial_audio_equalizer); set->setValue("initial_zoom_factor", initial_zoom_factor); set->setValue("initial_volnorm", initial_volnorm); set->setValue("initial_deinterlace", initial_deinterlace); set->setValue("initial_audio_channels", initial_audio_channels); set->setValue("initial_stereo_mode", initial_stereo_mode); set->setValue("initial_audio_track", initial_audio_track); set->setValue("initial_subtitle_track", initial_subtitle_track); set->endGroup(); // defaults /* ********* Instances ********* */ set->beginGroup("instances"); set->setValue("use_single_instance", use_single_instance); set->setValue("connection_port", connection_port); set->setValue("use_autoport", use_autoport); set->setValue("temp/autoport", autoport); set->endGroup(); // instances /* **************** Floating control **************** */ set->beginGroup("floating_control"); set->setValue("margin", floating_control_margin); set->setValue("width", floating_control_width); set->setValue("animated", floating_control_animated); set->setValue("display_in_compact_mode", floating_display_in_compact_mode); #ifndef Q_OS_WIN set->setValue("bypass_window_manager", bypass_window_manager); #endif set->endGroup(); // floating_control /* ******* History ******* */ set->beginGroup("history"); set->setValue("recents", history_recents->toStringList()); set->setValue("recents/max_items", history_recents->maxItems()); set->setValue("urls", history_urls->toStringList()); set->setValue("urls/max_items", history_urls->maxItems()); set->endGroup(); // history /* ******* Filters ******* */ filters->save(set); set->sync(); }
void ProjectManager::loadHistoryProject() { // 配置文件的每个group 都是项目根目录的绝对路径, 这样可以保持treeview中的每个group都是唯一的 QStringList projectList = historySettings->childGroups(); QStringList::const_iterator constIterator = projectList.constBegin(); QStringList::const_iterator endIterator = projectList.constEnd(); // 初始化 allProjectMap while (constIterator != endIterator) { if (!allProjectMap.contains(*constIterator)) allProjectMap[*constIterator] = QString(); ++constIterator; } qDebug() << "导入历史项目中 ..."; constIterator = projectList.constBegin(); while (constIterator != endIterator) { qDebug() << "开始导入项目" << *constIterator << "..."; historySettings->beginGroup(*constIterator); QString rootPath = historySettings->value("RootPath").toString(); if (rootPath.contains(QRegExp("/\\s*$"))) { rootPath.remove(QRegExp("/\\s*$")); historySettings->setValue("RootPath", rootPath); } // 如果 pathList 中含有rootPath, 则说明该位置的项目已经导入了, 不需要重新导入它 // 从 historySettings 和 allProjectMap 中删除它, 并继续下一个项目 if (pathList.contains(rootPath)) { historySettings->endGroup(); qDebug() << "目录" << rootPath << "中的项目已经导入, 不需要重新导入"; historySettings->remove(*constIterator); allProjectMap.remove(*constIterator); ++constIterator; continue; } // 如果rootPath 为空 或者 不存在该目录, 则从historySettings和allProjectMap中删除该项目 if (rootPath.isEmpty() || !QFile::exists(rootPath)) { historySettings->endGroup(); qDebug() << "目录" << rootPath + "不存在, 放弃该项目" << *constIterator; allProjectMap.remove(*constIterator); historySettings->remove(*constIterator); ++constIterator; continue; } // 查看是否存在project.small文件, 如果不存在, 则拷贝一份模板, 如果拷贝失败, 则从historySettings和allProjectMap中删除该项目 // 之所以在不存在的情况加拷贝一份模板, 是因为用户可能误删了配置文件, 所以重新建立它 bool isNew = false; QFileInfo fileInfo(rootPath + "/project.small"); if (!fileInfo.exists()) { if (!QFile::copy(Global::projectConfigTemplate(), fileInfo.absoluteFilePath())) { QString errorInfo = "拷贝项目配置文件失败 \ncopy from:" + Global::projectConfigTemplate() + "\n copy to:" + fileInfo.absoluteFilePath() + "\n没有导入该项目\"" + *constIterator + "\""; qDebug() << errorInfo; hintInfoList << errorInfo; emit hint(errorInfo); historySettings->endGroup(); allProjectMap.remove(*constIterator); historySettings->remove(*constIterator); ++constIterator; continue; } isNew = true; } else if (!fileInfo.isFile() || !fileInfo.isWritable() || !fileInfo.isReadable()) { // 如果project.small不是普通文件或者没有读写权限, 则从historySettings和allProjectMap中删除该项目 QString errorInfo = "文件\"" + fileInfo.absoluteFilePath() + "\"不是普通文件, 或者您没有它读写权限" + "\n没有导入该项目\"" + *constIterator + "\""; qDebug() << errorInfo; hintInfoList << errorInfo; emit hint(errorInfo); historySettings->endGroup(); allProjectMap.remove(*constIterator); historySettings->remove(*constIterator); ++constIterator; continue; } QSettings *projectSettings = new QSettings(fileInfo.absoluteFilePath(), QSettings::IniFormat); // 如果配置文件是复制得到的, 设置 Name = *constIterator if (isNew || projectSettings->value("Name").toString().isEmpty()) { projectSettings->setValue("Name", *constIterator); projectSettings->sync(); } QString projectName = projectSettings->value("Name").toString(); // 如果project.small文件中的Name 与 历史配置文件的项目名称变量不一致, 则使之尽可能与项目配置文件一致 if (projectName != *constIterator) { projectName = validProjectName(projectName); qDebug() << "项目名称" << *constIterator << "与project.small配置文件中的Name不一致, 修改项目名称"; qDebug() << "修改后的名称为" << projectName; // 暂存historySettings中项目oldName配置 QString status = historySettings->value("Status", "On").toString(); QString isCurrent = historySettings->value("IsCurrent", "False").toString(); QString path = historySettings->value("RootPath").toString(); historySettings->endGroup(); // 移除 historySettings中的oldName配置, 加入newName的配置 historySettings->remove(*constIterator); historySettings->setValue(projectName + "/Status", status); historySettings->setValue(projectName + "/IsCurrent", isCurrent); historySettings->setValue(projectName + "/RootPath", path); historySettings->sync(); historySettings->beginGroup(projectName); // 更新项目配置文件 QSettings *projectSettings = new QSettings(rootPath + "/project.small", QSettings::IniFormat); projectSettings->setValue("Name", projectName); projectSettings->sync(); delete projectSettings; } allProjectMap[projectName] = rootPath; pathList << rootPath; // 如果Status = On/on/oN if (historySettings->value("Status", "On").toString().toLower() == "on") { openedProjectList << projectName; QString isCurrent = historySettings->value("IsCurrent", "False").toString().toLower(); // 如果currentProject为空, 且IsCurrent = True, 则设置currentProject = projectName if (isCurrent == "true" && currentProject.isEmpty()) currentProject = projectName; } else { closedProjectList << projectName; } historySettings->endGroup(); qDebug() << "导入项目" << projectName << "成功."; ++constIterator; } historySettings->sync(); qDebug() << "所有项目导入完成."; }
SettingsModel::SettingsModel(void) { QString configPath = "LameXP.ini"; if(!lamexp_portable_mode()) { QString dataPath = initDirectory(QDesktopServices::storageLocation(QDesktopServices::DataLocation)); if(!dataPath.isEmpty()) { configPath = QString("%1/config.ini").arg(QDir(dataPath).canonicalPath()); } else { qWarning("SettingsModel: DataLocation could not be initialized!"); dataPath = initDirectory(QDesktopServices::storageLocation(QDesktopServices::HomeLocation)); if(!dataPath.isEmpty()) { configPath = QString("%1/LameXP.ini").arg(QDir(dataPath).canonicalPath()); } } } else { qDebug("LameXP is running in \"portable\" mode -> config in application dir!\n"); QString appPath = QFileInfo(QApplication::applicationFilePath()).canonicalFilePath(); if(appPath.isEmpty()) { appPath = QFileInfo(QApplication::applicationFilePath()).absoluteFilePath(); } if(QFileInfo(appPath).exists() && QFileInfo(appPath).isFile()) { configPath = QString("%1/%2.ini").arg(QFileInfo(appPath).absolutePath(), QFileInfo(appPath).completeBaseName()); } } //Create settings QSettings *configFile = new QSettings(configPath, QSettings::IniFormat); const QString groupKey = QString().sprintf("LameXP_%u%02u%05u", lamexp_version_major(), lamexp_version_minor(), lamexp_version_confg()); QStringList childGroups =configFile->childGroups(); //Clean-up settings while(!childGroups.isEmpty()) { QString current = childGroups.takeFirst(); QRegExp filter("^LameXP_(\\d+)(\\d\\d)(\\d\\d\\d\\d\\d)$"); if(filter.indexIn(current) >= 0) { bool ok = false; unsigned int temp = filter.cap(3).toUInt(&ok) + 10; if(ok && (temp >= lamexp_version_confg())) { continue; } } qWarning("Deleting obsolete group from config: %s", QUTF8(current)); REMOVE_GROUP(configFile, current); } //Setup settings configFile->beginGroup(groupKey); configFile->setValue(g_settingsId_versionNumber, QApplication::applicationVersion()); configFile->sync(); //Create the cache m_configCache = new SettingsCache(configFile); }
bool MainWindow::openPath(const QString &path) { #ifndef Q_OS_ANDROID // Empty path does nothing. This also helps with the single instance application code. if (path.isEmpty()) return true; MainWindow* const existing = findMainWindow(path); if (existing) { existing->show(); existing->raise(); existing->activateWindow(); return true; } #endif // Check a blocker that prevents immediate re-opening of crashing files. // Needed for stopping auto-loading a crashing file on startup. static const QString reopen_blocker = QString::fromLatin1("open_in_progress"); QSettings settings; const QString open_in_progress(settings.value(reopen_blocker).toString()); if (open_in_progress == path) { int result = QMessageBox::warning(this, tr("Crash warning"), tr("It seems that %1 crashed the last time this file was opened:<br /><tt>%2</tt><br /><br />Really retry to open it?").arg(appName()).arg(path), QMessageBox::Yes | QMessageBox::No); settings.remove(reopen_blocker); if (result == QMessageBox::No) return false; } settings.setValue(reopen_blocker, path); settings.sync(); MainWindowController* const new_controller = MainWindowController::controllerForFile(path); if (!new_controller) { QMessageBox::warning(this, tr("Error"), tr("Cannot open file:\n%1\n\nFile format not recognized.").arg(path)); settings.remove(reopen_blocker); return false; } QString new_actual_path = path; QString autosave_path = Autosave::autosavePath(path); bool new_autosave_conflict = QFileInfo(autosave_path).exists(); if (new_autosave_conflict) { #if defined(Q_OS_ANDROID) // Assuming small screen, showing dialog before opening the file AutosaveDialog* autosave_dialog = new AutosaveDialog(path, autosave_path, autosave_path, this); int result = autosave_dialog->exec(); new_actual_path = (result == QDialog::Accepted) ? autosave_dialog->selectedPath() : QString(); delete autosave_dialog; #else // Assuming large screen, dialog will be shown while the autosaved file is open new_actual_path = autosave_path; #endif } if (new_actual_path.isEmpty() || !new_controller->load(new_actual_path, this)) { delete new_controller; settings.remove(reopen_blocker); return false; } MainWindow* open_window = this; #if !defined(Q_OS_ANDROID) if (has_opened_file) open_window = new MainWindow(); #endif open_window->setController(new_controller, path); open_window->actual_path = new_actual_path; open_window->setHasAutosaveConflict(new_autosave_conflict); open_window->setHasUnsavedChanges(false); open_window->setVisible(true); // Respect the window flags set by new_controller. open_window->raise(); num_open_files++; settings.remove(reopen_blocker); setMostRecentlyUsedFile(path); #if !defined(Q_OS_ANDROID) // Assuming large screen. Android handled above. if (new_autosave_conflict) { auto autosave_dialog = new AutosaveDialog(path, autosave_path, new_actual_path, open_window, Qt::WindowTitleHint | Qt::CustomizeWindowHint); autosave_dialog->move(open_window->rect().right() - autosave_dialog->width(), open_window->rect().top()); autosave_dialog->show(); autosave_dialog->raise(); connect(autosave_dialog, &AutosaveDialog::pathSelected, open_window, &MainWindow::switchActualPath); connect(open_window, &MainWindow::actualPathChanged, autosave_dialog, &AutosaveDialog::setSelectedPath); connect(open_window, &MainWindow::autosaveConflictResolved, autosave_dialog, &AutosaveDialog::autosaveConflictResolved); } #endif open_window->activateWindow(); return true; }
int main(int argc, char * argv[]) { /* * Before starting main application, need to set 'QT_X11_NO_MITSHM=1' * to make the runtime work with IBM PPC machine. */ #if defined (Q_OS_LINUX) QByteArray val("1"); qputenv("QT_X11_NO_MITSHM", val); #endif // Create the QT application QApplication app(argc, argv); app.setQuitOnLastWindowClosed(false); // Setup the settings management QCoreApplication::setOrganizationName("pgadmin"); QCoreApplication::setOrganizationDomain("pgadmin.org"); QCoreApplication::setApplicationName(PGA_APP_NAME.toLower().replace(" ", "")); #if QT_VERSION >= 0x050000 // Set high DPI pixmap to display icons clear on Qt widget. QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #endif // Create a hash of the executable path so we can run copies side-by-side QString homeDir = QDir::homePath(); unsigned long exeHash = sdbm((unsigned char *)argv[0]); // Create the address file, that will be used to store the appserver URL for this instance addrFileName = homeDir + (QString("/.%1.%2.addr").arg(PGA_APP_NAME).arg(exeHash)).remove(" "); QFile addrFile(addrFileName); // Create a system-wide semaphore keyed by app name, exe hash and the username // to ensure instances are unique to the user and path QString userName = qgetenv("USER"); // *nix if (userName.isEmpty()) userName = qgetenv("USERNAME"); // Windows QString semaName = QString("%1-%2-%3-sema").arg(PGA_APP_NAME).arg(userName).arg(exeHash); QString shmemName = QString("%1-%2-%3-shmem").arg(PGA_APP_NAME).arg(userName).arg(exeHash); QSystemSemaphore sema(semaName, 1); sema.acquire(); #ifndef Q_OS_WIN32 // We may need to clean up stale shmem segments on *nix. Attaching and detaching // should remove the segment if it is orphaned. QSharedMemory stale_shmem(shmemName); if (stale_shmem.attach()) stale_shmem.detach(); #endif QSharedMemory shmem(shmemName); bool is_running; if (shmem.attach()) { is_running = true; } else { shmem.create(1); is_running = false; } sema.release(); QSettings settings; if (is_running){ addrFile.open(QIODevice::ReadOnly | QIODevice::Text); QTextStream in(&addrFile); QString addr = in.readLine(); QString cmd = settings.value("BrowserCommand").toString(); if (!cmd.isEmpty()) { cmd.replace("%URL%", addr); QProcess::startDetached(cmd); } else { if (!QDesktopServices::openUrl(addr)) { QString error(QWidget::tr("Failed to open the system default web browser. Is one installed?.")); QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error); exit(1); } } return 0; } atexit(cleanup); // In windows and linux, it is required to set application level proxy // because socket bind logic to find free port gives socket creation error // when system proxy is configured. We are also setting // "setUseSystemConfiguration"=true to use the system proxy which will // override this application level proxy. As this bug is fixed in Qt 5.9 so // need to set application proxy for Qt version < 5.9. // #if defined (Q_OS_WIN) && QT_VERSION <= 0x050800 // Give dummy URL required to find proxy server configured in windows. QNetworkProxyQuery proxyQuery(QUrl("https://www.pgadmin.org")); QNetworkProxy l_proxy; QList<QNetworkProxy> listOfProxies = QNetworkProxyFactory::systemProxyForQuery(proxyQuery); if (listOfProxies.size()) { l_proxy = listOfProxies[0]; // If host name is not empty means proxy server is configured. if (!l_proxy.hostName().isEmpty()) { QNetworkProxy::setApplicationProxy(QNetworkProxy()); } } #endif #if defined (Q_OS_LINUX) && QT_VERSION <= 0x050800 QByteArray proxy_env; proxy_env = qgetenv("http_proxy"); // If http_proxy environment is defined in linux then proxy server is configured. if (!proxy_env.isEmpty()) { QNetworkProxy::setApplicationProxy(QNetworkProxy()); } #endif // Display the spash screen QSplashScreen *splash = new QSplashScreen(); splash->setPixmap(QPixmap(":/splash.png")); splash->show(); app.processEvents(QEventLoop::AllEvents); quint16 port = 0L; // Find an unused port number. Essentially, we're just reserving one // here that Flask will use when we start up the server. // In order to use the socket, we need to free this socket ASAP. // Hence - putting this code in a code block so the scope of the socket // variable vanishes to make that socket available. { #if QT_VERSION >= 0x050000 QTcpSocket socket; #if QT_VERSION >= 0x050900 socket.setProxy(QNetworkProxy::NoProxy); #endif socket.bind(0, QTcpSocket::ShareAddress); #else QUdpSocket socket; socket.bind(0, QUdpSocket::ShareAddress); #endif port = socket.localPort(); } // Generate a random key to authenticate the client to the server QString key = QUuid::createUuid().toString(); key = key.mid(1, key.length() - 2); // Generate the filename for the log logFileName = homeDir + (QString("/.%1.%2.log").arg(PGA_APP_NAME).arg(exeHash)).remove(" "); // Start the tray service TrayIcon *trayicon = new TrayIcon(logFileName); if (!trayicon->Init()) { QString error = QString(QWidget::tr("An error occurred initialising the tray icon")); QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error); exit(1); } // Fire up the webserver Server *server; bool done = false; while (done != true) { server = new Server(port, key, logFileName); if (!server->Init()) { splash->finish(NULL); qDebug() << server->getError(); QString error = QString(QWidget::tr("An error occurred initialising the application server:\n\n%1")).arg(server->getError()); QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error); exit(1); } server->start(); // This is a hack to give the server a chance to start and potentially fail. As // the Python interpreter is a synchronous call, we can't check for proper startup // easily in a more robust way - we have to rely on a clean startup not returning. // It should always fail pretty quickly, and take longer to start if it succeeds, so // we don't really get a visible delay here. delay(1000); // Any errors? if (server->isFinished() || server->getError().length() > 0) { splash->finish(NULL); qDebug() << server->getError(); QString error = QString(QWidget::tr("An error occurred initialising the application server:\n\n%1")).arg(server->getError()); QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error); // Allow the user to tweak the Python Path if needed bool ok; ConfigWindow *dlg = new ConfigWindow(); dlg->setWindowTitle(QWidget::tr("Configuration")); dlg->setBrowserCommand(settings.value("BrowserCommand").toString()); dlg->setPythonPath(settings.value("PythonPath").toString()); dlg->setApplicationPath(settings.value("ApplicationPath").toString()); dlg->setModal(true); ok = dlg->exec(); QString browsercommand = dlg->getBrowserCommand(); QString pythonpath = dlg->getPythonPath(); QString applicationpath = dlg->getApplicationPath(); if (ok) { settings.setValue("BrowserCommand", browsercommand); settings.setValue("PythonPath", pythonpath); settings.setValue("ApplicationPath", applicationpath); settings.sync(); } else { exit(1); } delete server; } else done = true; } // Ensure the server gets cleaned up later QObject::connect(server, SIGNAL(finished()), server, SLOT(deleteLater())); // Generate the app server URL QString appServerUrl = QString("http://127.0.0.1:%1/?key=%2").arg(port).arg(key); // Read the server connection timeout from the registry or set the default timeout. int timeout = settings.value("ConnectionTimeout", 30).toInt(); // Now the server should be up, we'll attempt to connect and get a response. // We'll retry in a loop a few time before aborting if necessary. QTime endTime = QTime::currentTime().addSecs(timeout); bool alive = false; while(QTime::currentTime() <= endTime) { alive = PingServer(QUrl(appServerUrl)); if (alive) { break; } delay(200); } // Attempt to connect one more time in case of a long network timeout while looping if (!alive && !PingServer(QUrl(appServerUrl))) { splash->finish(NULL); QString error(QWidget::tr("The application server could not be contacted.")); QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error); exit(1); } // Stash the URL for any duplicate processes to open if (addrFile.open(QIODevice::WriteOnly)) { addrFile.setPermissions(QFile::ReadOwner|QFile::WriteOwner); QTextStream out(&addrFile); out << appServerUrl << endl; } // Go! trayicon->setAppServerUrl(appServerUrl); // Enable the shutdown server menu as server started successfully. trayicon->enableShutdownMenu(); QString cmd = settings.value("BrowserCommand").toString(); if (!cmd.isEmpty()) { cmd.replace("%URL%", appServerUrl); QProcess::startDetached(cmd); } else { if (!QDesktopServices::openUrl(appServerUrl)) { QString error(QWidget::tr("Failed to open the system default web browser. Is one installed?.")); QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error); exit(1); } } QObject::connect(trayicon, SIGNAL(shutdownSignal(QUrl)), server, SLOT(shutdown(QUrl))); splash->finish(NULL); return app.exec(); }
bool clearAssociation(const QString & extension) { if(!isSupportAssociation()) return false; #ifdef Q_WS_WIN if(!checkAssociation(extension)) return true; QString ext("." + extension); QString ProgID = makeProgID(extension); QSettings RegCU("HKEY_CURRENT_USER", QSettings::NativeFormat); QSettings RegCR ("HKEY_CLASSES_ROOT", QSettings::NativeFormat); if (QSysInfo::WindowsVersion < QSysInfo::WV_NT && !RegCR.isWritable()) //Win98 return false; QString fileName = QFileInfo(qApp->applicationFilePath()).fileName(); QString FileExtsKey = QString("Software/Microsoft/Windows/CurrentVersion/Explorer/FileExts/") + ext; /// Windows 7:"/UserChoice/Progid" ; XP: "/Progid" QString CurClassId = (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA) ? RegCU.value(FileExtsKey + "/UserChoice/Progid").toString() : RegCU.value(FileExtsKey + "/Progid").toString(); QString CurAppId = RegCU.value(FileExtsKey + "/Application").toString(); /// Windows XP if (!CurClassId.isEmpty() && ( (CurClassId == ProgID) || (0 == CurClassId.compare(fileName, Qt::CaseInsensitive)) || (0 == CurClassId.compare(QString("Applications\\%1").arg(fileName), Qt::CaseInsensitive)) ) ){ removeUserChoice(extension); } if (!CurAppId.isEmpty() && ( (CurAppId == ProgID) || (0 == CurAppId.compare(fileName, Qt::CaseInsensitive)) ) ){ RegCU.remove(FileExtsKey + "/Application"); } if (QSysInfo::WindowsVersion >= QSysInfo::WV_NT){ if (RegCU.value("Software/Classes/" + ext + REG_DEFAULT).toString() == ProgID) //Only remove if we own it /// This is no recommend to delete in MSDN, case it may cause other problems, such as cannot create new text document if delete '.txt' group. // RegCU.remove("Software/Classes/" + ext); RegCU.remove("Software/Classes/" + ProgID); }else{ //Windows 98 ==> Write to HKCR if (RegCR.value(ext + REG_DEFAULT).toString() == ProgID) // RegCR.remove(ext); RegCR.remove(ProgID); } RegCU.sync(); RegCR.sync(); // SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);// Refresh Explorer cache. return (RegCU.status() == QSettings::NoError && RegCR.status() == QSettings::NoError); #else return false; #endif // Q_WS_WIN }
//---------------------------------------------------------------------------- ctkDICOMServerNodeWidget::ctkDICOMServerNodeWidget(QWidget* _parent):Superclass(_parent), d_ptr(new ctkDICOMServerNodeWidgetPrivate) { Q_D(ctkDICOMServerNodeWidget); d->setupUi(this); // checkable headers. d->nodeTable->model()->setHeaderData(0, Qt::Horizontal, Qt::Unchecked, Qt::CheckStateRole); QHeaderView* previousHeaderView = d->nodeTable->horizontalHeader(); ctkCheckableHeaderView* headerView = new ctkCheckableHeaderView(Qt::Horizontal, d->nodeTable); headerView->setClickable(previousHeaderView->isClickable()); headerView->setMovable(previousHeaderView->isMovable()); headerView->setHighlightSections(previousHeaderView->highlightSections()); headerView->setPropagateToItems(true); d->nodeTable->setHorizontalHeader(headerView); d->removeButton->setEnabled(false); QSettings settings; QMap<QString, QVariant> node; if ( settings.value("ServerNodeCount").toInt() == 0 ) { node["Name"] = "Local Database"; node["CheckState"] = Qt::Checked; node["AETitle"] = "N/A"; node["Address"] = "N/A"; node["Port"] = "N/A"; settings.setValue("ServerNodeCount", 2); settings.setValue("ServerNodes/0", QVariant(node)); node["Name"] = "ExampleHost"; node["CheckState"] = Qt::Unchecked; node["AETitle"] = "CTK_AE"; node["Address"] = "localhost"; node["Port"] = "11112"; settings.setValue("ServerNodes/1", QVariant(node)); settings.sync(); } int count = settings.value("ServerNodeCount").toInt(); d->nodeTable->setRowCount(count); for (int row = 0; row < count; row++) { node = settings.value(QString("ServerNodes/%1").arg(row)).toMap(); QTableWidgetItem *newItem; newItem = new QTableWidgetItem( node["Name"].toString() ); newItem->setCheckState( Qt::CheckState(node["CheckState"].toInt()) ); d->nodeTable->setItem(row, 0, newItem); newItem = new QTableWidgetItem( node["AETitle"].toString() ); d->nodeTable->setItem(row, 1, newItem); newItem = new QTableWidgetItem( node["Address"].toString() ); d->nodeTable->setItem(row, 2, newItem); newItem = new QTableWidgetItem( node["Port"].toString() ); d->nodeTable->setItem(row, 3, newItem); } connect(d->addButton ,SIGNAL(clicked()), this, SLOT(addNode())); connect(d->removeButton ,SIGNAL(clicked()), this, SLOT(removeNode())); connect(d->nodeTable, SIGNAL(cellChanged(int,int)), this, SLOT(onCellChanged(int,int))); connect(d->nodeTable, SIGNAL(currentItemChanged(QTableWidgetItem*, QTableWidgetItem*)), this, SLOT(onCurrentItemChanged(QTableWidgetItem*, QTableWidgetItem*))); }
Dialog::Dialog() { QSettings *Msettings = new QSettings("main_settings.conf",QSettings::NativeFormat); if (Msettings->value("section/cmd").toString() == NULL) { Msettings->setValue("section/cmd", "sudo /usr/bin/xfreerdp --plugin rdpsnd --data alsa -- --plugin drdynvc --data audin -- --plugin rdpdr --data disk:usb-flash:/media/ -- --sec rdp -f -x lan"); Msettings->sync(); } QSettings *settings = new QSettings("disp_settings.conf",QSettings::NativeFormat); if (settings->value("section/mode").toString() != NULL) { if (settings->value("section/display").toString() == "yes") { QProcess process; process.startDetached("/usr/bin/-xrandr -s "+settings->value("section/mode").toString()); process.waitForFinished(-1); } } QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); createFormGroupBox(); caseCheckBox = new QCheckBox(tr("Запомнить параметры экрана")); createXrandr(); reb = new QPushButton(tr("Выключить"),this); admin = new QPushButton(tr("Админ"),this); buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); buttonBox->addButton(reb,QDialogButtonBox::RejectRole); buttonBox->addButton(admin,QDialogButtonBox::HelpRole); connect(buttonBox, SIGNAL(helpRequested()), this, SLOT(radmin())); connect(buttonBox, SIGNAL(accepted()), this, SLOT(romik())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reboot())); connect(caseCombo, SIGNAL(activated(int)), this, SLOT(changeCase(int))); connect(caseCheckBox, SIGNAL(stateChanged(int)), this, SLOT(saveDisplay(int))); if (caseCheckBox->isChecked()) { } QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget(formGroupBox); //! Ввод данных mainLayout->addWidget(caseCombo); //! Выбор разрешения mainLayout->addWidget(caseCheckBox); //! Сохранить параметры экрана mainLayout->addWidget(buttonBox); //! Кноки setLayout(mainLayout); setWindowTitle(tr("Удаленный рабочий стол")); }
void ApplicationHelpers::setLanguage(const QString &language) { QSettings settings; settings.setValue("language", language); settings.sync(); }
void LDesktop::checkResolution(){ //Compare the current screen resolution with the last one used/saved and adjust config values *only* //NOTE: This is only run the first time this desktop is created (before loading all the interface) - not on each desktop change int oldWidth = settings->value(DPREFIX+"screen/lastWidth",-1).toInt(); int oldHeight = settings->value(DPREFIX+"screen/lastHeight",-1).toInt(); QRect scrn = LSession::handle()->screenGeom(desktopnumber); if(scrn.isNull()){ return; } issyncing = true; settings->setValue(DPREFIX+"screen/lastWidth",scrn.width()); settings->setValue(DPREFIX+"screen/lastHeight",scrn.height()); if(oldWidth<1 || oldHeight<1 || scrn.width()<1 || scrn.height()<1){ //nothing to do - something invalid }else if(scrn.width()==oldWidth && scrn.height()==oldHeight){ //nothing to do - same as before }else{ //Calculate the scale factor between the old/new sizes in each dimension // and forward that on to all the interface elements double xscale = scrn.width()/((double) oldWidth); double yscale = scrn.height()/((double) oldHeight); if(DEBUG){ qDebug() << "Screen Resolution Changed:" << desktopnumber; qDebug() << " - Old:" << QString::number(oldWidth)+"x"+QString::number(oldHeight); qDebug() << " - New:" << QString::number(scrn.width())+"x"+QString::number(scrn.height()); qDebug() << " - Scale Factors:" << xscale << yscale; } //Update any panels in the config file for(int i=0; i<4; i++){ QString PPREFIX = "panel"+QString::number(desktopnumber)+"."+QString::number(i)+"/"; int ht = settings->value(PPREFIX+"height",-1).toInt(); if(ht<1){ continue; } //no panel height defined QString loc = settings->value(PPREFIX+"location","top").toString().toLower(); if(loc=="top" || loc=="bottom"){ settings->setValue(PPREFIX+"height", (int) ht*yscale); //vertical dimension }else{ settings->setValue(PPREFIX+"height", (int) ht*xscale); //horizontal dimension } } //Update any desktop plugins QStringList plugs = settings->value(DPREFIX+"pluginlist").toStringList(); QFileInfoList files = LSession::handle()->DesktopFiles(); for(int i=0; i<files.length(); i++){ plugs << "applauncher::"+files[i].absoluteFilePath()+"---"+DPREFIX; } //QString pspath = QDir::homePath()+"/.lumina/desktop-plugins/%1.conf"; QSettings *DP = LSession::handle()->DesktopPluginSettings(); QStringList keys = DP->allKeys(); for(int i=0; i<plugs.length(); i++){ QStringList filter = keys.filter(plugs[i]); for(int j=0; j<filter.length(); j++){ //Has existing settings - need to adjust it if(filter[j].endsWith("location/height")){ DP->setValue( filter[j], qRound(DP->value(filter[j]).toInt()*yscale) ); } if(filter[j].endsWith("location/width")){ DP->setValue( filter[j], qRound(DP->value(filter[j]).toInt()*xscale) ); } if(filter[j].endsWith("location/x")){ DP->setValue( filter[j], qRound(DP->value(filter[j]).toInt()*xscale) ); } if(filter[j].endsWith("location/y")){ DP->setValue( filter[j], qRound(DP->value(filter[j]).toInt()*yscale) ); } if(filter[j].endsWith("IconSize")){ DP->setValue( filter[j], qRound(DP->value(filter[j]).toInt()*yscale) ); } if(filter[j].endsWith("iconsize")){ DP->setValue( filter[j], qRound(DP->value(filter[j]).toInt()*yscale) ); } } } DP->sync(); //make sure it gets saved to disk right away } issyncing = false; }
void ServiceManager::loadDefaultSettings() { QString defaultdir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation); // save config to /sdcard, remove when the app works properly qputenv("XDG_CONFIG_HOME", defaultdir.toLocal8Bit()); QSettings settings; // skip initialization if some config is already present if(!settings.value("appsPath").isNull()) return; qDebug("saving to: %s", qPrintable(settings.fileName())); defaultdir = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); qDebug("photoPath: %s", qPrintable(defaultdir)); settings.setValue("photoPath", defaultdir); defaultdir = QStandardPaths::writableLocation(QStandardPaths::MusicLocation); qDebug("musicPath: %s", qPrintable(defaultdir)); settings.setValue("musicPath", defaultdir); defaultdir = QStandardPaths::writableLocation(QStandardPaths::MoviesLocation); qDebug("photoPath: %s", qPrintable(defaultdir)); settings.setValue("videoPath", defaultdir); defaultdir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation); defaultdir.append(QDir::separator()).append("PS Vita"); qDebug("appsPath: %s", qPrintable(defaultdir)); settings.setValue("appsPath", defaultdir); defaultdir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation); defaultdir.append(QDir::separator()).append("PSV Updates"); qDebug("urlPath: %s", qPrintable(defaultdir)); settings.setValue("urlPath", defaultdir); defaultdir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation); defaultdir.append(QDir::separator()).append("PSV Packages"); qDebug("pkgPath: %s", qPrintable(defaultdir)); settings.setValue("pkgPath", defaultdir); settings.setValue("offlineMode", true); settings.setValue("skipMetadata", false); // disable USB for now settings.setValue("disableUSB", true); settings.setValue("disableWireless", false); settings.setValue("useMemoryStorage", true); settings.setValue("photoSkip", false); settings.setValue("videoSkip", false); settings.setValue("musicSkip", false); settings.setValue("protocolMode", "automatic"); settings.setValue("protocolIndex", 0); settings.setValue("protocolVersion", VITAMTP_PROTOCOL_MAX_VERSION); QString deviceName = QAndroidJniObject::getStaticObjectField( "android/os/Build", "MODEL", "Ljava/lang/String;").toString(); qDebug("Detected device model: %s", qPrintable(deviceName)); settings.setValue("hostName", deviceName); settings.sync(); }
void ConfigWindow::save_settings() { QSettings settings; // Check if we have to update the pony windows with new always-on-top/bypass-wm value bool change_ontop = (getSetting<bool>("general/always-on-top", settings) != ui->alwaysontop->isChecked()); bool change_bypass_wm = (getSetting<bool>("general/bypass-wm", settings) != ui->x11_bypass_wm->isChecked()); bool reload_ponies = (getSetting<QString>("general/pony-directory", settings) != ui->ponydata_directory->text()); // Write the program settings settings.clear(); // General settings settings.beginGroup("general"); settings.setValue("always-on-top", ui->alwaysontop->isChecked()); settings.setValue("bypass-wm", ui->x11_bypass_wm->isChecked()); settings.setValue("pony-directory", ui->ponydata_directory->text()); settings.setValue("interactions-enabled", ui->interactions_enabled->isChecked()); settings.setValue("debug", ui->debug_enabled->isChecked()); settings.setValue("show-advanced", ui->show_advanced->isChecked()); debug = getSetting<bool>("debug", settings); settings.endGroup(); // Speech settings settings.beginGroup("speech"); settings.setValue("enabled", ui->speechenabled->isChecked()); settings.setValue("duration", ui->textdelay->value()); settings.setValue("probability", ui->speechprobability->value()); settings.endGroup(); // Sound settings settings.beginGroup("sound"); settings.setValue("enabled", ui->playsounds->isChecked()); settings.endGroup(); // Write the active ponies list settings.beginWriteArray("loaded-ponies"); int i=0; for(const auto &pony : ponies) { if(change_ontop) { pony->set_on_top(ui->alwaysontop->isChecked()); } if(change_bypass_wm) { pony->set_bypass_wm(ui->x11_bypass_wm->isChecked()); } settings.setArrayIndex(i); settings.setValue("name", pony->directory); i++; } settings.endArray(); if(reload_ponies) { reload_available_ponies(); } // Make sure we write our changes to disk settings.sync(); }
//---------------------------------------------------------------------------- ctkDICOMAppWidget::ctkDICOMAppWidget(QWidget* _parent):Superclass(_parent), d_ptr(new ctkDICOMAppWidgetPrivate(this)) { Q_D(ctkDICOMAppWidget); d->setupUi(this); this->setSearchWidgetPopUpMode(false); //Hide image previewer buttons d->NextImageButton->hide(); d->PrevImageButton->hide(); d->NextSeriesButton->hide(); d->PrevSeriesButton->hide(); d->NextStudyButton->hide(); d->PrevStudyButton->hide(); //Enable sorting in tree view d->TreeView->setSortingEnabled(true); d->TreeView->setSelectionBehavior(QAbstractItemView::SelectRows); d->DICOMProxyModel.setSourceModel(&d->DICOMModel); d->TreeView->setModel(&d->DICOMModel); d->ThumbnailsWidget->setThumbnailSize( QSize(d->ThumbnailWidthSlider->value(), d->ThumbnailWidthSlider->value())); connect(d->TreeView, SIGNAL(collapsed(QModelIndex)), this, SLOT(onTreeCollapsed(QModelIndex))); connect(d->TreeView, SIGNAL(expanded(QModelIndex)), this, SLOT(onTreeExpanded(QModelIndex))); //Set ToolBar button style d->ToolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); //Initialize Q/R widget d->QueryRetrieveWidget = new ctkDICOMQueryRetrieveWidget(); d->QueryRetrieveWidget->setWindowModality ( Qt::ApplicationModal ); //initialize directory from settings, then listen for changes QSettings settings; if ( settings.value("DatabaseDirectory", "") == "" ) { QString directory = QString("./ctkDICOM-Database"); settings.setValue("DatabaseDirectory", directory); settings.sync(); } QString databaseDirectory = settings.value("DatabaseDirectory").toString(); this->setDatabaseDirectory(databaseDirectory); d->DirectoryButton->setDirectory(databaseDirectory); connect(d->DirectoryButton, SIGNAL(directoryChanged(QString)), this, SLOT(setDatabaseDirectory(QString))); //Initialize import widget d->ImportDialog = new ctkFileDialog(); QCheckBox* importCheckbox = new QCheckBox("Copy on import", d->ImportDialog); d->ImportDialog->setBottomWidget(importCheckbox); d->ImportDialog->setFileMode(QFileDialog::Directory); d->ImportDialog->setLabelText(QFileDialog::Accept,"Import"); d->ImportDialog->setWindowTitle("Import DICOM files from directory ..."); d->ImportDialog->setWindowModality(Qt::ApplicationModal); //connect signal and slots connect(d->TreeView, SIGNAL(clicked(QModelIndex)), d->ThumbnailsWidget, SLOT(onModelSelected(QModelIndex))); connect(d->TreeView, SIGNAL(clicked(QModelIndex)), d->ImagePreview, SLOT(onModelSelected(QModelIndex))); connect(d->TreeView, SIGNAL(clicked(QModelIndex)), this, SLOT(onModelSelected(QModelIndex))); connect(d->ThumbnailsWidget, SIGNAL(selected(ctkThumbnailLabel)), this, SLOT(onThumbnailSelected(ctkThumbnailLabel))); connect(d->ThumbnailsWidget, SIGNAL(doubleClicked(ctkThumbnailLabel)), this, SLOT(onThumbnailDoubleClicked(ctkThumbnailLabel))); connect(d->ImportDialog, SIGNAL(fileSelected(QString)),this,SLOT(onImportDirectory(QString))); connect(d->QueryRetrieveWidget, SIGNAL(canceled()), d->QueryRetrieveWidget, SLOT(hide()) ); connect(d->QueryRetrieveWidget, SIGNAL(canceled()), this, SLOT(onQueryRetrieveFinished()) ); connect(d->ImagePreview, SIGNAL(requestNextImage()), this, SLOT(onNextImage())); connect(d->ImagePreview, SIGNAL(requestPreviousImage()), this, SLOT(onPreviousImage())); connect(d->ImagePreview, SIGNAL(imageDisplayed(int,int)), this, SLOT(onImagePreviewDisplayed(int,int))); connect(d->SearchOption, SIGNAL(parameterChanged()), this, SLOT(onSearchParameterChanged())); connect(d->PlaySlider, SIGNAL(valueChanged(int)), d->ImagePreview, SLOT(displayImage(int))); }
connect(ui->pushButton_link,&QPushButton::clicked,[=]{ //test ->TODO:delete this line connect(this,SIGNAL(sendConnectSocketReturn(int,bool)),this,SLOT(finishedConnectSlot(int ,bool))); ui->pushButton_link->setEnabled(false); // ui->pushButton_put->setEnabled(true);//TODO:should check has data in table... // ui->pushButton_weigh->setEnabled(false); ui->pushButton_weigh->setEnabled(true);//TODO:test to change true.should be delete; emit sendConnectSocket(_GroupIpList); emit sendConnectSocketReturn(ui->combGroup->currentText().toInt(),true); }); connect(ui->pushButton_close,&QPushButton::clicked,[=]{ QSettings setting;//将对应每一项当前连接状态保存到setting里,以便后面读取及更新界面UI setting.beginGroup(QString("GroupData/%1").arg(ui->combGroup->currentText())); setting.setValue("States",flag);//此处只保存当前组号连接状态 setting.sync();//立即更新以保存 setting.endGroup(); ui->pushButton_link->setEnabled(true); ui->pushButton_close->setEnabled(false); ui->pushButton_put->setEnabled(false); ui->pushButton_weigh->setEnabled(false); emit closeConnect(); }); } Widget::~Widget() { if(TimerGlbDly){ if(TimerGlbDly->isActive())
void QgsNewHttpConnection::accept() { QSettings settings; QString key = mBaseKey + txtName->text(); QString credentialsKey = "/Qgis/" + mCredentialsBaseKey + '/' + txtName->text(); // warn if entry was renamed to an existing connection if (( mOriginalConnName.isNull() || mOriginalConnName.compare( txtName->text(), Qt::CaseInsensitive ) != 0 ) && settings.contains( key + "/url" ) && QMessageBox::question( this, tr( "Save connection" ), tr( "Should the existing connection %1 be overwritten?" ).arg( txtName->text() ), QMessageBox::Ok | QMessageBox::Cancel ) == QMessageBox::Cancel ) { return; } if ( !txtPassword->text().isEmpty() && QMessageBox::question( this, tr( "Saving passwords" ), tr( "WARNING: You have entered a password. It will be stored in plain text in your project files and in your home directory on Unix-like systems, or in your user profile on Windows. If you do not want this to happen, please press the Cancel button.\nNote: giving the password is optional. It will be requested interactivly, when needed." ), QMessageBox::Ok | QMessageBox::Cancel ) == QMessageBox::Cancel ) { return; } // on rename delete original entry first if ( !mOriginalConnName.isNull() && mOriginalConnName != key ) { settings.remove( mBaseKey + mOriginalConnName ); settings.remove( "/Qgis/" + mCredentialsBaseKey + '/' + mOriginalConnName ); settings.sync(); } QUrl url( txtUrl->text().trimmed() ); const QList< QPair<QByteArray, QByteArray> > &items = url.encodedQueryItems(); QHash< QString, QPair<QByteArray, QByteArray> > params; for ( QList< QPair<QByteArray, QByteArray> >::const_iterator it = items.constBegin(); it != items.constEnd(); ++it ) { params.insert( QString( it->first ).toUpper(), *it ); } if ( params["SERVICE"].second.toUpper() == "WMS" || params["SERVICE"].second.toUpper() == "WFS" || params["SERVICE"].second.toUpper() == "WCS" ) { url.removeEncodedQueryItem( params["SERVICE"].first ); url.removeEncodedQueryItem( params["REQUEST"].first ); url.removeEncodedQueryItem( params["FORMAT"].first ); } if ( url.encodedPath().isEmpty() ) { url.setEncodedPath( "/" ); } settings.setValue( key + "/url", url.toString() ); if ( mBaseKey == "/Qgis/connections-wms/" || mBaseKey == "/Qgis/connections-wcs/" || mBaseKey == "/Qgis/connections-wfs/" ) { settings.setValue( key + "/ignoreAxisOrientation", cbxIgnoreAxisOrientation->isChecked() ); settings.setValue( key + "/invertAxisOrientation", cbxInvertAxisOrientation->isChecked() ); } if ( mBaseKey == "/Qgis/connections-wms/" || mBaseKey == "/Qgis/connections-wcs/" ) { settings.setValue( key + "/ignoreGetMapURI", cbxIgnoreGetMapURI->isChecked() ); settings.setValue( key + "/smoothPixmapTransform", cbxSmoothPixmapTransform->isChecked() ); int dpiMode = 0; switch ( cmbDpiMode->currentIndex() ) { case 0: // all => QGIS|UMN|GeoServer dpiMode = 7; break; case 1: // off dpiMode = 0; break; case 2: // QGIS dpiMode = 1; break; case 3: // UMN dpiMode = 2; break; case 4: // GeoServer dpiMode = 4; break; } settings.setValue( key + "/dpiMode", dpiMode ); } if ( mBaseKey == "/Qgis/connections-wms/" ) { settings.setValue( key + "/ignoreGetFeatureInfoURI", cbxIgnoreGetFeatureInfoURI->isChecked() ); } if ( mBaseKey == "/Qgis/connections-wfs/" ) { QString version = "auto"; switch ( cmbVersion->currentIndex() ) { case 0: version = "auto"; break; case 1: version = "1.0.0"; break; case 2: version = "1.1.0"; break; case 3: version = "2.0.0"; break; } settings.setValue( key + "/version", version ); settings.setValue( key + "/maxnumfeatures", txtMaxNumFeatures->text() ); } settings.setValue( key + "/referer", txtReferer->text() ); settings.setValue( credentialsKey + "/username", txtUserName->text() ); settings.setValue( credentialsKey + "/password", txtPassword->text() ); settings.setValue( credentialsKey + "/authcfg", mAuthConfigSelect->configId() ); settings.setValue( mBaseKey + "/selected", txtName->text() ); QDialog::accept(); }
void squeezeLiteGui::Init(void) { qmlRegisterType<ControlListModel>("net.galtfamily.controlListModel",1,0,"ControlListModel"); // qmlRegisterType<ControlListItem>("net.galtfamily.controllistitem",1,0,"ControlListItem"); setSource(QUrl::fromLocalFile("qml/squeezelitegui/squeezeliteguimain.qml")); show(); QSettings *mySettings = new QSettings("squeezelitegui", "squeezelitegui"); if( !mySettings->contains("Version") || mySettings->value("Version")!=DATAVERSION) { // no settings file, so create one mySettings->setValue("Version", DATAVERSION); mySettings->setValue("Server/Address","127.0.0.1"); // mySettings->setValue("Server/Address","10.6.67.54"); mySettings->setValue("Server/AudioPort","3483"); mySettings->setValue("Server/CLIPort", "9090"); mySettings->setValue("Server/HttpPort", "9000"); mySettings->setValue("Server/Username", ""); mySettings->setValue("Server/Password", ""); mySettings->setValue("Audio/Device","default"); mySettings->setValue("Player/Name","squeezelite"); mySettings->sync(); } lmsUsername = mySettings->value("Server/Username","").toString(); lmsPassword = mySettings->value("Server/Password","").toString(); SqueezeBoxServerAddress = mySettings->value("Server/Address","127.0.0.1").toString(); SqueezeBoxServerAudioPort = mySettings->value("Server/AudioPort","3483").toString(); SqueezeBoxServerCLIPort = mySettings->value("Server/CLIPort", "9090").toString(); SqueezeBoxServerHttpPort = mySettings->value("Server/HttpPort", "9000").toString(); AudioDevice = mySettings->value("Audio/Device","").toString(); PlayerName = mySettings->value("Player/Name", "squeezelite").toString(); getplayerMACAddress(); // get the MAC address we are going to use player = new QProcess(this); #ifdef Q_OS_LINUX QString program = "squeezelite"; program += (QString(" -m " + QString( MacAddress ))) + (QString(" -n " + PlayerName)) + (QString(" -o " + AudioDevice)) + " " + SqueezeBoxServerAddress; #else QString program = QString('"')+QString("c:\\program files (x86)\\squeezelite\\squeezelite-win")+QString('"'); program += (QString(" -m " + QString( MacAddress ))) + (QString(" -n " + PlayerName)) + (QString(" -o " + AudioDevice)) + " " + SqueezeBoxServerAddress; #endif DEBUGF( "player command " << program); player->start( program ); DEBUGF("ERROR STRING IF ANY" << player->error() << player->errorString() ); // player->waitForStarted(2000); // // initialize the CLI interface. Make sure that you've set the appropriate server address and port cli = new SlimCLI(0, SqueezeBoxServerAddress, encodedMacAddress, SqueezeBoxServerCLIPort.toInt()); m_cliThread = new cliThread(cli); cli->moveToThread(m_cliThread); connect(cli,SIGNAL(isConnected()), this, SLOT(CliReady())); connect(cli,SIGNAL(cliError(QString)),this,SLOT(ErrorMessageReceiver(QString))); m_cliThread->start(); m_interfaceState = INTERFACE_CLI_STARTED; }
void ConfigBase::writeConfiguration( const QString &profile, const Configuration &config ) { qApp->processEvents(); if ( config.isEmpty() ) { return; } if ( profile.isEmpty() || profile.isNull() ) { return; } QSettings *writeConf = new QSettings( profile, QSettings::IniFormat ); // SDL settings writeConf->beginGroup( "sdl" ); QMap< QString, QVariant >::const_iterator m_Sdl = config.sdl.constBegin(); while ( m_Sdl != config.sdl.constEnd() ) { qApp->processEvents(); writeConf->setValue( m_Sdl.key(), m_Sdl.value() ); ++m_Sdl; } writeConf->endGroup(); // DOSBox settings writeConf->beginGroup( "dosbox" ); QMap< QString, QVariant >::const_iterator m_Dosbox = config.dosbox.constBegin(); while ( m_Dosbox != config.dosbox.constEnd() ) { qApp->processEvents(); writeConf->setValue( m_Dosbox.key(), m_Dosbox.value() ); ++m_Dosbox; } writeConf->endGroup(); // Render settings writeConf->beginGroup( "render" ); QMap< QString, QVariant >::const_iterator m_Render = config.render.constBegin(); while ( m_Render != config.render.constEnd() ) { qApp->processEvents(); writeConf->setValue( m_Render.key(), m_Render.value() ); ++m_Render; } writeConf->endGroup(); // CPU settings writeConf->beginGroup( "cpu" ); QMap< QString, QVariant >::const_iterator m_Cpu = config.cpu.constBegin(); while ( m_Cpu != config.cpu.constEnd() ) { qApp->processEvents(); writeConf->setValue( m_Cpu.key(), m_Cpu.value() ); ++m_Cpu; } writeConf->endGroup(); // Mixer settings writeConf->beginGroup( "mixer" ); QMap< QString, QVariant >::const_iterator m_Mixer = config.mixer.constBegin(); while ( m_Mixer != config.mixer.constEnd() ) { qApp->processEvents(); writeConf->setValue( m_Mixer.key(), m_Mixer.value() ); ++m_Mixer; } writeConf->endGroup(); // Mdi settings writeConf->beginGroup( "midi" ); QMap< QString, QVariant >::const_iterator m_Mdi = config.mdi.constBegin(); while ( m_Mdi != config.mdi.constEnd() ) { qApp->processEvents(); writeConf->setValue( m_Mdi.key(), m_Mdi.value() ); ++m_Mdi; } writeConf->endGroup(); // Soundblaster settings writeConf->beginGroup( "sblaster" ); QMap< QString, QVariant >::const_iterator m_SBlaster = config.sblaster.constBegin(); while ( m_SBlaster != config.sblaster.constEnd() ) { qApp->processEvents(); writeConf->setValue( m_SBlaster.key(), m_SBlaster.value() ); ++m_SBlaster; } writeConf->endGroup(); // GUS settings writeConf->beginGroup( "gus" ); QMap< QString, QVariant >::const_iterator m_Gus = config.gus.constBegin(); while ( m_Gus != config.gus.constEnd() ) { qApp->processEvents(); writeConf->setValue( m_Gus.key(), m_Gus.value() ); ++m_Gus; } writeConf->endGroup(); // PC Speaker settings writeConf->beginGroup( "speaker" ); QMap< QString, QVariant >::const_iterator m_Speaker = config.speaker.constBegin(); while ( m_Speaker != config.speaker.constEnd() ) { qApp->processEvents(); writeConf->setValue( m_Speaker.key(), m_Speaker.value() ); ++m_Speaker; } writeConf->endGroup(); // joystick settings writeConf->beginGroup( "joystick" ); QMap< QString, QVariant >::const_iterator m_Joystick = config.joystick.constBegin(); while ( m_Joystick != config.joystick.constEnd() ) { qApp->processEvents(); writeConf->setValue( m_Joystick.key(), m_Joystick.value() ); ++m_Joystick; } writeConf->endGroup(); // Serial settings writeConf->beginGroup( "serial" ); QMap< QString, QVariant >::const_iterator m_Serial = config.serial.constBegin(); while ( m_Serial != config.serial.constEnd() ) { qApp->processEvents(); writeConf->setValue( m_Serial.key(), m_Serial.value() ); ++m_Serial; } writeConf->endGroup(); // DOS settings writeConf->beginGroup( "dos" ); QMap< QString, QVariant >::const_iterator m_Dos = config.dos.constBegin(); while ( m_Dos != config.dos.constEnd() ) { qApp->processEvents(); writeConf->setValue( m_Dos.key(), m_Dos.value() ); ++m_Dos; } writeConf->endGroup(); // IPX settings writeConf->beginGroup( "ipx" ); writeConf->setValue( "ipx", config.ipx ); writeConf->endGroup(); writeConf->sync(); // Autoexec settings QFile configFile( profile ); if ( !configFile.open( QIODevice::ReadWrite | QIODevice::Text | QIODevice::Append ) ) { qDebug() << QDateTime::currentDateTime().toString( Qt::LocaleDate ) << tr( " - [ERROR] Unable to open and read profile: " ) << configFile.fileName() << endl; return; } QTextStream out( &configFile ); out << "\n[autoexec]\n"; // TODO Write Autoexec // QMap< QString, QStringList>::const_iterator autoexecIt = config.autoexec.constBegin(); // while( autoexecIt != config.autoexec.end() ) { // // QString key = autoexecIt.key(); // QStringList value = autoexecIt.value(); // // if ( line.startsWith( "mount" ) ) { // // mountOptions = line.split( " " ); // m_Configuration.autoexec.insert( "mount", mountOptions ); // // } else if ( line.contains( "bat" ) || line.contains( "com" ) || line.contains( "exe" ) ) { // m_Configuration.autoexec.insert( "executable", QStringList() << line ); // // } else if ( line.contains( ":" ) ) { // mountOptions = line.split( ":" ); // m_Configuration.autoexec.insert( "drive", QStringList() << mountOptions.value( 0 ) ); // m_Configuration.autoexec.insert( "switch", QStringList() << "true" ); // // } else if ( line.startsWith( "exit" ) ) { // m_Configuration.autoexec.insert( "exit", QStringList() << "true" ); // } // // ++autoexecIt; // } out.flush(); configFile.flush(); configFile.close(); delete writeConf; }