Example #1
0
int main(int argc, char *argv[]) {
  if (CrashReporting::SendCrashReport(argc, argv)) {
    return 0;
  }

  CrashReporting crash_reporting;

#ifdef Q_OS_DARWIN
  // Do Mac specific startup to get media keys working.
  // This must go before QApplication initialisation.
  mac::MacMain();
#endif

  QCoreApplication::setApplicationName("Clementine");
  QCoreApplication::setApplicationVersion(CLEMENTINE_VERSION_DISPLAY);
  QCoreApplication::setOrganizationName("Clementine");
  QCoreApplication::setOrganizationDomain("clementine-player.org");

#ifdef Q_OS_DARWIN
  // Must happen after QCoreApplication::setOrganizationName().
  setenv("XDG_CONFIG_HOME", Utilities::GetConfigPath(Utilities::Path_Root).toLocal8Bit().constData(), 1);
  if (mac::MigrateLegacyConfigFiles()) {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(Utilities::GetConfigPath(
        Utilities::Path_Root) + "/" + Database::kDatabaseFilename);
    db.open();
    QSqlQuery query(
        "UPDATE songs SET art_manual = replace("
        "art_manual, '.config', 'Library/Application Support') "
        "WHERE art_manual LIKE '%.config%'", db);
    query.exec();
    db.close();
    QSqlDatabase::removeDatabase(db.connectionName());
  }
#endif

  // This makes us show up nicely in gnome-volume-control
  g_type_init();
  g_set_application_name(QCoreApplication::applicationName().toLocal8Bit());

  RegisterMetaTypes();

#ifdef HAVE_LIBLASTFM
  lastfm::ws::ApiKey = LastFMService::kApiKey;
  lastfm::ws::SharedSecret = LastFMService::kSecret;
  lastfm::setNetworkAccessManager(new NetworkAccessManager);
#endif

  CommandlineOptions options(argc, argv);

  {
    // Only start a core application now so we can check if there's another
    // Clementine running without needing an X server.
    // This MUST be done before parsing the commandline options so QTextCodec
    // gets the right system locale for filenames.
    QtSingleCoreApplication a(argc, argv);
    crash_reporting.SetApplicationPath(a.applicationFilePath());

    // Parse commandline options - need to do this before starting the
    // full QApplication so it works without an X server
    if (!options.Parse())
      return 1;

    if (a.isRunning()) {
      if (options.is_empty()) {
        qLog(Info) << "Clementine is already running - activating existing window";
      }
      if (a.sendMessage(options.Serialize(), 5000)) {
        return 0;
      }
      // Couldn't send the message so start anyway
    }
  }

  // Initialise logging
  logging::Init();
  logging::SetLevels(options.log_levels());
  g_log_set_default_handler(reinterpret_cast<GLogFunc>(&logging::GLog), NULL);

  // Seed the random number generators.
  time_t t = time(NULL);
  srand(t);
  qsrand(t);

  IncreaseFDLimit();

  QtSingleApplication a(argc, argv);

  // A bug in Qt means the wheel_scroll_lines setting gets ignored and replaced
  // with the default value of 3 in QApplicationPrivate::initialize.
  {
    QSettings qt_settings(QSettings::UserScope, "Trolltech");
    qt_settings.beginGroup("Qt");
    QApplication::setWheelScrollLines(
          qt_settings.value("wheelScrollLines",
                            QApplication::wheelScrollLines()).toInt());
  }

#ifdef Q_OS_DARWIN
  QCoreApplication::setLibraryPaths(
      QStringList() << QCoreApplication::applicationDirPath() + "/../PlugIns");
#endif

  a.setQuitOnLastWindowClosed(false);

  // Do this check again because another instance might have started by now
  if (a.isRunning() && a.sendMessage(options.Serialize(), 5000)) {
    return 0;
  }

#ifndef Q_OS_DARWIN
  // Gnome on Ubuntu has menu icons disabled by default.  I think that's a bad
  // idea, and makes some menus in Clementine look confusing.
  QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus, false);
#else
  QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus, true);
  // Fixes focus issue with NSSearchField, see QTBUG-11401
  QCoreApplication::setAttribute(Qt::AA_NativeWindows, true);
#endif

  SetGstreamerEnvironment();

  // Set the permissions on the config file on Unix - it can contain passwords
  // for internet services so it's important that other users can't read it.
  // On Windows these are stored in the registry instead.
#ifdef Q_OS_UNIX
  {
    QSettings s;

    // Create the file if it doesn't exist already
    if (!QFile::exists(s.fileName())) {
      QFile file(s.fileName());
      file.open(QIODevice::WriteOnly);
    }

    // Set -rw-------
    QFile::setPermissions(s.fileName(), QFile::ReadOwner | QFile::WriteOwner);
  }
#endif

#ifdef HAVE_QCA
  QCA::Initializer qca_initializer;
#endif

  // Resources
  Q_INIT_RESOURCE(data);
  Q_INIT_RESOURCE(translations);

  // Grooveshark uses GoDaddy to sign its SSL certificates, which are in turn
  // signed by a ValiCert CA.  This CA certificate isn't installed by default
  // in Windows, it's only added by windows update, or manually browsing to a
  // website with a certificate signed by ValiCert.  Here we explicitly add
  // that CA to the default list used by QSslSocket, so it always works in
  // Clementine.
  QSslSocket::addDefaultCaCertificates(
        QSslCertificate::fromPath(":/grooveshark-valicert-ca.pem", QSsl::Pem));

  // Has the user forced a different language?
  QString language = options.language();
  if (language.isEmpty()) {
    QSettings s;
    s.beginGroup("General");
    language = s.value("language").toString();
  }

  // Translations
  LoadTranslation("qt", QLibraryInfo::location(QLibraryInfo::TranslationsPath), language);
  LoadTranslation("clementine", ":/translations", language);
  LoadTranslation("clementine", a.applicationDirPath(), language);
  LoadTranslation("clementine", QDir::currentPath(), language);

  // Icons
  IconLoader::Init();

  Application app;

  Echonest::Config::instance()->setAPIKey("DFLFLJBUF4EGTXHIG");
  Echonest::Config::instance()->setNetworkAccessManager(new NetworkAccessManager);

  // Network proxy
  QNetworkProxyFactory::setApplicationProxyFactory(
      NetworkProxyFactory::Instance());

  // Initialize the repository of cover providers.  Last.fm registers itself
  // when its service is created.
  app.cover_providers()->AddProvider(new AmazonCoverProvider);
  app.cover_providers()->AddProvider(new DiscogsCoverProvider);

#ifdef Q_OS_LINUX
  // In 11.04 Ubuntu decided that the system tray should be reserved for certain
  // whitelisted applications.  Clementine will override this setting and insert
  // itself into the list of whitelisted apps.
  UbuntuUnityHack hack;
#endif // Q_OS_LINUX

  // Create the tray icon and OSD
  scoped_ptr<SystemTrayIcon> tray_icon(SystemTrayIcon::CreateSystemTrayIcon());
  OSD osd(tray_icon.get(), &app);

#ifdef HAVE_DBUS
  mpris::Mpris mpris(&app);
#endif

  // Window
  MainWindow w(&app, tray_icon.get(), &osd);
#ifdef HAVE_GIO
  ScanGIOModulePath();
#endif
#ifdef HAVE_DBUS
  QObject::connect(&mpris, SIGNAL(RaiseMainWindow()), &w, SLOT(Raise()));
#endif
  QObject::connect(&a, SIGNAL(messageReceived(QByteArray)), &w, SLOT(CommandlineOptionsReceived(QByteArray)));
  w.CommandlineOptionsReceived(options);

  int ret = a.exec();

#ifdef Q_OS_LINUX
  // The nvidia driver would cause Clementine (or any application that used
  // opengl) to use 100% cpu on shutdown.  See:
  //   http://code.google.com/p/clementine-player/issues/detail?id=2088
  //   https://bugs.gentoo.org/show_bug.cgi?id=375615
  // Work around this problem by exiting immediately (and not running the buggy
  // nvidia atexit shutdown handler) if we're using one of the affected versions
  // of the nvidia driver.

  QFile self_maps("/proc/self/maps");
  if (self_maps.open(QIODevice::ReadOnly)) {
    QByteArray data = self_maps.readAll();
    if (data.contains("libnvidia-tls.so.285.03") ||
        data.contains("libnvidia-tls.so.280.13") ||
        data.contains("libnvidia-tls.so.275.28") ||
        data.contains("libnvidia-tls.so.275.19")) {
      qLog(Warning) << "Exiting immediately to work around NVIDIA driver bug";
      _exit(ret);
    }
    self_maps.close();
  }
#endif

  return ret;
}
Example #2
0
/// \brief Read the settings from the last session or another file.
/// \param fileName Optional filename to load the settings from an ini file.
/// \return 0 on success, negative on error.
int DsoSettings::load(const QString &fileName) {
	// Use main configuration if the fileName wasn't set
	QSettings *settingsLoader;
	if(fileName.isEmpty())
		settingsLoader = new QSettings(this);
	else {
		settingsLoader = new QSettings(fileName, QSettings::IniFormat, this);
	}
	if(settingsLoader->status() != QSettings::NoError)
		return -settingsLoader->status();

	// Main window layout and other general options
	settingsLoader->beginGroup("options");
	settingsLoader->beginGroup("window");
	// Docking windows and toolbars
	settingsLoader->beginGroup("docks");
	QList<DsoSettingsOptionsWindowPanel *> docks;
	docks.append(&(this->options.window.dock.horizontal));
	docks.append(&(this->options.window.dock.spectrum));
	docks.append(&(this->options.window.dock.trigger));
	docks.append(&(this->options.window.dock.voltage));
	QStringList dockNames;
	dockNames << "horizontal" << "spectrum" << "trigger" << "voltage";
	for(int dockId = 0; dockId < docks.size(); ++dockId) {
		settingsLoader->beginGroup(dockNames[dockId]);
		if(settingsLoader->contains("floating"))
			docks[dockId]->floating = settingsLoader->value("floating").toBool();
		if(settingsLoader->contains("position"))
			docks[dockId]->position = settingsLoader->value("position").toPoint();
		if(settingsLoader->contains("visible"))
			docks[dockId]->visible = settingsLoader->value("visible").toBool();
		settingsLoader->endGroup();
	}
	settingsLoader->endGroup();
	settingsLoader->beginGroup("toolbars");
	QList<DsoSettingsOptionsWindowPanel *> toolbars;
	toolbars.append(&(this->options.window.toolbar.file));
	toolbars.append(&(this->options.window.toolbar.oscilloscope));
	toolbars.append(&(this->options.window.toolbar.view));
	QStringList toolbarNames;
	toolbarNames << "file" << "oscilloscope" << "view";
	for(int toolbarId = 0; toolbarId < toolbars.size(); ++toolbarId) {
		settingsLoader->beginGroup(toolbarNames[toolbarId]);
		if(settingsLoader->contains("floating"))
			toolbars[toolbarId]->floating = settingsLoader->value("floating").toBool();
		if(settingsLoader->contains("position"))
			toolbars[toolbarId]->position = settingsLoader->value("position").toPoint();
		if(settingsLoader->contains("visible"))
			toolbars[toolbarId]->visible = settingsLoader->value("visible").toBool();
		settingsLoader->endGroup();
	}
	settingsLoader->endGroup();
	// Main window
	if(settingsLoader->contains("pos"))
		this->options.window.position = settingsLoader->value("pos").toPoint();
	if(settingsLoader->contains("size"))
		this->options.window.size = settingsLoader->value("size").toSize();
	settingsLoader->endGroup();
	// General options
	if(settingsLoader->contains("alwaysSave"))
		this->options.alwaysSave = settingsLoader->value("alwaysSave").toBool();
	if(settingsLoader->contains("imageSize"))
		this->options.imageSize = settingsLoader->value("imageSize").toSize();
	settingsLoader->endGroup();
	
	// Oszilloskope settings
	settingsLoader->beginGroup("scope");
	// Horizontal axis
	settingsLoader->beginGroup("horizontal");
	if(settingsLoader->contains("format"))
		this->scope.horizontal.format = (Dso::GraphFormat) settingsLoader->value("format").toInt();
	if(settingsLoader->contains("frequencybase"))
		this->scope.horizontal.frequencybase = settingsLoader->value("frequencybase").toDouble();
	for(int marker = 0; marker < 2; ++marker) {
		QString name;
		name = QString("marker%1").arg(marker);
		if(settingsLoader->contains(name))
			this->scope.horizontal.marker[marker] = settingsLoader->value(name).toDouble();
	}
	if(settingsLoader->contains("timebase"))
		this->scope.horizontal.timebase = settingsLoader->value("timebase").toDouble();
	if(settingsLoader->contains("recordLength"))
		this->scope.horizontal.recordLength = settingsLoader->value("recordLength").toUInt();
	if(settingsLoader->contains("samplerate"))
		this->scope.horizontal.samplerate = settingsLoader->value("samplerate").toDouble();
	if(settingsLoader->contains("samplerateSet"))
		this->scope.horizontal.samplerateSet = settingsLoader->value("samplerateSet").toBool();
	settingsLoader->endGroup();
	// Trigger
	settingsLoader->beginGroup("trigger");
	if(settingsLoader->contains("filter"))
		this->scope.trigger.filter = settingsLoader->value("filter").toBool();
	if(settingsLoader->contains("mode"))
		this->scope.trigger.mode = (Dso::TriggerMode) settingsLoader->value("mode").toInt();
	if(settingsLoader->contains("position"))
		this->scope.trigger.position = settingsLoader->value("position").toDouble();
	if(settingsLoader->contains("slope"))
		this->scope.trigger.slope = (Dso::Slope) settingsLoader->value("slope").toInt();
	if(settingsLoader->contains("source"))
		this->scope.trigger.source = settingsLoader->value("source").toInt();
	if(settingsLoader->contains("special"))
		this->scope.trigger.special = settingsLoader->value("special").toInt();
	settingsLoader->endGroup();
	// Spectrum
	for(int channel = 0; channel < this->scope.spectrum.count(); ++channel) {
		settingsLoader->beginGroup(QString("spectrum%1").arg(channel));
		if(settingsLoader->contains("magnitude"))
			this->scope.spectrum[channel].magnitude = settingsLoader->value("magnitude").toDouble();
		if(settingsLoader->contains("offset"))
			this->scope.spectrum[channel].offset = settingsLoader->value("offset").toDouble();
		if(settingsLoader->contains("used"))
			this->scope.spectrum[channel].used = settingsLoader->value("used").toBool();
		settingsLoader->endGroup();
	}
	// Vertical axis
	for(int channel = 0; channel < this->scope.voltage.count(); ++channel) {
		settingsLoader->beginGroup(QString("vertical%1").arg(channel));
		if(settingsLoader->contains("gain"))
			this->scope.voltage[channel].gain = settingsLoader->value("gain").toDouble();
		if(settingsLoader->contains("misc"))
			this->scope.voltage[channel].misc = settingsLoader->value("misc").toInt();
		if(settingsLoader->contains("offset"))
			this->scope.voltage[channel].offset = settingsLoader->value("offset").toDouble();
		if(settingsLoader->contains("trigger"))
			this->scope.voltage[channel].trigger = settingsLoader->value("trigger").toDouble();
		if(settingsLoader->contains("used"))
			this->scope.voltage[channel].used = settingsLoader->value("used").toBool();
		settingsLoader->endGroup();
	}
	if(settingsLoader->contains("spectrumLimit"))
		this->scope.spectrumLimit = settingsLoader->value("spectrumLimit").toDouble();
	if(settingsLoader->contains("spectrumReference"))
		this->scope.spectrumReference = settingsLoader->value("spectrumReference").toDouble();
	if(settingsLoader->contains("spectrumWindow"))
		this->scope.spectrumWindow = (Dso::WindowFunction) settingsLoader->value("spectrumWindow").toInt();
	settingsLoader->endGroup();
	
	// View
	settingsLoader->beginGroup("view");
	// Colors
	settingsLoader->beginGroup("color");
	DsoSettingsColorValues *colors;
	for(int mode = 0; mode < 2; ++mode) {
		if(mode == 0) {
			colors = &this->view.color.screen;
			settingsLoader->beginGroup("screen");
		}
		else {
			colors = &this->view.color.print;
			settingsLoader->beginGroup("print");
		}
		
		if(settingsLoader->contains("axes"))
			colors->axes = settingsLoader->value("axes").value<QColor>();
		if(settingsLoader->contains("background"))
			colors->background = settingsLoader->value("background").value<QColor>();
		if(settingsLoader->contains("border"))
			colors->border = settingsLoader->value("border").value<QColor>();
		if(settingsLoader->contains("grid"))
			colors->grid = settingsLoader->value("grid").value<QColor>();
		if(settingsLoader->contains("markers"))
			colors->markers = settingsLoader->value("markers").value<QColor>();
		for(int channel = 0; channel < this->scope.spectrum.count(); ++channel) {
			QString key = QString("spectrum%1").arg(channel);
			if(settingsLoader->contains(key))
				colors->spectrum[channel] = settingsLoader->value(key).value<QColor>();
		}
		if(settingsLoader->contains("text"))
			colors->text = settingsLoader->value("text").value<QColor>();
		for(int channel = 0; channel < this->scope.voltage.count(); ++channel) {
			QString key = QString("voltage%1").arg(channel);
			if(settingsLoader->contains(key))
				colors->voltage[channel] = settingsLoader->value(key).value<QColor>();
		}
		settingsLoader->endGroup();
	}
	settingsLoader->endGroup();
	// Other view settings
	if(settingsLoader->contains("digitalPhosphor"))
		this->view.digitalPhosphor = settingsLoader->value("digitalPhosphor").toBool();
	if(settingsLoader->contains("interpolation"))
		this->view.interpolation = (Dso::InterpolationMode) settingsLoader->value("interpolation").toInt();
	if(settingsLoader->contains("screenColorImages"))
		this->view.screenColorImages = (Dso::InterpolationMode) settingsLoader->value("screenColorImages").toBool();
	if(settingsLoader->contains("zoom"))
		this->view.zoom = (Dso::InterpolationMode) settingsLoader->value("zoom").toBool();
	settingsLoader->endGroup();
	
	delete settingsLoader;
	
	return 0;
}
Example #3
0
int main(int argc, char *argv[]) {
  if (CrashReporting::SendCrashReport(argc, argv)) {
    return 0;
  }

  CrashReporting crash_reporting;

#ifdef Q_OS_DARWIN
  // Do Mac specific startup to get media keys working.
  // This must go before QApplication initialisation.
  mac::MacMain();
#endif

  QCoreApplication::setApplicationName("Clementine");
  QCoreApplication::setApplicationVersion(CLEMENTINE_VERSION_DISPLAY);
  QCoreApplication::setOrganizationName("Clementine");
  QCoreApplication::setOrganizationDomain("clementine-player.org");

#ifdef Q_OS_DARWIN
  // Must happen after QCoreApplication::setOrganizationName().
  setenv("XDG_CONFIG_HOME", Utilities::GetConfigPath(Utilities::Path_Root).toLocal8Bit().constData(), 1);
  if (mac::MigrateLegacyConfigFiles()) {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(Utilities::GetConfigPath(
        Utilities::Path_Root) + "/" + Database::kDatabaseFilename);
    db.open();
    QSqlQuery query(
        "UPDATE songs SET art_manual = replace("
        "art_manual, '.config', 'Library/Application Support') "
        "WHERE art_manual LIKE '%.config%'", db);
    query.exec();
    db.close();
    QSqlDatabase::removeDatabase(db.connectionName());
  }
#endif

  // This makes us show up nicely in gnome-volume-control
  g_type_init();
  g_set_application_name(QCoreApplication::applicationName().toLocal8Bit());

  qRegisterMetaType<CoverSearchResult>("CoverSearchResult");
  qRegisterMetaType<QList<CoverSearchResult> >("QList<CoverSearchResult>");
  qRegisterMetaType<CoverSearchResults>("CoverSearchResults");
  qRegisterMetaType<Directory>("Directory");
  qRegisterMetaType<DirectoryList>("DirectoryList");
  qRegisterMetaType<Subdirectory>("Subdirectory");
  qRegisterMetaType<SubdirectoryList>("SubdirectoryList");
  qRegisterMetaType<Song>("Song");
  qRegisterMetaType<QList<Song> >("QList<Song>");
  qRegisterMetaType<SongList>("SongList");
  qRegisterMetaType<PlaylistItemPtr>("PlaylistItemPtr");
  qRegisterMetaType<QList<PlaylistItemPtr> >("QList<PlaylistItemPtr>");
  qRegisterMetaType<PlaylistItemList>("PlaylistItemList");
  qRegisterMetaType<Engine::State>("Engine::State");
  qRegisterMetaType<Engine::SimpleMetaBundle>("Engine::SimpleMetaBundle");
  qRegisterMetaType<Equalizer::Params>("Equalizer::Params");
  qRegisterMetaTypeStreamOperators<Equalizer::Params>("Equalizer::Params");
  qRegisterMetaType<const char*>("const char*");
  qRegisterMetaType<QNetworkReply*>("QNetworkReply*");
  qRegisterMetaType<QNetworkReply**>("QNetworkReply**");
  qRegisterMetaType<smart_playlists::GeneratorPtr>("smart_playlists::GeneratorPtr");
  qRegisterMetaType<ColumnAlignmentMap>("ColumnAlignmentMap");
  qRegisterMetaTypeStreamOperators<QMap<int, int> >("ColumnAlignmentMap");
  qRegisterMetaType<QNetworkCookie>("QNetworkCookie");
  qRegisterMetaType<QList<QNetworkCookie> >("QList<QNetworkCookie>");
  qRegisterMetaType<SearchProvider::Result>("SearchProvider::Result");
  qRegisterMetaType<SearchProvider::ResultList>("SearchProvider::ResultList");
  qRegisterMetaType<DigitallyImportedClient::Channel>("DigitallyImportedClient::Channel");
  qRegisterMetaType<SomaFMService::Stream>("SomaFMService::Stream");
  qRegisterMetaTypeStreamOperators<DigitallyImportedClient::Channel>("DigitallyImportedClient::Channel");
  qRegisterMetaTypeStreamOperators<SomaFMService::Stream>("SomaFMService::Stream");

  qRegisterMetaType<GstBuffer*>("GstBuffer*");
  qRegisterMetaType<GstElement*>("GstElement*");
  qRegisterMetaType<GstEnginePipeline*>("GstEnginePipeline*");

#ifdef HAVE_REMOTE
  qRegisterMetaType<xrme::SIPInfo>("xrme::SIPInfo");
#endif

#ifdef HAVE_LIBLASTFM
  lastfm::ws::ApiKey = LastFMService::kApiKey;
  lastfm::ws::SharedSecret = LastFMService::kSecret;
  lastfm::setNetworkAccessManager(new NetworkAccessManager);
#endif

  CommandlineOptions options(argc, argv);

  {
    // Only start a core application now so we can check if there's another
    // Clementine running without needing an X server.
    // This MUST be done before parsing the commandline options so QTextCodec
    // gets the right system locale for filenames.
    QtSingleCoreApplication a(argc, argv);
    crash_reporting.SetApplicationPath(a.applicationFilePath());

    // Parse commandline options - need to do this before starting the
    // full QApplication so it works without an X server
    if (!options.Parse())
      return 1;

    if (a.isRunning()) {
      if (options.is_empty()) {
        qLog(Info) << "Clementine is already running - activating existing window";
      }
      if (a.sendMessage(options.Serialize(), 5000)) {
        return 0;
      }
      // Couldn't send the message so start anyway
    }
  }

#ifdef Q_OS_LINUX
  // Force Clementine's menu to be shown in the Clementine window and not in
  // the Unity global menubar thing.  See:
  // https://bugs.launchpad.net/unity/+bug/775278
  setenv("QT_X11_NO_NATIVE_MENUBAR", "1", true);
#endif

  // Initialise logging
  logging::Init();
  logging::SetLevels(options.log_levels());
  g_log_set_default_handler(reinterpret_cast<GLogFunc>(&logging::GLog), NULL);

  IncreaseFDLimit();

  QtSingleApplication a(argc, argv);
#ifdef Q_OS_DARWIN
  QCoreApplication::setLibraryPaths(
      QStringList() << QCoreApplication::applicationDirPath() + "/../PlugIns");
#endif

  a.setQuitOnLastWindowClosed(false);

  // Do this check again because another instance might have started by now
  if (a.isRunning() && a.sendMessage(options.Serialize(), 5000)) {
    return 0;
  }

#ifndef Q_OS_DARWIN
  // Gnome on Ubuntu has menu icons disabled by default.  I think that's a bad
  // idea, and makes some menus in Clementine look confusing.
  QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus, false);
#else
  QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus, true);
#endif

  // Set the permissions on the config file on Unix - it can contain passwords
  // for internet services so it's important that other users can't read it.
  // On Windows these are stored in the registry instead.
#ifdef Q_OS_UNIX
  {
    QSettings s;

    // Create the file if it doesn't exist already
    if (!QFile::exists(s.fileName())) {
      QFile file(s.fileName());
      file.open(QIODevice::WriteOnly);
    }

    // Set -rw-------
    QFile::setPermissions(s.fileName(), QFile::ReadOwner | QFile::WriteOwner);
  }
#endif

#ifdef HAVE_QCA
  QCA::Initializer qca_initializer;
#endif

  // Resources
  Q_INIT_RESOURCE(data);
  Q_INIT_RESOURCE(translations);

  // Grooveshark uses GoDaddy to sign its SSL certificates, which are in turn
  // signed by a ValiCert CA.  This CA certificate isn't installed by default
  // in Windows, it's only added by windows update, or manually browsing to a
  // website with a certificate signed by ValiCert.  Here we explicitly add
  // that CA to the default list used by QSslSocket, so it always works in
  // Clementine.
  QSslSocket::addDefaultCaCertificates(
        QSslCertificate::fromPath(":/grooveshark-valicert-ca.pem", QSsl::Pem));

  // Has the user forced a different language?
  QString language = options.language();
  if (language.isEmpty()) {
    QSettings s;
    s.beginGroup("General");
    language = s.value("language").toString();
  }

  // Translations
  LoadTranslation("qt", QLibraryInfo::location(QLibraryInfo::TranslationsPath), language);
  LoadTranslation("clementine", ":/translations", language);
  LoadTranslation("clementine", a.applicationDirPath(), language);
  LoadTranslation("clementine", QDir::currentPath(), language);

  // Icons
  IconLoader::Init();

  // Appearance (UI costumization)
  Appearance appearance;

  Echonest::Config::instance()->setAPIKey("DFLFLJBUF4EGTXHIG");
  Echonest::Config::instance()->setNetworkAccessManager(new NetworkAccessManager);

  // Network proxy
  QNetworkProxyFactory::setApplicationProxyFactory(
      NetworkProxyFactory::Instance());

  // Seed the random number generator
  srand(time(NULL));

  // Initialize the repository of cover providers.  Last.fm registers itself
  // when its service is created.
  CoverProviders cover_providers;
  cover_providers.AddProvider(new AmazonCoverProvider);
  cover_providers.AddProvider(new DiscogsCoverProvider);

  // Create the tag loader on another thread.
  TagReaderClient* tag_reader_client = new TagReaderClient;

  QThread tag_reader_thread;
  tag_reader_thread.start();
  tag_reader_client->moveToThread(&tag_reader_thread);
  tag_reader_client->Start();

  // Create some key objects
  scoped_ptr<BackgroundThread<Database> > database(
      new BackgroundThreadImplementation<Database, Database>(NULL));
  database->Start(true);
  TaskManager task_manager;
  PlaylistManager playlists(&task_manager, NULL);
  Player player(&playlists, &task_manager);
  GlobalSearch global_search;
  InternetModel internet_model(database.get(), &task_manager, &player,
                               &cover_providers, &global_search, NULL);

#ifdef Q_OS_LINUX
  // In 11.04 Ubuntu decided that the system tray should be reserved for certain
  // whitelisted applications.  Clementine will override this setting and insert
  // itself into the list of whitelisted apps.
  UbuntuUnityHack hack;
#endif // Q_OS_LINUX

  // Create the tray icon and OSD
  scoped_ptr<SystemTrayIcon> tray_icon(SystemTrayIcon::CreateSystemTrayIcon());
  OSD osd(tray_icon.get());

  ArtLoader art_loader;

#ifdef HAVE_DBUS
  qDBusRegisterMetaType<QImage>();
  qDBusRegisterMetaType<TrackMetadata>();
  qDBusRegisterMetaType<TrackIds>();
  qDBusRegisterMetaType<QList<QByteArray> >();

  mpris::Mpris mpris(&player, &art_loader);

  QObject::connect(&playlists, SIGNAL(CurrentSongChanged(Song)), &art_loader, SLOT(LoadArt(Song)));
  QObject::connect(&art_loader, SIGNAL(ThumbnailLoaded(Song, QString, QImage)),
                   &osd, SLOT(CoverArtPathReady(Song, QString)));

  GlobalSearchService global_search_service(&global_search);
#endif

  // Window
  MainWindow w(
      database.get(),
      &task_manager,
      &playlists,
      &internet_model,
      &player,
      tray_icon.get(),
      &osd,
      &art_loader,
      &cover_providers,
      &global_search);
#ifdef HAVE_GIO
  ScanGIOModulePath();
#endif
#ifdef HAVE_DBUS
  QObject::connect(&mpris, SIGNAL(RaiseMainWindow()), &w, SLOT(Raise()));
#endif
  QObject::connect(&a, SIGNAL(messageReceived(QByteArray)), &w, SLOT(CommandlineOptionsReceived(QByteArray)));
  w.CommandlineOptionsReceived(options);

  int ret = a.exec();

  tag_reader_client->deleteLater();
  tag_reader_thread.quit();
  tag_reader_thread.wait();

#ifdef Q_OS_LINUX
  // The nvidia driver would cause Clementine (or any application that used
  // opengl) to use 100% cpu on shutdown.  See:
  //   http://code.google.com/p/clementine-player/issues/detail?id=2088
  //   https://bugs.gentoo.org/show_bug.cgi?id=375615
  // Work around this problem by exiting immediately (and not running the buggy
  // nvidia atexit shutdown handler) if we're using one of the affected versions
  // of the nvidia driver.

  QFile self_maps("/proc/self/maps");
  if (self_maps.open(QIODevice::ReadOnly)) {
    QByteArray data = self_maps.readAll();
    if (data.contains("libnvidia-tls.so.285.03") ||
        data.contains("libnvidia-tls.so.280.13") ||
        data.contains("libnvidia-tls.so.275.28") ||
        data.contains("libnvidia-tls.so.275.19")) {
      qLog(Warning) << "Exiting immediately to work around NVIDIA driver bug";
      _exit(ret);
    }
    self_maps.close();
  }
#endif

  return ret;
}
Example #4
0
BrowserApplication::BrowserApplication(int &argc, char **argv)
    : QApplication(argc, argv)
    , m_localServer(0)
{
    QCoreApplication::setOrganizationName(QLatin1String("Qt"));
    QCoreApplication::setApplicationName(QLatin1String("demobrowser"));
    QCoreApplication::setApplicationVersion(QLatin1String("0.1"));
#ifdef Q_WS_QWS
    // Use a different server name for QWS so we can run an X11
    // browser and a QWS browser in parallel on the same machine for
    // debugging
    QString serverName = QCoreApplication::applicationName() + QLatin1String("_qws");
#else
    QString serverName = QCoreApplication::applicationName();
#endif
    QLocalSocket socket;
    socket.connectToServer(serverName);
    if (socket.waitForConnected(500)) {
        QTextStream stream(&socket);
        QStringList args = QCoreApplication::arguments();
        if (args.count() > 1)
            stream << args.last();
        else
            stream << QString();
        stream.flush();
        socket.waitForBytesWritten();
        return;
    }

#if defined(Q_WS_MAC)
    QApplication::setQuitOnLastWindowClosed(false);
#else
    QApplication::setQuitOnLastWindowClosed(true);
#endif

    m_localServer = new QLocalServer(this);
    connect(m_localServer, SIGNAL(newConnection()),
            this, SLOT(newLocalSocketConnection()));
    if (!m_localServer->listen(serverName)) {
        if (m_localServer->serverError() == QAbstractSocket::AddressInUseError
            && QFile::exists(m_localServer->serverName())) {
            QFile::remove(m_localServer->serverName());
            m_localServer->listen(serverName);
        }
    }

#ifndef QT_NO_OPENSSL
    if (!QSslSocket::supportsSsl()) {
    QMessageBox::information(0, "Demo Browser",
                 "This system does not support OpenSSL. SSL websites will not be available.");
    }
#endif

    QDesktopServices::setUrlHandler(QLatin1String("http"), this, "openUrl");
    QString localSysName = QLocale::system().name();

    installTranslator(QLatin1String("qt_") + localSysName);

    QSettings settings;
    settings.beginGroup(QLatin1String("sessions"));
    m_lastSession = settings.value(QLatin1String("lastSession")).toByteArray();
    settings.endGroup();

#if defined(Q_WS_MAC)
    connect(this, SIGNAL(lastWindowClosed()),
            this, SLOT(lastWindowClosed()));
#endif

    QTimer::singleShot(0, this, SLOT(postLaunch()));
}
Example #5
0
void postmarkThread::run()
{
    int argc = 8;
    char *argv[32];
    for (int i = 0; i < 32; ++i)
    {
        argv[i] = new char[32];
    }

    /*
        set location /pmfs
        set size 50 10000
        set read 50
        set write 50
        set buffering false
        set number 1000
        set transactions 50000
        run
    */


    int i = -1;

    ++i;
    //sprintf(argv[++i], "set location %s", param->file_posi.toStdString().c_str() );

    sprintf(argv[++i], "set size %d %d", param->file_size_min, param->file_size_max);

    sprintf(argv[++i], "set read %d", param->read_block_size);
    sprintf(argv[++i], "set write %d", param->write_block_size);

    if (param->use_buffer_checked)
    {
        strcpy(argv[++i], "set buffering false");
    }
    else
    {
        strcpy(argv[++i], "set buffering false");
    }

    sprintf(argv[++i], "set number %d", param->number);

    sprintf(argv[++i], "set transactions %d", param->transactions);

    strcpy(argv[++i], "run");


    delete param;

    QString qsConfigDir("./config.ini");
    QSettings * qsetConfig;
    if(!QFile::exists(qsConfigDir))
    {
        qsetConfig = new QSettings(tr("config.ini"), QSettings::IniFormat);

        qsetConfig->beginGroup("testConfig");
            qsetConfig->setValue("filesize", 16);
            qsetConfig->setValue("flaga", true);
            qsetConfig->setValue("flags", true);
            qsetConfig->setValue("flagi0", true);
            qsetConfig->setValue("flagi1", true);
            qsetConfig->setValue("flagi2", true);
        qsetConfig->endGroup();
        qsetConfig->beginGroup("ramfs");
            qsetConfig->setValue("filename", "/ramfs/tmpfile");
            qsetConfig->setValue("dev", "/dev/ram0");
            qsetConfig->setValue("mnt", "/ramfs");
            qsetConfig->setValue("fstype", "ramfs");
        qsetConfig->endGroup();
        qsetConfig->beginGroup("obfs");
            qsetConfig->setValue("filename", "/obfs/tmpfile");
            qsetConfig->setValue("dev", "/dev/obfsdev");
            qsetConfig->setValue("mnt", "/obfs");
            qsetConfig->setValue("fstype", "obfs");
        qsetConfig->endGroup();
        qsetConfig->beginGroup("pmfs");
            qsetConfig->setValue("filename", "/pmfs/tmpfile");
            qsetConfig->setValue("dev", "/dev/pmfsdev");
            qsetConfig->setValue("mnt", "/pmfs");
            qsetConfig->setValue("fstype", "pmfs");
        qsetConfig->endGroup();
    }
    else{
        /* 读取ini文件 */
        qsetConfig = new QSettings(tr("config.ini"), QSettings::IniFormat);
        //qDebug()<<"read"<<endl;
    }


    QString devDir;/* 设备路径 */
    QString mntDir;/* 挂载路径 */
    QString fsType;/* 文件系统类型 */


    QString command = "mount";
    QStringList args;

    bool useShellToMount = qsetConfig->value("shell").toBool();
    QString shellDir = qsetConfig->value("shelldir").toString();


    //开始postmark的测试

    extern char global_fschararray[FS_NUM][16];
    for (int i = 0; i < FS_NUM; ++i)
    {
        char buff[32];
        if (whichfs & (1 << i))
        {
            pgs->setVisible(true);
            qsetConfig->beginGroup(global_fschararray[i]);
                devDir = qsetConfig->value("dev").toString();
                mntDir = qsetConfig->value("mnt").toString();
                fsType = qsetConfig->value("fstype").toString();
            qsetConfig->endGroup();

            if (useShellToMount)
            {
                /* 执行shell 以"sh ./shell fstype mount"格式 */
                command = "sh";
                args.clear();
                args << shellDir << fsType << "mount";
                QProcess::execute( command, args );
            }
            else
            {
                //mkfs
                label->setText("Formatting Device ...");
                command = "mkfs";
                args.clear();
                args.append("-t");
                args.append(fsType);
                args.append(devDir);
                QProcess::execute(command, args);

                //挂载
                sprintf(buff, "Mounting %s ...", global_fschararray[i]);
                label->setText(buff);
                command = "mount";
                args.clear();
                args.append("-t");
                args.append(fsType);
                args.append(devDir);
                args.append(mntDir);
                QProcess::execute(command, args);
                sprintf(argv[0], "set location %s", mntDir.toStdString().c_str() );
                sprintf(buff, "Testing %s ...", global_fschararray[i]);
                label->setText(buff);
            }

            sleep(1);/* 给时间完成以上工作 */


            //Postmark
            postmark_main(i, argc, argv);


            //umount
            if (useShellToMount)
            {
                /* 执行shell 以"sh ./shell fstype umount"格式 */
                command = "sh";
                args.clear();
                args << shellDir << fsType << "umount";
                QProcess::execute( command, args );
            }
            else
            {
                sprintf(buff, "Umounting %s ...", global_fschararray[i]);
                label->setText(buff);
                command = "umount";
                args.clear();
                args.append(mntDir);
                QProcess::execute(command, args);
            }

        }
    }

    //send thread end signal
    notifyGUI_2_int(FS_NUM-1, 4, 0, 0, 0);

    pgs->setVisible(false);
    label->setText("");



    for (int i = 0; i < 32; ++i)
    {
        delete[] argv[i];
    }
}
void QgsManageConnectionsDialog::loadOracleConnections( const QDomDocument &doc, const QStringList &items )
{
  QDomElement root = doc.documentElement();
  if ( root.tagName() != QLatin1String( "qgsOracleConnections" ) )
  {
    QMessageBox::information( this,
                              tr( "Loading connections" ),
                              tr( "The file is not an Oracle connections exchange file." ) );
    return;
  }

  QString connectionName;
  QSettings settings;
  settings.beginGroup( QStringLiteral( "/Oracle/connections" ) );
  QStringList keys = settings.childGroups();
  settings.endGroup();
  QDomElement child = root.firstChildElement();
  bool prompt = true;
  bool overwrite = true;

  while ( !child.isNull() )
  {
    connectionName = child.attribute( QStringLiteral( "name" ) );
    if ( !items.contains( connectionName ) )
    {
      child = child.nextSiblingElement();
      continue;
    }

    // check for duplicates
    if ( keys.contains( connectionName ) && prompt )
    {
      int res = QMessageBox::warning( this,
                                      tr( "Loading connections" ),
                                      tr( "Connection with name '%1' already exists. Overwrite?" )
                                      .arg( connectionName ),
                                      QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No | QMessageBox::NoToAll | QMessageBox::Cancel );
      switch ( res )
      {
        case QMessageBox::Cancel:
          return;
        case QMessageBox::No:
          child = child.nextSiblingElement();
          continue;
        case QMessageBox::Yes:
          overwrite = true;
          break;
        case QMessageBox::YesToAll:
          prompt = false;
          overwrite = true;
          break;
        case QMessageBox::NoToAll:
          prompt = false;
          overwrite = false;
          break;
      }
    }

    if ( keys.contains( connectionName ) && !overwrite )
    {
      child = child.nextSiblingElement();
      continue;
    }

    //no dups detected or overwrite is allowed
    settings.beginGroup( "/Oracle/connections/" + connectionName );

    settings.setValue( QStringLiteral( "/host" ), child.attribute( QStringLiteral( "host" ) ) );
    settings.setValue( QStringLiteral( "/port" ), child.attribute( QStringLiteral( "port" ) ) );
    settings.setValue( QStringLiteral( "/database" ), child.attribute( QStringLiteral( "database" ) ) );
    settings.setValue( QStringLiteral( "/dboptions" ), child.attribute( QStringLiteral( "dboptions" ) ) );
    settings.setValue( QStringLiteral( "/dbworkspace" ), child.attribute( QStringLiteral( "dbworkspace" ) ) );
    settings.setValue( QStringLiteral( "/estimatedMetadata" ), child.attribute( QStringLiteral( "estimatedMetadata" ) ) );
    settings.setValue( QStringLiteral( "/userTablesOnly" ), child.attribute( QStringLiteral( "userTablesOnly" ) ) );
    settings.setValue( QStringLiteral( "/geometryColumnsOnly" ), child.attribute( QStringLiteral( "geometryColumnsOnly" ) ) );
    settings.setValue( QStringLiteral( "/allowGeometrylessTables" ), child.attribute( QStringLiteral( "allowGeometrylessTables" ) ) );
    settings.setValue( QStringLiteral( "/saveUsername" ), child.attribute( QStringLiteral( "saveUsername" ) ) );
    settings.setValue( QStringLiteral( "/username" ), child.attribute( QStringLiteral( "username" ) ) );
    settings.setValue( QStringLiteral( "/savePassword" ), child.attribute( QStringLiteral( "savePassword" ) ) );
    settings.setValue( QStringLiteral( "/password" ), child.attribute( QStringLiteral( "password" ) ) );
    settings.endGroup();

    child = child.nextSiblingElement();
  }
}
Example #7
0
void SettingsDialog::saveToSettings()
{
    QSettings settings;
    settings.beginGroup(QLatin1String("MainWindow"));
    settings.setValue(QLatin1String("home"), homeLineEdit->text());
    settings.endGroup();

    settings.beginGroup(QLatin1String("general"));
    settings.setValue(QLatin1String("openLinksIn"), openLinksIn->currentIndex());
    settings.endGroup();

    settings.beginGroup(QLatin1String("history"));
    int historyExpire = expireHistory->currentIndex();
    int idx = -1;
    switch (historyExpire) {
    case 0:
        idx = 1;
        break;
    case 1:
        idx = 7;
        break;
    case 2:
        idx = 14;
        break;
    case 3:
        idx = 30;
        break;
    case 4:
        idx = 365;
        break;
    case 5:
        idx = -1;
        break;
    }
    settings.setValue(QLatin1String("historyExpire"), idx);
    settings.endGroup();

    // Appearance
    settings.beginGroup(QLatin1String("websettings"));
    settings.setValue(QLatin1String("fixedFont"), fixedFont);
    settings.setValue(QLatin1String("standardFont"), standardFont);
    settings.setValue(QLatin1String("enableJavascript"), enableJavascript->isChecked());
    settings.setValue(QLatin1String("enablePlugins"), enablePlugins->isChecked());
    QString userStyleSheetString = userStyleSheet->text();
    if (QFile::exists(userStyleSheetString))
        settings.setValue(QLatin1String("userStyleSheet"), QUrl::fromLocalFile(userStyleSheetString));
    else
        settings.setValue(QLatin1String("userStyleSheet"), QUrl(userStyleSheetString));
    settings.endGroup();

    //Privacy
    settings.beginGroup(QLatin1String("cookies"));

    CookieJar::KeepPolicy keepCookies;
    switch(acceptCombo->currentIndex()) {
    default:
    case 0:
        keepCookies = CookieJar::KeepUntilExpire;
        break;
    case 1:
        keepCookies = CookieJar::KeepUntilExit;
        break;
    case 2:
        keepCookies = CookieJar::KeepUntilTimeLimit;
        break;
    }
    CookieJar *jar = BrowserApplication::cookieJar();
    QMetaEnum acceptPolicyEnum = jar->staticMetaObject.enumerator(jar->staticMetaObject.indexOfEnumerator("AcceptPolicy"));
    settings.setValue(QLatin1String("acceptCookies"), QLatin1String(acceptPolicyEnum.valueToKey(keepCookies)));

    CookieJar::KeepPolicy keepPolicy;
    switch(keepUntilCombo->currentIndex()) {
    default:
    case 0:
        keepPolicy = CookieJar::KeepUntilExpire;
        break;
    case 1:
        keepPolicy = CookieJar::KeepUntilExit;
        break;
    case 2:
        keepPolicy = CookieJar::KeepUntilTimeLimit;
        break;
    }

    QMetaEnum keepPolicyEnum = jar->staticMetaObject.enumerator(jar->staticMetaObject.indexOfEnumerator("KeepPolicy"));
    settings.setValue(QLatin1String("keepCookiesUntil"), QLatin1String(keepPolicyEnum.valueToKey(keepPolicy)));

    settings.endGroup();

    // proxy
    settings.beginGroup(QLatin1String("proxy"));
    settings.setValue(QLatin1String("enabled"), proxySupport->isChecked());
    settings.setValue(QLatin1String("type"), proxyType->currentIndex());
    settings.setValue(QLatin1String("hostName"), proxyHostName->text());
    settings.setValue(QLatin1String("port"), proxyPort->text());
    settings.setValue(QLatin1String("userName"), proxyUserName->text());
    settings.setValue(QLatin1String("password"), proxyPassword->text());
    settings.endGroup();

    BrowserApplication::instance()->loadSettings();
    BrowserApplication::networkAccessManager()->loadSettings();
    BrowserApplication::cookieJar()->loadSettings();
    BrowserApplication::historyManager()->loadSettings();
}
/*!
    \fn OptionsDialog::setSetting(const QString& group, const QString& key, QVariant value)
 */
void OptionsDialog::setSetting(const QString& group, const QString& key, QVariant value) {
    QSettings lokalSettings;
    lokalSettings.beginGroup(group);
    lokalSettings.setValue(key, value);
    lokalSettings.endGroup();
}
/*!
    \fn OptionsDialog::removeSetting(const QString& group, const QString& key)
 */
void OptionsDialog::removeSetting(const QString& group, const QString& key) {
    QSettings lokalSettings;
    lokalSettings.beginGroup(group);
    lokalSettings.remove(key);
    lokalSettings.endGroup();
}
Example #10
0
NowPlayingWidget::NowPlayingWidget(QWidget* parent)
    : QWidget(parent),
      app_(nullptr),
      album_cover_choice_controller_(new AlbumCoverChoiceController(this)),
      mode_(SmallSongDetails),
      menu_(new QMenu(this)),
      above_statusbar_action_(nullptr),
      fit_cover_width_action_(nullptr),
      visible_(false),
      small_ideal_height_(0),
      fit_width_(false),
      show_hide_animation_(new QTimeLine(500, this)),
      fade_animation_(new QTimeLine(1000, this)),
      details_(new QTextDocument(this)),
      previous_track_opacity_(0.0),
      bask_in_his_glory_action_(nullptr),
      downloading_covers_(false),
      aww_(false),
      kittens_(nullptr),
      pending_kitten_(0) {
  // Load settings
  QSettings s;
  s.beginGroup(kSettingsGroup);
  mode_ = Mode(s.value("mode", SmallSongDetails).toInt());
  album_cover_choice_controller_->search_cover_auto_action()->setChecked(
      s.value("search_for_cover_auto", false).toBool());
  fit_width_ = s.value("fit_cover_width", false).toBool();

  // Accept drops for setting album art
  setAcceptDrops(true);

  // Context menu
  QActionGroup* mode_group = new QActionGroup(this);
  QSignalMapper* mode_mapper = new QSignalMapper(this);
  connect(mode_mapper, SIGNAL(mapped(int)), SLOT(SetMode(int)));
  CreateModeAction(SmallSongDetails, tr("Small album cover"), mode_group,
                   mode_mapper);
  CreateModeAction(LargeSongDetails, tr("Large album cover"), mode_group,
                   mode_mapper);
  CreateModeAction(LargeSongDetailsBelow,
                   tr("Large album cover (details below)"), mode_group,
                   mode_mapper);

  menu_->addActions(mode_group->actions());

  fit_cover_width_action_ = menu_->addAction(tr("Fit cover to width"));

  fit_cover_width_action_->setCheckable(true);
  fit_cover_width_action_->setEnabled((mode_ != SmallSongDetails) ? true
                                                                  : false);
  connect(fit_cover_width_action_, SIGNAL(toggled(bool)),
          SLOT(FitCoverWidth(bool)));
  fit_cover_width_action_->setChecked(fit_width_);
  menu_->addSeparator();

  QList<QAction*> actions = album_cover_choice_controller_->GetAllActions();

  // Here we add the search automatically action, too!
  actions.append(album_cover_choice_controller_->search_cover_auto_action());

  connect(album_cover_choice_controller_->cover_from_file_action(),
          SIGNAL(triggered()), this, SLOT(LoadCoverFromFile()));
  connect(album_cover_choice_controller_->cover_to_file_action(),
          SIGNAL(triggered()), this, SLOT(SaveCoverToFile()));
  connect(album_cover_choice_controller_->cover_from_url_action(),
          SIGNAL(triggered()), this, SLOT(LoadCoverFromURL()));
  connect(album_cover_choice_controller_->search_for_cover_action(),
          SIGNAL(triggered()), this, SLOT(SearchForCover()));
  connect(album_cover_choice_controller_->unset_cover_action(),
          SIGNAL(triggered()), this, SLOT(UnsetCover()));
  connect(album_cover_choice_controller_->show_cover_action(),
          SIGNAL(triggered()), this, SLOT(ShowCover()));
  connect(album_cover_choice_controller_->search_cover_auto_action(),
          SIGNAL(triggered()), this, SLOT(SearchCoverAutomatically()));

  menu_->addActions(actions);
  menu_->addSeparator();
  above_statusbar_action_ = menu_->addAction(tr("Show above status bar"));

  above_statusbar_action_->setCheckable(true);
  connect(above_statusbar_action_, SIGNAL(toggled(bool)),
          SLOT(ShowAboveStatusBar(bool)));
  above_statusbar_action_->setChecked(
      s.value("above_status_bar", false).toBool());

  bask_in_his_glory_action_ =
      menu_->addAction(tr("ALL GLORY TO THE HYPNOTOAD"));
  bask_in_his_glory_action_->setVisible(false);
  connect(bask_in_his_glory_action_, SIGNAL(triggered()), SLOT(Bask()));

  // Animations
  connect(show_hide_animation_, SIGNAL(frameChanged(int)),
          SLOT(SetHeight(int)));
  setMaximumHeight(0);

  connect(fade_animation_, SIGNAL(valueChanged(qreal)),
          SLOT(FadePreviousTrack(qreal)));
  fade_animation_->setDirection(QTimeLine::Backward);  // 1.0 -> 0.0

  // add placeholder text to get the correct height
  if (mode_ == LargeSongDetailsBelow) {
    details_->setDefaultStyleSheet(
        "p {"
        "  font-size: small;"
        "  color: white;"
        "}");
    details_->setHtml(QString("<p align=center><i></i><br/><br/></p>"));
  }

  UpdateHeight();

  connect(album_cover_choice_controller_, SIGNAL(AutomaticCoverSearchDone()),
          this, SLOT(AutomaticCoverSearchDone()));
}
Example #11
0
void PlaylistTabBar::Close() {
  if (menu_index_ == -1) return;

  const int playlist_id = tabData(menu_index_).toInt();

  QSettings s;
  s.beginGroup(kSettingsGroup);

  const bool ask_for_delete = s.value("warn_close_playlist", true).toBool();

  if (ask_for_delete && !manager_->IsPlaylistFavorite(playlist_id) &&
      !manager_->playlist(playlist_id)->GetAllSongs().empty()) {
    QMessageBox confirmation_box;
    confirmation_box.setWindowIcon(QIcon(":/icon.png"));
    confirmation_box.setWindowTitle(tr("Remove playlist"));
    confirmation_box.setIcon(QMessageBox::Question);
    confirmation_box.setText(
        tr("You are about to remove a playlist which is not part of your "
           "favorite playlists: "
           "the playlist will be deleted (this action cannot be undone). \n"
           "Are you sure you want to continue?"));
    confirmation_box.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);

    QCheckBox dont_prompt_again(tr("Warn me when closing a playlist tab"),
                                &confirmation_box);
    dont_prompt_again.setChecked(ask_for_delete);
    dont_prompt_again.blockSignals(true);
    dont_prompt_again.setToolTip(
        tr("This option can be changed in the \"Behavior\" preferences"));

    QGridLayout* grid = qobject_cast<QGridLayout*>(confirmation_box.layout());
    QDialogButtonBox* buttons = confirmation_box.findChild<QDialogButtonBox*>();
    if (grid && buttons) {
      const int index = grid->indexOf(buttons);
      int row, column, row_span, column_span = 0;
      grid->getItemPosition(index, &row, &column, &row_span, &column_span);
      QLayoutItem* buttonsItem = grid->takeAt(index);
      grid->addWidget(&dont_prompt_again, row, column, row_span, column_span,
                      Qt::AlignLeft | Qt::AlignTop);
      grid->addItem(buttonsItem, ++row, column, row_span, column_span);
    } else {
      confirmation_box.addButton(&dont_prompt_again, QMessageBox::ActionRole);
    }

    if (confirmation_box.exec() != QMessageBox::Yes) {
      return;
    }

    // If user changed the pref, save the new one
    if (dont_prompt_again.isChecked() != ask_for_delete) {
      s.setValue("warn_close_playlist", dont_prompt_again.isChecked());
    }
  }

  // Close the playlist. If the playlist is not a favorite playlist, it will be
  // deleted, as it will not be visible after being closed. Otherwise, the tab
  // is closed but the playlist still exists and can be resurrected from the
  // "Playlists" tab.
  emit Close(playlist_id);

  // Select the nearest tab.
  if (menu_index_ > 1) {
    setCurrentIndex(menu_index_ - 1);
  }

  // Update playlist tab order/visibility
  TabMoved();
}
void QConnectionManager::serviceStateChanged(const QString &state)
{
    NetworkService *service = static_cast<NetworkService *>(sender());
    qDebug() << state << service->name();

    if (currentNetworkState == "disconnect") {
        ua->sendConnectReply("Clear");
    }
    if (state == "failure") {
        serviceInProgress.clear();

        Q_EMIT errorReported(service->path(), "Connection failure: "+ service->name());
        autoConnect();
    }
    if (currentNetworkState == "configuration" && state == "ready"
            && netman->state() != "online") {
        goodConnectTimer->start();
    }

    //manual connection
    if ((state == "ready" || state == "online") && service->path() != serviceInProgress) {
        qDebug() << "manual connection of" << service->path() << "detected, enabling auto connect timeout";
        lastManuallyConnectedService = service->path();
        manualConnnectionTimer.start();
    }

    //auto migrate
    if (service->path() == serviceInProgress
            && state == "online") {
        serviceInProgress.clear();
    }

    //auto migrate
    if (state == "idle") {
        if (lastManuallyConnectedService == service->path()) {
            lastManuallyConnectedService.clear();
            manualConnnectionTimer.invalidate();
        }

        if (serviceInProgress == service->path())
            serviceInProgress.clear();

        previousConnectedService = service->path();
        if (service->type() == "ethernet") { //keep this alive
            NetworkTechnology tech;
            tech.setPath(netman->technologyPathForService(service->path()));
            if (tech.powered()) {
               requestConnect(service->path());
            }
        } else {
            updateServicesMap();
            qDebug() <<"serviceInProgress"<< serviceInProgress;
            // If a manual connection has recently been detected autoConnect() will do nothing.
            // Always call autoConnect() here as this state change could be that manual connection
            // disconnecting.
            autoConnect();
        }
    }

    if (!(currentNetworkState == "online" && state == "association"))
        Q_EMIT connectionState(state, service->type());

        currentNetworkState = state;
        QSettings confFile;
        confFile.beginGroup("Connectionagent");
        confFile.setValue("connected",currentNetworkState);
}
QStringList QgsWMSConnection::connectionList()
{
  QSettings settings;
  settings.beginGroup( "/Qgis/connections-wms" );
  return settings.childGroups();
}
Example #14
0
DlgRegister::DlgRegister(QWidget *parent)
    : QDialog(parent)
{
    QSettings settings;
    settings.beginGroup("server");

    hostLabel = new QLabel(tr("&Host:"));
    hostEdit = new QLineEdit(settings.value("hostname", "cockatrice.woogerworks.com").toString());
    hostLabel->setBuddy(hostEdit);

    portLabel = new QLabel(tr("&Port:"));
    portEdit = new QLineEdit(settings.value("port", "4747").toString());
    portLabel->setBuddy(portEdit);

    playernameLabel = new QLabel(tr("Player &name:"));
    playernameEdit = new QLineEdit(settings.value("playername", "Player").toString());
    playernameLabel->setBuddy(playernameEdit);

    passwordLabel = new QLabel(tr("P&assword:"));
    passwordEdit = new QLineEdit(settings.value("password").toString());
    passwordLabel->setBuddy(passwordEdit);
    passwordEdit->setEchoMode(QLineEdit::Password);

    passwordConfirmationLabel = new QLabel(tr("Password (again):"));
    passwordConfirmationEdit = new QLineEdit();
    passwordConfirmationLabel->setBuddy(passwordConfirmationEdit);
    passwordConfirmationEdit->setEchoMode(QLineEdit::Password);

    emailLabel = new QLabel(tr("Email:"));
    emailEdit = new QLineEdit();
    emailLabel->setBuddy(emailEdit);

    emailConfirmationLabel = new QLabel(tr("Email (again):"));
    emailConfirmationEdit = new QLineEdit();
    emailConfirmationLabel->setBuddy(emailConfirmationEdit);

    genderLabel = new QLabel(tr("Pronouns:"));
    genderEdit = new QComboBox();
    genderLabel->setBuddy(genderEdit);
    genderEdit->insertItem(0, QIcon(":/resources/genders/unknown.svg"), tr("Neutral"));
    genderEdit->insertItem(1, QIcon(":/resources/genders/male.svg"), tr("Masculine"));
    genderEdit->insertItem(2, QIcon(":/resources/genders/female.svg"), tr("Feminine"));
    genderEdit->setCurrentIndex(0);

    countryLabel = new QLabel(tr("Country:"));
    countryEdit = new QComboBox();
    countryLabel->setBuddy(countryEdit);
    countryEdit->insertItem(0, tr("Undefined"));
    countryEdit->setCurrentIndex(0);
    QStringList countries = settingsCache->getCountries();
    foreach(QString c, countries)
        countryEdit->addItem(QPixmap(":/resources/countries/" + c + ".svg"), c);

    realnameLabel = new QLabel(tr("Real name:"));
    realnameEdit = new QLineEdit();
    realnameLabel->setBuddy(realnameEdit);
    
    QGridLayout *grid = new QGridLayout;
    grid->addWidget(hostLabel, 0, 0);
    grid->addWidget(hostEdit, 0, 1);
    grid->addWidget(portLabel, 1, 0);
    grid->addWidget(portEdit, 1, 1);
    grid->addWidget(playernameLabel, 2, 0);
    grid->addWidget(playernameEdit, 2, 1);
    grid->addWidget(passwordLabel, 3, 0);
    grid->addWidget(passwordEdit, 3, 1);
    grid->addWidget(passwordConfirmationLabel, 4, 0);
    grid->addWidget(passwordConfirmationEdit, 4, 1);
    grid->addWidget(emailLabel, 5, 0);
    grid->addWidget(emailEdit, 5, 1);
    grid->addWidget(emailConfirmationLabel, 6, 0);
    grid->addWidget(emailConfirmationEdit, 6, 1);
    grid->addWidget(genderLabel, 7, 0);
    grid->addWidget(genderEdit, 7, 1);
    grid->addWidget(countryLabel, 8, 0);
    grid->addWidget(countryEdit, 8, 1);
    grid->addWidget(realnameLabel, 9, 0);
    grid->addWidget(realnameEdit, 9, 1);
    
    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk()));
    connect(buttonBox, SIGNAL(rejected()), this, SLOT(actCancel()));
         
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addLayout(grid);
    mainLayout->addWidget(buttonBox);
    setLayout(mainLayout);

    setWindowTitle(tr("Register to server"));
    setFixedHeight(sizeHint().height());
    setMinimumWidth(300);
}
void QgsManageConnectionsDialog::loadOWSConnections( const QDomDocument &doc, const QStringList &items, const QString &service )
{
  QDomElement root = doc.documentElement();
  if ( root.tagName() != "qgs" + service.toUpper() + "Connections" )
  {
    QMessageBox::information( this, tr( "Loading connections" ),
                              tr( "The file is not an %1 connections exchange file." ).arg( service ) );
    return;
  }

  QString connectionName;
  QSettings settings;
  settings.beginGroup( "/Qgis/connections-" + service.toLower() );
  QStringList keys = settings.childGroups();
  settings.endGroup();
  QDomElement child = root.firstChildElement();
  bool prompt = true;
  bool overwrite = true;

  while ( !child.isNull() )
  {
    connectionName = child.attribute( QStringLiteral( "name" ) );
    if ( !items.contains( connectionName ) )
    {
      child = child.nextSiblingElement();
      continue;
    }

    // check for duplicates
    if ( keys.contains( connectionName ) && prompt )
    {
      int res = QMessageBox::warning( this,
                                      tr( "Loading connections" ),
                                      tr( "Connection with name '%1' already exists. Overwrite?" )
                                      .arg( connectionName ),
                                      QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No | QMessageBox::NoToAll | QMessageBox::Cancel );

      switch ( res )
      {
        case QMessageBox::Cancel:
          return;
        case QMessageBox::No:
          child = child.nextSiblingElement();
          continue;
        case QMessageBox::Yes:
          overwrite = true;
          break;
        case QMessageBox::YesToAll:
          prompt = false;
          overwrite = true;
          break;
        case QMessageBox::NoToAll:
          prompt = false;
          overwrite = false;
          break;
      }
    }

    if ( keys.contains( connectionName ) && !overwrite )
    {
      child = child.nextSiblingElement();
      continue;
    }

    // no dups detected or overwrite is allowed
    settings.beginGroup( "/Qgis/connections-" + service.toLower() );
    settings.setValue( QString( '/' + connectionName + "/url" ), child.attribute( QStringLiteral( "url" ) ) );
    settings.setValue( QString( '/' + connectionName + "/ignoreGetMapURI" ), child.attribute( QStringLiteral( "ignoreGetMapURI" ) ) == QLatin1String( "true" ) );
    settings.setValue( QString( '/' + connectionName + "/ignoreGetFeatureInfoURI" ), child.attribute( QStringLiteral( "ignoreGetFeatureInfoURI" ) ) == QLatin1String( "true" ) );
    settings.setValue( QString( '/' + connectionName + "/ignoreAxisOrientation" ), child.attribute( QStringLiteral( "ignoreAxisOrientation" ) ) == QLatin1String( "true" ) );
    settings.setValue( QString( '/' + connectionName + "/invertAxisOrientation" ), child.attribute( QStringLiteral( "invertAxisOrientation" ) ) == QLatin1String( "true" ) );
    settings.setValue( QString( '/' + connectionName + "/referer" ), child.attribute( QStringLiteral( "referer" ) ) );
    settings.setValue( QString( '/' + connectionName + "/smoothPixmapTransform" ), child.attribute( QStringLiteral( "smoothPixmapTransform" ) ) == QLatin1String( "true" ) );
    settings.setValue( QString( '/' + connectionName + "/dpiMode" ), child.attribute( QStringLiteral( "dpiMode" ), QStringLiteral( "7" ) ).toInt() );
    settings.endGroup();

    if ( !child.attribute( QStringLiteral( "username" ) ).isEmpty() )
    {
      settings.beginGroup( "/Qgis/" + service.toUpper() + '/' + connectionName );
      settings.setValue( QStringLiteral( "/username" ), child.attribute( QStringLiteral( "username" ) ) );
      settings.setValue( QStringLiteral( "/password" ), child.attribute( QStringLiteral( "password" ) ) );
      settings.endGroup();
    }
    child = child.nextSiblingElement();
  }
}
Example #16
0
		void LogManager::welcome()
		{
				static_logger()->info("Initialising Log4Qt %1",
															QLatin1String(LOG4QT_VERSION_STR));

				// Debug: Info
				if (static_logger()->isDebugEnabled())
				{
						// Create a nice timestamp with UTC offset
						DateTime start_time = DateTime::fromMilliSeconds(InitialisationHelper::startTime());
						QString offset;
						{
								QDateTime utc = start_time.toUTC();
								QDateTime local = start_time.toLocalTime();
								QDateTime local_as_utc = QDateTime(local.date(), local.time(), Qt::UTC);
								int min = utc.secsTo(local_as_utc) / 60;
								if (min < 0)
										offset += QLatin1Char('-');
								else
										offset += QLatin1Char('+');
								min = abs(min);
								offset += QString::number(min / 60).rightJustified(2, QLatin1Char('0'));
								offset += QLatin1Char(':');
								offset += QString::number(min % 60).rightJustified(2, QLatin1Char('0'));
						}
						static_logger()->debug("Program startup time is %1 (UTC%2)",
																	 start_time.toString(QLatin1String("ISO8601")),
																	 offset);
						static_logger()->debug("Internal logging uses the level %1",
																	 logLogger()->level().toString());
				}

				// Trace: Dump settings
				if (static_logger()->isTraceEnabled())
				{
						static_logger()->trace("Settings from the system environment:");
						QString entry;
						Q_FOREACH (entry, InitialisationHelper::environmentSettings().keys())
								static_logger()->trace("    %1: '%2'",
																			 entry,
																			 InitialisationHelper::environmentSettings().value(entry));

						static_logger()->trace("Settings from the application settings:");
						if (QCoreApplication::instance())
						{
								const QLatin1String log4qt_group("Log4Qt");
								const QLatin1String properties_group("Properties");
								static_logger()->trace("    %1:", log4qt_group);
								QSettings s;
								s.beginGroup(log4qt_group);
								Q_FOREACH (entry, s.childKeys())
										static_logger()->trace("        %1: '%2'",
																					 entry,
																					 s.value(entry).toString());
								static_logger()->trace("    %1/%2:", log4qt_group, properties_group);
								s.beginGroup(properties_group);
										Q_FOREACH (entry, s.childKeys())
												static_logger()->trace("        %1: '%2'",
																							 entry,
																							 s.value(entry).toString());
						} else
								static_logger()->trace("    QCoreApplication::instance() is not available");
				}
		}
void QgsManageConnectionsDialog::loadWfsConnections( const QDomDocument &doc, const QStringList &items )
{
  QDomElement root = doc.documentElement();
  if ( root.tagName() != QLatin1String( "qgsWFSConnections" ) )
  {
    QMessageBox::information( this, tr( "Loading connections" ),
                              tr( "The file is not an WFS connections exchange file." ) );
    return;
  }

  QString connectionName;
  QSettings settings;
  settings.beginGroup( QStringLiteral( "/Qgis/connections-wfs" ) );
  QStringList keys = settings.childGroups();
  settings.endGroup();
  QDomElement child = root.firstChildElement();
  bool prompt = true;
  bool overwrite = true;

  while ( !child.isNull() )
  {
    connectionName = child.attribute( QStringLiteral( "name" ) );
    if ( !items.contains( connectionName ) )
    {
      child = child.nextSiblingElement();
      continue;
    }

    // check for duplicates
    if ( keys.contains( connectionName ) && prompt )
    {
      int res = QMessageBox::warning( this,
                                      tr( "Loading connections" ),
                                      tr( "Connection with name '%1' already exists. Overwrite?" )
                                      .arg( connectionName ),
                                      QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No | QMessageBox::NoToAll | QMessageBox::Cancel );

      switch ( res )
      {
        case QMessageBox::Cancel:
          return;
        case QMessageBox::No:
          child = child.nextSiblingElement();
          continue;
        case QMessageBox::Yes:
          overwrite = true;
          break;
        case QMessageBox::YesToAll:
          prompt = false;
          overwrite = true;
          break;
        case QMessageBox::NoToAll:
          prompt = false;
          overwrite = false;
          break;
      }
    }

    if ( keys.contains( connectionName ) && !overwrite )
    {
      child = child.nextSiblingElement();
      continue;
    }

    // no dups detected or overwrite is allowed
    settings.beginGroup( QStringLiteral( "/Qgis/connections-wfs" ) );
    settings.setValue( QString( '/' + connectionName + "/url" ), child.attribute( QStringLiteral( "url" ) ) );
    settings.endGroup();

    if ( !child.attribute( QStringLiteral( "username" ) ).isEmpty() )
    {
      settings.beginGroup( "/Qgis/WFS/" + connectionName );
      settings.setValue( QStringLiteral( "/username" ), child.attribute( QStringLiteral( "username" ) ) );
      settings.setValue( QStringLiteral( "/password" ), child.attribute( QStringLiteral( "password" ) ) );
      settings.endGroup();
    }
    child = child.nextSiblingElement();
  }
}
Example #18
0
void
EventFilterDialog::initDialog()
{
    setModal(true);
    setWindowTitle(tr("Event Filter"));
    QGridLayout *metagrid = new QGridLayout;
    setLayout(metagrid);
    QWidget *mainWidget = new QWidget(this);
    QVBoxLayout *mainWidgetLayout = new QVBoxLayout;
    metagrid->addWidget(mainWidget, 0, 0);

    //----------[ Note Filter Widgets ]-------------------------

    // Frame
    QGroupBox* noteFrame = new QGroupBox(tr("Note Events"));
    noteFrame->setContentsMargins(20, 20, 20, 20);
    QGridLayout* noteFrameLayout = new QGridLayout;
    noteFrameLayout->setSpacing(6);
    mainWidgetLayout->addWidget(noteFrame);

    // Labels
    QLabel* pitchFromLabel = new QLabel(tr("lowest:"), noteFrame);
    noteFrameLayout->addWidget(pitchFromLabel, 0, 2);

    QLabel* pitchToLabel = new QLabel(tr("highest:"), noteFrame);
    noteFrameLayout->addWidget(pitchToLabel, 0, 4);

    QLabel* pitchLabel = new QLabel(tr("Pitch:"), noteFrame);
    noteFrameLayout->addWidget(pitchLabel, 1, 1);

    QLabel* velocityLabel = new QLabel(tr("Velocity:"), noteFrame);
    noteFrameLayout->addWidget(velocityLabel, 2, 1);

    QLabel* durationLabel = new QLabel(tr("Duration:"), noteFrame);
    noteFrameLayout->addWidget(durationLabel, 3, 1);

    m_useNotationDuration = new QCheckBox();
    noteFrameLayout->addWidget(m_useNotationDuration, 4, 1);

    m_selectRests = new QCheckBox();
    noteFrameLayout->addWidget(m_selectRests, 5, 1);

    // Include Boxes
    m_notePitchIncludeComboBox = new QComboBox(noteFrame);
    m_notePitchIncludeComboBox->setEditable(false);
    m_notePitchIncludeComboBox->addItem(tr("include"));
    m_notePitchIncludeComboBox->addItem(tr("exclude"));

    QSettings settings;
    settings.beginGroup( EventFilterDialogConfigGroup );

    m_notePitchIncludeComboBox->setCurrentIndex( qStrToBool( settings.value("pitchinclude", "0" ) ) );
    noteFrameLayout->addWidget(m_notePitchIncludeComboBox, 1, 0);

    m_noteVelocityIncludeComboBox = new QComboBox(noteFrame);
    m_noteVelocityIncludeComboBox->setEditable(false);
    m_noteVelocityIncludeComboBox->addItem(tr("include"));
    m_noteVelocityIncludeComboBox->addItem(tr("exclude"));

    m_noteVelocityIncludeComboBox->setCurrentIndex( qStrToBool( settings.value("velocityinclude", "0" ) ) );
    noteFrameLayout->addWidget(m_noteVelocityIncludeComboBox, 2, 0);

    m_noteDurationIncludeComboBox = new QComboBox(noteFrame);
    m_noteDurationIncludeComboBox->setEditable(false);
    m_noteDurationIncludeComboBox->addItem(tr("include"));
    m_noteDurationIncludeComboBox->addItem(tr("exclude"));

    m_noteDurationIncludeComboBox->setCurrentIndex( qStrToBool( settings.value("durationinclude", "0" ) ) );
    noteFrameLayout->addWidget(m_noteDurationIncludeComboBox, 3, 0);

    QLabel* durationCheckBoxLabel = new QLabel(tr("Use notation duration"));
    noteFrameLayout->addWidget(durationCheckBoxLabel, 4, 2);
    m_useNotationDuration->setChecked(settings.value("usenotationduration", "0").toBool());

    QLabel* useRestsLabel = new QLabel(tr("Select rests"));
    noteFrameLayout->addWidget(useRestsLabel, 5, 2);
    m_selectRests->setChecked(settings.value("selectrests", "0").toBool());

    // Pitch From
    m_pitchFromSpinBox = new QSpinBox(noteFrame);
    m_pitchFromSpinBox->setMaximum(127);

    m_pitchFromSpinBox->setValue( settings.value("pitchfrom", 0).toUInt() );
    noteFrameLayout->addWidget(m_pitchFromSpinBox, 1, 2);
    connect(m_pitchFromSpinBox, SIGNAL(valueChanged(int)),
            SLOT(slotPitchFromChanged(int)));

    m_pitchFromChooserButton = new QPushButton(tr("edit"), noteFrame);
    m_pitchFromChooserButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,
                                                        QSizePolicy::Fixed,
                                                        QSizePolicy::PushButton));
    m_pitchFromChooserButton->setToolTip(tr("choose a pitch using a staff"));
    noteFrameLayout->addWidget(m_pitchFromChooserButton, 1, 3);
    connect(m_pitchFromChooserButton, SIGNAL(clicked()),
            SLOT(slotPitchFromChooser()));

    // Pitch To
    m_pitchToSpinBox = new QSpinBox(noteFrame);
    m_pitchToSpinBox->setMaximum(127);

    m_pitchToSpinBox->setValue( settings.value("pitchto", 127).toUInt() );
    noteFrameLayout->addWidget(m_pitchToSpinBox, 1, 4);
    connect(m_pitchToSpinBox, SIGNAL(valueChanged(int)),
            SLOT(slotPitchToChanged(int)));

    m_pitchToChooserButton = new QPushButton(tr("edit"), noteFrame);
    m_pitchToChooserButton->setToolTip(tr("choose a pitch using a staff"));
    noteFrameLayout->addWidget(m_pitchToChooserButton, 1, 5);
    connect(m_pitchToChooserButton, SIGNAL(clicked()),
            SLOT(slotPitchToChooser()));

    // Velocity From/To
    m_velocityFromSpinBox = new QSpinBox(noteFrame);
    m_velocityFromSpinBox->setMaximum(127);

    m_velocityFromSpinBox->setValue( settings.value("velocityfrom", 0).toUInt() );
    noteFrameLayout->addWidget(m_velocityFromSpinBox, 2, 2);
    connect(m_velocityFromSpinBox, SIGNAL(valueChanged(int)),
            SLOT(slotVelocityFromChanged(int)));

    m_velocityToSpinBox = new QSpinBox(noteFrame);
    m_velocityToSpinBox->setMaximum(127);

    m_velocityToSpinBox->setValue( settings.value("velocityto", 127).toUInt() );
    noteFrameLayout->addWidget( m_velocityToSpinBox, 2, 4 );
    connect(m_velocityToSpinBox, SIGNAL(valueChanged(int)),
            SLOT(slotVelocityToChanged(int)));


    // Duration From/To
    m_noteDurationFromComboBox = new QComboBox(noteFrame);
    m_noteDurationFromComboBox->setEditable(false);
    m_noteDurationFromComboBox->addItem(tr("longest"));
    noteFrameLayout->addWidget(m_noteDurationFromComboBox, 3, 2);
    connect(m_noteDurationFromComboBox, SIGNAL(activated(int)),
            SLOT(slotDurationFromChanged(int)));

    m_noteDurationToComboBox = new QComboBox(noteFrame);
    m_noteDurationToComboBox->setEditable(false);
    m_noteDurationToComboBox->addItem(tr("longest"));
    noteFrameLayout->addWidget(m_noteDurationToComboBox, 3, 4);
    connect(m_noteDurationToComboBox, SIGNAL(activated(int)),
            SLOT(slotDurationToChanged(int)));

    populateDurationCombos();


    //---------[ Buttons ]--------------------------------------
    QFrame* privateLayoutWidget = new QFrame(mainWidget);
    privateLayoutWidget->setContentsMargins(20, 20, 20, 20);
    QGridLayout* buttonLayout = new QGridLayout;
    buttonLayout->setSpacing(6);
    mainWidgetLayout->addWidget(privateLayoutWidget);

    m_buttonAll = new QPushButton(tr("Include all"), privateLayoutWidget);
    m_buttonAll->setAutoDefault(true);
    m_buttonAll->setToolTip(tr("Include entire range of values"));
    buttonLayout->addWidget( m_buttonAll, 0, 0 );

    m_buttonNone = new QPushButton(tr("Exclude all"), privateLayoutWidget);
    m_buttonNone->setAutoDefault(true);
    m_buttonNone->setToolTip(tr("Exclude entire range of values"));
    buttonLayout->addWidget( m_buttonNone, 0, 1 );

    connect(m_buttonAll, SIGNAL(clicked()), this, SLOT(slotToggleAll()));
    connect(m_buttonNone, SIGNAL(clicked()), this, SLOT(slotToggleNone()));

    settings.endGroup();

    privateLayoutWidget->setLayout(buttonLayout);
    noteFrame->setLayout(noteFrameLayout);
    mainWidget->setLayout(mainWidgetLayout);

    QDialogButtonBox *buttonBox
        = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    metagrid->addWidget(buttonBox, 1, 0);
    metagrid->setRowStretch(0, 10);
    connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
    connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
}
Example #19
0
DlgRegister::DlgRegister(QWidget *parent)
    : QDialog(parent)
{
    QSettings settings;
    settings.beginGroup("server");

    hostLabel = new QLabel(tr("&Host:"));
    hostEdit = new QLineEdit(settings.value("hostname", "cockatrice.woogerworks.com").toString());
    hostLabel->setBuddy(hostEdit);

    portLabel = new QLabel(tr("&Port:"));
    portEdit = new QLineEdit(settings.value("port", "4747").toString());
    portLabel->setBuddy(portEdit);

    playernameLabel = new QLabel(tr("Player &name:"));
    playernameEdit = new QLineEdit(settings.value("playername", "Player").toString());
    playernameLabel->setBuddy(playernameEdit);

    passwordLabel = new QLabel(tr("P&assword:"));
    passwordEdit = new QLineEdit(settings.value("password").toString());
    passwordLabel->setBuddy(passwordEdit);
    passwordEdit->setEchoMode(QLineEdit::Password);

    emailLabel = new QLabel(tr("Email:"));
    emailEdit = new QLineEdit();
    emailLabel->setBuddy(emailEdit);

    genderLabel = new QLabel(tr("Gender:"));
    genderEdit = new QComboBox();
    genderLabel->setBuddy(genderEdit);
    genderEdit->insertItem(0, QIcon(":/resources/genders/unknown.svg"), tr("Undefined"));
    genderEdit->insertItem(1, QIcon(":/resources/genders/male.svg"), tr("Male"));
    genderEdit->insertItem(2, QIcon(":/resources/genders/female.svg"), tr("Female"));
    genderEdit->setCurrentIndex(0);

    countryLabel = new QLabel(tr("Country:"));
    countryEdit = new QComboBox();
    countryLabel->setBuddy(countryEdit);
    countryEdit->insertItem(0, tr("Undefined"));
    countryEdit->addItem(QPixmap(":/resources/countries/ad.svg"), "ad");
    countryEdit->addItem(QIcon(":/resources/countries/ae.svg"), "ae");
    countryEdit->addItem(QIcon(":/resources/countries/af.svg"), "af");
    countryEdit->addItem(QIcon(":/resources/countries/ag.svg"), "ag");
    countryEdit->addItem(QIcon(":/resources/countries/ai.svg"), "ai");
    countryEdit->addItem(QIcon(":/resources/countries/al.svg"), "al");
    countryEdit->addItem(QIcon(":/resources/countries/am.svg"), "am");
    countryEdit->addItem(QIcon(":/resources/countries/ao.svg"), "ao");
    countryEdit->addItem(QIcon(":/resources/countries/aq.svg"), "aq");
    countryEdit->addItem(QIcon(":/resources/countries/ar.svg"), "ar");
    countryEdit->addItem(QIcon(":/resources/countries/as.svg"), "as");
    countryEdit->addItem(QIcon(":/resources/countries/at.svg"), "at");
    countryEdit->addItem(QIcon(":/resources/countries/au.svg"), "au");
    countryEdit->addItem(QIcon(":/resources/countries/aw.svg"), "aw");
    countryEdit->addItem(QIcon(":/resources/countries/ax.svg"), "ax");
    countryEdit->addItem(QIcon(":/resources/countries/az.svg"), "az");
    countryEdit->addItem(QIcon(":/resources/countries/ba.svg"), "ba");
    countryEdit->addItem(QIcon(":/resources/countries/bb.svg"), "bb");
    countryEdit->addItem(QIcon(":/resources/countries/bd.svg"), "bd");
    countryEdit->addItem(QIcon(":/resources/countries/be.svg"), "be");
    countryEdit->addItem(QIcon(":/resources/countries/bf.svg"), "bf");
    countryEdit->addItem(QIcon(":/resources/countries/bg.svg"), "bg");
    countryEdit->addItem(QIcon(":/resources/countries/bh.svg"), "bh");
    countryEdit->addItem(QIcon(":/resources/countries/bi.svg"), "bi");
    countryEdit->addItem(QIcon(":/resources/countries/bj.svg"), "bj");
    countryEdit->addItem(QIcon(":/resources/countries/bl.svg"), "bl");
    countryEdit->addItem(QIcon(":/resources/countries/bm.svg"), "bm");
    countryEdit->addItem(QIcon(":/resources/countries/bn.svg"), "bn");
    countryEdit->addItem(QIcon(":/resources/countries/bo.svg"), "bo");
    countryEdit->addItem(QIcon(":/resources/countries/bq.svg"), "bq");
    countryEdit->addItem(QIcon(":/resources/countries/br.svg"), "br");
    countryEdit->addItem(QIcon(":/resources/countries/bs.svg"), "bs");
    countryEdit->addItem(QIcon(":/resources/countries/bt.svg"), "bt");
    countryEdit->addItem(QIcon(":/resources/countries/bv.svg"), "bv");
    countryEdit->addItem(QIcon(":/resources/countries/bw.svg"), "bw");
    countryEdit->addItem(QIcon(":/resources/countries/by.svg"), "by");
    countryEdit->addItem(QIcon(":/resources/countries/bz.svg"), "bz");
    countryEdit->addItem(QIcon(":/resources/countries/ca.svg"), "ca");
    countryEdit->addItem(QIcon(":/resources/countries/cc.svg"), "cc");
    countryEdit->addItem(QIcon(":/resources/countries/cd.svg"), "cd");
    countryEdit->addItem(QIcon(":/resources/countries/cf.svg"), "cf");
    countryEdit->addItem(QIcon(":/resources/countries/cg.svg"), "cg");
    countryEdit->addItem(QIcon(":/resources/countries/ch.svg"), "ch");
    countryEdit->addItem(QIcon(":/resources/countries/ci.svg"), "ci");
    countryEdit->addItem(QIcon(":/resources/countries/ck.svg"), "ck");
    countryEdit->addItem(QIcon(":/resources/countries/cl.svg"), "cl");
    countryEdit->addItem(QIcon(":/resources/countries/cm.svg"), "cm");
    countryEdit->addItem(QIcon(":/resources/countries/cn.svg"), "cn");
    countryEdit->addItem(QIcon(":/resources/countries/co.svg"), "co");
    countryEdit->addItem(QIcon(":/resources/countries/cr.svg"), "cr");
    countryEdit->addItem(QIcon(":/resources/countries/cu.svg"), "cu");
    countryEdit->addItem(QIcon(":/resources/countries/cv.svg"), "cv");
    countryEdit->addItem(QIcon(":/resources/countries/cw.svg"), "cw");
    countryEdit->addItem(QIcon(":/resources/countries/cx.svg"), "cx");
    countryEdit->addItem(QIcon(":/resources/countries/cy.svg"), "cy");
    countryEdit->addItem(QIcon(":/resources/countries/cz.svg"), "cz");
    countryEdit->addItem(QIcon(":/resources/countries/de.svg"), "de");
    countryEdit->addItem(QIcon(":/resources/countries/dj.svg"), "dj");
    countryEdit->addItem(QIcon(":/resources/countries/dk.svg"), "dk");
    countryEdit->addItem(QIcon(":/resources/countries/dm.svg"), "dm");
    countryEdit->addItem(QIcon(":/resources/countries/do.svg"), "do");
    countryEdit->addItem(QIcon(":/resources/countries/dz.svg"), "dz");
    countryEdit->addItem(QIcon(":/resources/countries/ec.svg"), "ec");
    countryEdit->addItem(QIcon(":/resources/countries/ee.svg"), "ee");
    countryEdit->addItem(QIcon(":/resources/countries/eg.svg"), "eg");
    countryEdit->addItem(QIcon(":/resources/countries/eh.svg"), "eh");
    countryEdit->addItem(QIcon(":/resources/countries/er.svg"), "er");
    countryEdit->addItem(QIcon(":/resources/countries/es.svg"), "es");
    countryEdit->addItem(QIcon(":/resources/countries/et.svg"), "et");
    countryEdit->addItem(QIcon(":/resources/countries/fi.svg"), "fi");
    countryEdit->addItem(QIcon(":/resources/countries/fj.svg"), "fj");
    countryEdit->addItem(QIcon(":/resources/countries/fk.svg"), "fk");
    countryEdit->addItem(QIcon(":/resources/countries/fm.svg"), "fm");
    countryEdit->addItem(QIcon(":/resources/countries/fo.svg"), "fo");
    countryEdit->addItem(QIcon(":/resources/countries/fr.svg"), "fr");
    countryEdit->addItem(QIcon(":/resources/countries/ga.svg"), "ga");
    countryEdit->addItem(QIcon(":/resources/countries/gb.svg"), "gb");
    countryEdit->addItem(QIcon(":/resources/countries/gd.svg"), "gd");
    countryEdit->addItem(QIcon(":/resources/countries/ge.svg"), "ge");
    countryEdit->addItem(QIcon(":/resources/countries/gf.svg"), "gf");
    countryEdit->addItem(QIcon(":/resources/countries/gg.svg"), "gg");
    countryEdit->addItem(QIcon(":/resources/countries/gh.svg"), "gh");
    countryEdit->addItem(QIcon(":/resources/countries/gi.svg"), "gi");
    countryEdit->addItem(QIcon(":/resources/countries/gl.svg"), "gl");
    countryEdit->addItem(QIcon(":/resources/countries/gm.svg"), "gm");
    countryEdit->addItem(QIcon(":/resources/countries/gn.svg"), "gn");
    countryEdit->addItem(QIcon(":/resources/countries/gp.svg"), "gp");
    countryEdit->addItem(QIcon(":/resources/countries/gq.svg"), "gq");
    countryEdit->addItem(QIcon(":/resources/countries/gr.svg"), "gr");
    countryEdit->addItem(QIcon(":/resources/countries/gs.svg"), "gs");
    countryEdit->addItem(QIcon(":/resources/countries/gt.svg"), "gt");
    countryEdit->addItem(QIcon(":/resources/countries/gu.svg"), "gu");
    countryEdit->addItem(QIcon(":/resources/countries/gw.svg"), "gw");
    countryEdit->addItem(QIcon(":/resources/countries/gy.svg"), "gy");
    countryEdit->addItem(QIcon(":/resources/countries/hk.svg"), "hk");
    countryEdit->addItem(QIcon(":/resources/countries/hm.svg"), "hm");
    countryEdit->addItem(QIcon(":/resources/countries/hn.svg"), "hn");
    countryEdit->addItem(QIcon(":/resources/countries/hr.svg"), "hr");
    countryEdit->addItem(QIcon(":/resources/countries/ht.svg"), "ht");
    countryEdit->addItem(QIcon(":/resources/countries/hu.svg"), "hu");
    countryEdit->addItem(QIcon(":/resources/countries/id.svg"), "id");
    countryEdit->addItem(QIcon(":/resources/countries/ie.svg"), "ie");
    countryEdit->addItem(QIcon(":/resources/countries/il.svg"), "il");
    countryEdit->addItem(QIcon(":/resources/countries/im.svg"), "im");
    countryEdit->addItem(QIcon(":/resources/countries/in.svg"), "in");
    countryEdit->addItem(QIcon(":/resources/countries/io.svg"), "io");
    countryEdit->addItem(QIcon(":/resources/countries/iq.svg"), "iq");
    countryEdit->addItem(QIcon(":/resources/countries/ir.svg"), "ir");
    countryEdit->addItem(QIcon(":/resources/countries/is.svg"), "is");
    countryEdit->addItem(QIcon(":/resources/countries/it.svg"), "it");
    countryEdit->addItem(QIcon(":/resources/countries/je.svg"), "je");
    countryEdit->addItem(QIcon(":/resources/countries/jm.svg"), "jm");
    countryEdit->addItem(QIcon(":/resources/countries/jo.svg"), "jo");
    countryEdit->addItem(QIcon(":/resources/countries/jp.svg"), "jp");
    countryEdit->addItem(QIcon(":/resources/countries/ke.svg"), "ke");
    countryEdit->addItem(QIcon(":/resources/countries/kg.svg"), "kg");
    countryEdit->addItem(QIcon(":/resources/countries/kh.svg"), "kh");
    countryEdit->addItem(QIcon(":/resources/countries/ki.svg"), "ki");
    countryEdit->addItem(QIcon(":/resources/countries/km.svg"), "km");
    countryEdit->addItem(QIcon(":/resources/countries/kn.svg"), "kn");
    countryEdit->addItem(QIcon(":/resources/countries/kp.svg"), "kp");
    countryEdit->addItem(QIcon(":/resources/countries/kr.svg"), "kr");
    countryEdit->addItem(QIcon(":/resources/countries/kw.svg"), "kw");
    countryEdit->addItem(QIcon(":/resources/countries/ky.svg"), "ky");
    countryEdit->addItem(QIcon(":/resources/countries/kz.svg"), "kz");
    countryEdit->addItem(QIcon(":/resources/countries/la.svg"), "la");
    countryEdit->addItem(QIcon(":/resources/countries/lb.svg"), "lb");
    countryEdit->addItem(QIcon(":/resources/countries/lc.svg"), "lc");
    countryEdit->addItem(QIcon(":/resources/countries/li.svg"), "li");
    countryEdit->addItem(QIcon(":/resources/countries/lk.svg"), "lk");
    countryEdit->addItem(QIcon(":/resources/countries/lr.svg"), "lr");
    countryEdit->addItem(QIcon(":/resources/countries/ls.svg"), "ls");
    countryEdit->addItem(QIcon(":/resources/countries/lt.svg"), "lt");
    countryEdit->addItem(QIcon(":/resources/countries/lu.svg"), "lu");
    countryEdit->addItem(QIcon(":/resources/countries/lv.svg"), "lv");
    countryEdit->addItem(QIcon(":/resources/countries/ly.svg"), "ly");
    countryEdit->addItem(QIcon(":/resources/countries/ma.svg"), "ma");
    countryEdit->addItem(QIcon(":/resources/countries/mc.svg"), "mc");
    countryEdit->addItem(QIcon(":/resources/countries/md.svg"), "md");
    countryEdit->addItem(QIcon(":/resources/countries/me.svg"), "me");
    countryEdit->addItem(QIcon(":/resources/countries/mf.svg"), "mf");
    countryEdit->addItem(QIcon(":/resources/countries/mg.svg"), "mg");
    countryEdit->addItem(QIcon(":/resources/countries/mh.svg"), "mh");
    countryEdit->addItem(QIcon(":/resources/countries/mk.svg"), "mk");
    countryEdit->addItem(QIcon(":/resources/countries/ml.svg"), "ml");
    countryEdit->addItem(QIcon(":/resources/countries/mm.svg"), "mm");
    countryEdit->addItem(QIcon(":/resources/countries/mn.svg"), "mn");
    countryEdit->addItem(QIcon(":/resources/countries/mo.svg"), "mo");
    countryEdit->addItem(QIcon(":/resources/countries/mp.svg"), "mp");
    countryEdit->addItem(QIcon(":/resources/countries/mq.svg"), "mq");
    countryEdit->addItem(QIcon(":/resources/countries/mr.svg"), "mr");
    countryEdit->addItem(QIcon(":/resources/countries/ms.svg"), "ms");
    countryEdit->addItem(QIcon(":/resources/countries/mt.svg"), "mt");
    countryEdit->addItem(QIcon(":/resources/countries/mu.svg"), "mu");
    countryEdit->addItem(QIcon(":/resources/countries/mv.svg"), "mv");
    countryEdit->addItem(QIcon(":/resources/countries/mw.svg"), "mw");
    countryEdit->addItem(QIcon(":/resources/countries/mx.svg"), "mx");
    countryEdit->addItem(QIcon(":/resources/countries/my.svg"), "my");
    countryEdit->addItem(QIcon(":/resources/countries/mz.svg"), "mz");
    countryEdit->addItem(QIcon(":/resources/countries/na.svg"), "na");
    countryEdit->addItem(QIcon(":/resources/countries/nc.svg"), "nc");
    countryEdit->addItem(QIcon(":/resources/countries/ne.svg"), "ne");
    countryEdit->addItem(QIcon(":/resources/countries/nf.svg"), "nf");
    countryEdit->addItem(QIcon(":/resources/countries/ng.svg"), "ng");
    countryEdit->addItem(QIcon(":/resources/countries/ni.svg"), "ni");
    countryEdit->addItem(QIcon(":/resources/countries/nl.svg"), "nl");
    countryEdit->addItem(QIcon(":/resources/countries/no.svg"), "no");
    countryEdit->addItem(QIcon(":/resources/countries/np.svg"), "np");
    countryEdit->addItem(QIcon(":/resources/countries/nr.svg"), "nr");
    countryEdit->addItem(QIcon(":/resources/countries/nu.svg"), "nu");
    countryEdit->addItem(QIcon(":/resources/countries/nz.svg"), "nz");
    countryEdit->addItem(QIcon(":/resources/countries/om.svg"), "om");
    countryEdit->addItem(QIcon(":/resources/countries/pa.svg"), "pa");
    countryEdit->addItem(QIcon(":/resources/countries/pe.svg"), "pe");
    countryEdit->addItem(QIcon(":/resources/countries/pf.svg"), "pf");
    countryEdit->addItem(QIcon(":/resources/countries/pg.svg"), "pg");
    countryEdit->addItem(QIcon(":/resources/countries/ph.svg"), "ph");
    countryEdit->addItem(QIcon(":/resources/countries/pk.svg"), "pk");
    countryEdit->addItem(QIcon(":/resources/countries/pl.svg"), "pl");
    countryEdit->addItem(QIcon(":/resources/countries/pm.svg"), "pm");
    countryEdit->addItem(QIcon(":/resources/countries/pn.svg"), "pn");
    countryEdit->addItem(QIcon(":/resources/countries/pr.svg"), "pr");
    countryEdit->addItem(QIcon(":/resources/countries/ps.svg"), "ps");
    countryEdit->addItem(QIcon(":/resources/countries/pt.svg"), "pt");
    countryEdit->addItem(QIcon(":/resources/countries/pw.svg"), "pw");
    countryEdit->addItem(QIcon(":/resources/countries/py.svg"), "py");
    countryEdit->addItem(QIcon(":/resources/countries/qa.svg"), "qa");
    countryEdit->addItem(QIcon(":/resources/countries/re.svg"), "re");
    countryEdit->addItem(QIcon(":/resources/countries/ro.svg"), "ro");
    countryEdit->addItem(QIcon(":/resources/countries/rs.svg"), "rs");
    countryEdit->addItem(QIcon(":/resources/countries/ru.svg"), "ru");
    countryEdit->addItem(QIcon(":/resources/countries/rw.svg"), "rw");
    countryEdit->addItem(QIcon(":/resources/countries/sa.svg"), "sa");
    countryEdit->addItem(QIcon(":/resources/countries/sb.svg"), "sb");
    countryEdit->addItem(QIcon(":/resources/countries/sc.svg"), "sc");
    countryEdit->addItem(QIcon(":/resources/countries/sd.svg"), "sd");
    countryEdit->addItem(QIcon(":/resources/countries/se.svg"), "se");
    countryEdit->addItem(QIcon(":/resources/countries/sg.svg"), "sg");
    countryEdit->addItem(QIcon(":/resources/countries/sh.svg"), "sh");
    countryEdit->addItem(QIcon(":/resources/countries/si.svg"), "si");
    countryEdit->addItem(QIcon(":/resources/countries/sj.svg"), "sj");
    countryEdit->addItem(QIcon(":/resources/countries/sk.svg"), "sk");
    countryEdit->addItem(QIcon(":/resources/countries/sl.svg"), "sl");
    countryEdit->addItem(QIcon(":/resources/countries/sm.svg"), "sm");
    countryEdit->addItem(QIcon(":/resources/countries/sn.svg"), "sn");
    countryEdit->addItem(QIcon(":/resources/countries/so.svg"), "so");
    countryEdit->addItem(QIcon(":/resources/countries/sr.svg"), "sr");
    countryEdit->addItem(QIcon(":/resources/countries/ss.svg"), "ss");
    countryEdit->addItem(QIcon(":/resources/countries/st.svg"), "st");
    countryEdit->addItem(QIcon(":/resources/countries/sv.svg"), "sv");
    countryEdit->addItem(QIcon(":/resources/countries/sx.svg"), "sx");
    countryEdit->addItem(QIcon(":/resources/countries/sy.svg"), "sy");
    countryEdit->addItem(QIcon(":/resources/countries/sz.svg"), "sz");
    countryEdit->addItem(QIcon(":/resources/countries/tc.svg"), "tc");
    countryEdit->addItem(QIcon(":/resources/countries/td.svg"), "td");
    countryEdit->addItem(QIcon(":/resources/countries/tf.svg"), "tf");
    countryEdit->addItem(QIcon(":/resources/countries/tg.svg"), "tg");
    countryEdit->addItem(QIcon(":/resources/countries/th.svg"), "th");
    countryEdit->addItem(QIcon(":/resources/countries/tj.svg"), "tj");
    countryEdit->addItem(QIcon(":/resources/countries/tk.svg"), "tk");
    countryEdit->addItem(QIcon(":/resources/countries/tl.svg"), "tl");
    countryEdit->addItem(QIcon(":/resources/countries/tm.svg"), "tm");
    countryEdit->addItem(QIcon(":/resources/countries/tn.svg"), "tn");
    countryEdit->addItem(QIcon(":/resources/countries/to.svg"), "to");
    countryEdit->addItem(QIcon(":/resources/countries/tr.svg"), "tr");
    countryEdit->addItem(QIcon(":/resources/countries/tt.svg"), "tt");
    countryEdit->addItem(QIcon(":/resources/countries/tv.svg"), "tv");
    countryEdit->addItem(QIcon(":/resources/countries/tw.svg"), "tw");
    countryEdit->addItem(QIcon(":/resources/countries/tz.svg"), "tz");
    countryEdit->addItem(QIcon(":/resources/countries/ua.svg"), "ua");
    countryEdit->addItem(QIcon(":/resources/countries/ug.svg"), "ug");
    countryEdit->addItem(QIcon(":/resources/countries/um.svg"), "um");
    countryEdit->addItem(QIcon(":/resources/countries/us.svg"), "us");
    countryEdit->addItem(QIcon(":/resources/countries/uy.svg"), "uy");
    countryEdit->addItem(QIcon(":/resources/countries/uz.svg"), "uz");
    countryEdit->addItem(QIcon(":/resources/countries/va.svg"), "va");
    countryEdit->addItem(QIcon(":/resources/countries/vc.svg"), "vc");
    countryEdit->addItem(QIcon(":/resources/countries/ve.svg"), "ve");
    countryEdit->addItem(QIcon(":/resources/countries/vg.svg"), "vg");
    countryEdit->addItem(QIcon(":/resources/countries/vi.svg"), "vi");
    countryEdit->addItem(QIcon(":/resources/countries/vn.svg"), "vn");
    countryEdit->addItem(QIcon(":/resources/countries/vu.svg"), "vu");
    countryEdit->addItem(QIcon(":/resources/countries/wf.svg"), "wf");
    countryEdit->addItem(QIcon(":/resources/countries/ws.svg"), "ws");
    countryEdit->addItem(QIcon(":/resources/countries/ye.svg"), "ye");
    countryEdit->addItem(QIcon(":/resources/countries/yt.svg"), "yt");
    countryEdit->addItem(QIcon(":/resources/countries/za.svg"), "za");
    countryEdit->addItem(QIcon(":/resources/countries/zm.svg"), "zm");
    countryEdit->addItem(QIcon(":/resources/countries/zw.svg"), "zw");
    countryEdit->setCurrentIndex(0);

    realnameLabel = new QLabel(tr("Real name:"));
    realnameEdit = new QLineEdit();
    realnameLabel->setBuddy(realnameEdit);
    
    QGridLayout *grid = new QGridLayout;
    grid->addWidget(hostLabel, 0, 0);
    grid->addWidget(hostEdit, 0, 1);
    grid->addWidget(portLabel, 1, 0);
    grid->addWidget(portEdit, 1, 1);
    grid->addWidget(playernameLabel, 2, 0);
    grid->addWidget(playernameEdit, 2, 1);
    grid->addWidget(passwordLabel, 3, 0);
    grid->addWidget(passwordEdit, 3, 1);
    grid->addWidget(emailLabel, 4, 0);
    grid->addWidget(emailEdit, 4, 1);
    grid->addWidget(genderLabel, 5, 0);
    grid->addWidget(genderEdit, 5, 1);
    grid->addWidget(countryLabel, 6, 0);
    grid->addWidget(countryEdit, 6, 1);
    grid->addWidget(realnameLabel, 7, 0);
    grid->addWidget(realnameEdit, 7, 1);
    
    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk()));
    connect(buttonBox, SIGNAL(rejected()), this, SLOT(actCancel()));
         
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addLayout(grid);
    mainLayout->addWidget(buttonBox);
    setLayout(mainLayout);

    setWindowTitle(tr("Register to server"));
    setFixedHeight(sizeHint().height());
    setMinimumWidth(300);
}
Example #20
0
SerialConsole::SerialConsole(QWidget *parent) :
    QDockWidget(tr("Serial console"), parent)
{
	setObjectName("SerialConsole");

    extruder_temperature = 0.0;
    bed_temperature = 0.0;
    nb_processed_commands = 0;
    start_time.start();

    QWidget *widget = new QWidget;
    setWidget(widget);
    QVBoxLayout *layout = new QVBoxLayout;
    widget->setLayout(layout);

    QComboBox *serial_ports = new QComboBox;

	const QList<QSerialPortInfo> &available_ports = QSerialPortInfo::availablePorts();
	for(const QSerialPortInfo &port : available_ports)
    {
        serial_ports->addItem(QIcon::fromTheme("printer"), port.portName(), port.portName());
    }
    connect(serial_ports,SIGNAL(activated(QString)),this,SLOT(connectTo(QString)));

    QHBoxLayout *history_layout = new QHBoxLayout;
    scroll_bar = new QScrollBar(Qt::Vertical);
    scroll_bar->setMinimum(0);
    scroll_bar->setValue(0);
    history_layout->addWidget(history = new SimpleTextEdit);
	history->setMaxSize(10000);
    history_layout->addWidget(scroll_bar);
    connect(history,SIGNAL(scrollPositionChanged(int)),scroll_bar,SLOT(setValue(int)));
    connect(scroll_bar,SIGNAL(valueChanged(int)),history,SLOT(setScrollPosition(int)));
    connect(history,SIGNAL(maxScrollChanged(int)),this,SLOT(updateScrollBar(int)));

    layout->addWidget(serial_ports);
    layout->addLayout(history_layout);
    layout->addWidget(cmd = new QLineEdit);

    history->setFocusPolicy(Qt::NoFocus);
    cmd->setFocusPolicy(Qt::StrongFocus);

	rs232 = new QSerialPort(this);
	rs232->setBaudRate(115200);

    connect(rs232,SIGNAL(readyRead()),this,SLOT(readMessage()));
    connect(cmd,SIGNAL(returnPressed()),this,SLOT(sendMessage()));

    ack_timer = new QTimer(this);
    ack_timer->setSingleShot(true);
    ack_timer->setInterval(2000);
    connect(ack_timer,SIGNAL(timeout()),this,SLOT(kickAfterTimeout()));

    QTimer *timer = new QTimer(this);
    timer->setInterval(10000);
    timer->setSingleShot(false);
    connect(timer,SIGNAL(timeout()),this,SLOT(requestTemperature()));
    timer->start();

    ack_expected_before_sending_a_command = 0;
    b_paused = false;

    QSettings settings;
    settings.beginGroup("SerialConsole");
    const QString &serial_port = settings.value("serial_port", QString()).toString();
    settings.endGroup();

    int idx = 0;
	for(const QSerialPortInfo &port : available_ports)
        if (port.portName() == serial_port)
        {
            serial_ports->setCurrentIndex(idx);
            connectTo(serial_port);
            break;
        }
        else
            ++idx;
}
Example #21
0
void SettingsDialog::loadFromSettings()
{
    QSettings settings;
    settings.beginGroup(QLatin1String("MainWindow"));
    QString defaultHome = QLatin1String("about:home");
    homeLineEdit->setText(settings.value(QLatin1String("home"), defaultHome).toString());
    settings.endGroup();

    settings.beginGroup(QLatin1String("history"));
    int historyExpire = settings.value(QLatin1String("historyExpire")).toInt();
    int idx = 0;
    switch (historyExpire) {
    case 1:
        idx = 0;
        break;
    case 7:
        idx = 1;
        break;
    case 14:
        idx = 2;
        break;
    case 30:
        idx = 3;
        break;
    case 365:
        idx = 4;
        break;
    case -1:
        idx = 5;
        break;
    default:
        idx = 5;
    }
    expireHistory->setCurrentIndex(idx);
    settings.endGroup();

    settings.beginGroup(QLatin1String("downloadmanager"));
    QString downloadDirectory = settings.value(QLatin1String("downloadDirectory"), downloadsLocation->text()).toString();
    downloadsLocation->setText(downloadDirectory);
    settings.endGroup();

    settings.beginGroup(QLatin1String("general"));
    openLinksIn->setCurrentIndex(settings.value(QLatin1String("openLinksIn"), openLinksIn->currentIndex()).toInt());

    settings.endGroup();

    // Appearance
    settings.beginGroup(QLatin1String("websettings"));
    fixedFont = qvariant_cast<QFont>(settings.value(QLatin1String("fixedFont"), fixedFont));
    standardFont = qvariant_cast<QFont>(settings.value(QLatin1String("standardFont"), standardFont));

    standardLabel->setText(QString(QLatin1String("%1 %2")).arg(standardFont.family()).arg(standardFont.pointSize()));
    fixedLabel->setText(QString(QLatin1String("%1 %2")).arg(fixedFont.family()).arg(fixedFont.pointSize()));

    enableJavascript->setChecked(settings.value(QLatin1String("enableJavascript"), enableJavascript->isChecked()).toBool());
    enablePlugins->setChecked(settings.value(QLatin1String("enablePlugins"), enablePlugins->isChecked()).toBool());
    userStyleSheet->setText(settings.value(QLatin1String("userStyleSheet")).toUrl().toString());
    settings.endGroup();

    // Privacy
    settings.beginGroup(QLatin1String("cookies"));

    CookieJar *jar = BrowserApplication::cookieJar();
    QByteArray value = settings.value(QLatin1String("acceptCookies"), QLatin1String("AcceptOnlyFromSitesNavigatedTo")).toByteArray();
    QMetaEnum acceptPolicyEnum = jar->staticMetaObject.enumerator(jar->staticMetaObject.indexOfEnumerator("AcceptPolicy"));
    CookieJar::AcceptPolicy acceptCookies = acceptPolicyEnum.keyToValue(value) == -1 ?
                                            CookieJar::AcceptOnlyFromSitesNavigatedTo :
                                            static_cast<CookieJar::AcceptPolicy>(acceptPolicyEnum.keyToValue(value));
    switch(acceptCookies) {
    case CookieJar::AcceptAlways:
        acceptCombo->setCurrentIndex(0);
        break;
    case CookieJar::AcceptNever:
        acceptCombo->setCurrentIndex(1);
        break;
    case CookieJar::AcceptOnlyFromSitesNavigatedTo:
        acceptCombo->setCurrentIndex(2);
        break;
    }

    value = settings.value(QLatin1String("keepCookiesUntil"), QLatin1String("Expire")).toByteArray();
    QMetaEnum keepPolicyEnum = jar->staticMetaObject.enumerator(jar->staticMetaObject.indexOfEnumerator("KeepPolicy"));
    CookieJar::KeepPolicy keepCookies = keepPolicyEnum.keyToValue(value) == -1 ?
                                        CookieJar::KeepUntilExpire :
                                        static_cast<CookieJar::KeepPolicy>(keepPolicyEnum.keyToValue(value));
    switch(keepCookies) {
    case CookieJar::KeepUntilExpire:
        keepUntilCombo->setCurrentIndex(0);
        break;
    case CookieJar::KeepUntilExit:
        keepUntilCombo->setCurrentIndex(1);
        break;
    case CookieJar::KeepUntilTimeLimit:
        keepUntilCombo->setCurrentIndex(2);
        break;
    }
    settings.endGroup();


    // Proxy
    settings.beginGroup(QLatin1String("proxy"));
    proxySupport->setChecked(settings.value(QLatin1String("enabled"), false).toBool());
    proxyType->setCurrentIndex(settings.value(QLatin1String("type"), 0).toInt());
    proxyHostName->setText(settings.value(QLatin1String("hostName")).toString());
    proxyPort->setValue(settings.value(QLatin1String("port"), 1080).toInt());
    proxyUserName->setText(settings.value(QLatin1String("userName")).toString());
    proxyPassword->setText(settings.value(QLatin1String("password")).toString());
    settings.endGroup();
}
Example #22
0
void SerialConsole::connectTo(const QString &portname)
{
    ack_timer->stop();
    last_cmd.clear();
    b_paused = false;
    ack_expected_before_sending_a_command = 0;
    command_queue.clear();

    rs232->close();
    rs232->setPortName(portname);
    if (!rs232->open(QIODevice::ReadWrite))
        history->append("error connecting serial port\n");
    else
    {
        rs232->setDataBits(QSerialPort::Data8);
        rs232->setParity(QSerialPort::NoParity);
        rs232->setStopBits(QSerialPort::OneStop);
        rs232->setFlowControl(QSerialPort::HardwareControl);

        disconnect(rs232,SIGNAL(readyRead()),this,SLOT(readMessage()));

        QList<qint32> baudrates = QSerialPortInfo::standardBaudRates();
        if (!baudrates.contains(250000))
            baudrates.append(250000);
        bool b_valid = false;
        for(int i = baudrates.size() - 1 ; i >= 0 && !b_valid ; --i)
        {
            qDebug() << "trying " << baudrates[i] << " bauds";
            rs232->flush();
            rs232->readAll();
            rs232->setBaudRate(baudrates[i]);
            rs232->write("\nN0 M110*35\n");
            rs232->flush();
            rs232->waitForBytesWritten(10);
            QTime timer;
            timer.start();
            do
            {
                rs232->waitForReadyRead(10);
                while(rs232->canReadLine())
                {
                    QByteArray line = rs232->readLine().trimmed();
                    b_valid |= line == "ok";
                }
            } while (rs232->bytesAvailable() > 0 && timer.elapsed() < 100);
            if (b_valid)
                qDebug() << "working baud rate detected : " << baudrates[i];
        }

        if (b_valid)
            connect(rs232,SIGNAL(readyRead()),this,SLOT(readMessage()));

        history->append("connected on " + portname.toLatin1());
        QSettings settings;
        settings.beginGroup("SerialConsole");
        settings.setValue("serial_port", portname);
        settings.endGroup();

        command_history.clear();
        sendMessage("M110");

        nb_processed_commands = 0;
        emit updateWorkProgress(100);
    }
}
Example #23
0
	QVariant PluginManager::data (const QModelIndex& index, int role) const
	{
		if (!index.isValid () ||
				index.row () >= GetSize ())
			return QVariant ();

		if (role == Roles::PluginObject)
		{
			auto loader = AvailablePlugins_ [index.row ()];
			if (!loader || !loader->isLoaded ())
				return QVariant ();

			return QVariant::fromValue<QObject*> (loader->instance ());
		}
		else if (role == Roles::PluginID)
		{
			auto loader = AvailablePlugins_ [index.row ()];
			if (!loader || !loader->isLoaded ())
				return QVariant ();

			return qobject_cast<IInfo*> (loader->instance ())->GetUniqueID ();
		}
		else if (role == Roles::PluginFilename)
		{
			auto loader = AvailablePlugins_ [index.row ()];
			if (!loader)
				return QVariant ();

			return loader->fileName ();
		}

		switch (index.column ())
		{
			case 0:
				switch (role)
				{
					case Qt::DisplayRole:
						{
							QSettings settings (QCoreApplication::organizationName (),
									QCoreApplication::applicationName () + "-pg");
							settings.beginGroup ("Plugins");
							settings.beginGroup (AvailablePlugins_.at (index.row ())->fileName ());
							QVariant result = settings.value ("Name");
							settings.endGroup ();
							settings.endGroup ();
							return result;
						}
					case Qt::DecorationRole:
						{
							const auto& path = AvailablePlugins_.at (index.row ())->fileName ();
							const auto fName = path.toUtf8 ().toBase64 ().replace ('/', '_');
							const auto& res = QPixmap (QString (IconsDir_.absoluteFilePath (fName)));
							return res.isNull () ? DefaultPluginIcon_ : res;
						}
					case Qt::CheckStateRole:
						{
							QSettings settings (QCoreApplication::organizationName (),
									QCoreApplication::applicationName () + "-pg");
							settings.beginGroup ("Plugins");
							settings.beginGroup (AvailablePlugins_.at (index.row ())->fileName ());
							bool result = settings.value ("AllowLoad", true).toBool ();
							settings.endGroup ();
							settings.endGroup ();
							return result ? Qt::Checked : Qt::Unchecked;
						}
					case Qt::ForegroundRole:
						return QApplication::palette ()
							.brush (AvailablePlugins_.at (index.row ())->isLoaded () ?
									QPalette::Normal :
									QPalette::Disabled,
								QPalette::WindowText);
					default:
						return QVariant ();
				}
			case 1:
				if (role == Qt::DisplayRole)
				{
					QSettings settings (QCoreApplication::organizationName (),
							QCoreApplication::applicationName () + "-pg");
					settings.beginGroup ("Plugins");
					settings.beginGroup (AvailablePlugins_.at (index.row ())->fileName ());
					QVariant result = settings.value ("Info");
					settings.endGroup ();
					settings.endGroup ();
					return result;
				}
				else if (role == Qt::ForegroundRole)
					return QApplication::palette ()
						.brush (AvailablePlugins_.at (index.row ())->isLoaded () ?
								QPalette::Normal :
								QPalette::Disabled,
							QPalette::WindowText);
				else
					return QVariant ();
			case 2:
				if (role == Qt::SizeHintRole)
					return QSize (32, 32);
				else
					return QVariant ();
			default:
				return QVariant ();
		}
	}
Example #24
0
//C-tor
ZBC_MainWindow::ZBC_MainWindow(QWidget* pwgt) : QMainWindow(pwgt)
{
    this->setWindowIcon(QIcon(":/mainwindow/icons/resource/app.ico"));

//Actions
    QAction* pactQuit       = new QAction(QIcon(":/mainwindow/icons/resource/close.ico"), "Quit", this);
    QAction* pactBack       = new QAction(QIcon(":/buttons/toolbar/resource/left32.ico"), tr("Back"), this);
    QAction* pactForward    = new QAction(QIcon(":/buttons/toolbar/resource/right32.ico"), tr("Forward"), this);
    QAction* pactCMD        = new QAction(QIcon(":/buttons/toolbar/resource/cmd.ico"), tr("Run cmd.exe"), this);
    QAction* pactNotepad    = new QAction(QIcon(":/buttons/toolbar/resource/notepad.ico"), tr("Run notepad.exe"), this);
    QAction* pactPaint      = new QAction(QIcon(":/buttons/toolbar/resource/paint.ico"), tr("Run mspaint.exe"), this);
    QAction* pactCalc       = new QAction(QIcon(":/buttons/toolbar/resource/calc.ico"), tr("Run calc.exe"), this);
    QAction* pactTaskmgr    = new QAction(QIcon(":/buttons/toolbar/resource/taskmgr.ico"), tr("Run taskmgr.exe"), this);
//    QAction* pactRegedit    = new QAction(QIcon(":/buttons/toolbar/resource/regedit.ico"), tr("Run regedit.exe"), this);


//Menu Bar
    QMenu* pmnuFile = menuBar()->addMenu("File");
    pmnuFile->addAction(pactQuit);

    QMenu* pmnuView = menuBar()->addMenu("View");
    QMenu* pmnuSetStyle     = new QMenu("Set Style", this);
    pmnuView->addMenu(pmnuSetStyle);
    for( QString styleName : QStyleFactory::keys() )
    {
        if (styleName == "Fusion"){
            QMenu* pmnuFusion   = new QMenu("Fusion");
            pmnuSetStyle->addMenu(pmnuFusion);
            QAction* pactFusionDefault  = new QAction("Default", this);
            QAction* pactFusionDark  = new QAction("Dark", this);
            pmnuFusion->addAction(pactFusionDefault);
            pmnuFusion->addAction(pactFusionDark);
            connect(pactFusionDefault,
                    &QAction::triggered,
                    [=](){
                    QApplication::setStyle(QStyleFactory::create("Fusion"));
            });
            connect(pactFusionDark,
                    &QAction::triggered,
                    [=](){
                    QApplication::setStyle(new ZBC_SimpleStyle);
            });
        }
        else{
            QAction* pactStyle  = new QAction(styleName, this);
            pmnuSetStyle->addAction(pactStyle);
            connect(pactStyle,
                    &QAction::triggered,
                    [=](){
                    QApplication::setStyle(QStyleFactory::create(styleName));
                    });
        }
    }


//Tool Bar
/*
    QToolBar* ptbrFile = addToolBar("File");
    ptbrFile->setMovable(false);
    ptbrFile->addAction(pactQuit);
*/

    QToolBar* ptbrGo = addToolBar("Go");
    ptbrGo->setMovable(false);
    ptbrGo->addAction(pactBack);
    ptbrGo->addAction(pactForward);

    QToolBar* ptbrTools = addToolBar(tr("Tools"));
    ptbrTools->setMovable(false);
    ptbrTools->addAction(pactCMD);
    ptbrTools->addAction(pactNotepad);
    ptbrTools->addAction(pactPaint);
    ptbrTools->addAction(pactCalc);
    ptbrTools->addAction(pactTaskmgr);
//    ptbrTools->addAction(pactRegedit);

//Central Widget
    ZBC_CentralWidget* pzbcCwgt = new ZBC_CentralWidget(this);
    this->setCentralWidget(pzbcCwgt);


//Connections
//Quit
    connect(pactQuit,
            &QAction::triggered,
            this,
            &QMainWindow::close);

//Go Back
    connect(pactBack,
            &QAction::triggered,
            pzbcCwgt,
            &ZBC_CentralWidget::goBack
            );

//Go Forward
    connect(pactForward,
            &QAction::triggered,
            pzbcCwgt,
            &ZBC_CentralWidget::goForward);


//Run cmd.exe
    connect(pactCMD,
            &QAction::triggered,
            [=](){
                QProcess* pprcCmd   = new QProcess(this);
                pprcCmd->startDetached("cmd.exe");
            });

//Run notepad.exe
    connect(pactNotepad,
            &QAction::triggered,
            [=](){
                QProcess* pprcCmd   = new QProcess(this);
                pprcCmd->startDetached("notepad.exe");
            });

//Run mspaint.exe
        connect(pactPaint,
                &QAction::triggered,
                [=](){
                    QProcess* pprcCmd   = new QProcess(this);
                    pprcCmd->startDetached("mspaint.exe");
                });

//Run calc.exe
        connect(pactCalc,
                &QAction::triggered,
                [=](){
                    QProcess* pprcCmd   = new QProcess(this);
                    pprcCmd->startDetached("calc.exe");
                });

//Run taskmgr.exe
        connect(pactTaskmgr,
                &QAction::triggered,
                [=](){
                    QProcess* pprcCmd   = new QProcess(this);
                    pprcCmd->startDetached("taskmgr.exe");
                });

//Run regedit.exe !!! Doesn't work!!!
/*
        connect(pactRegedit,
                &QAction::triggered,
                [=](){
                    QProcess* pprcCmd   = new QProcess(this);
                    pprcCmd->startDetached("regedit.exe");
                    qDebug() << "regedit.exe";
                });
*/

        connect(this,
                &ZBC_MainWindow::mainWindowClose,
                pzbcCwgt,
                &ZBC_CentralWidget::mainWindowClose);

//Settings
    QSettings Settings;
    Settings.beginGroup("/Settings");
    Settings.beginGroup("/MainWindow");
    if (Settings.contains("/Geometry"))
        this->restoreGeometry(Settings.value("/Geometry").toByteArray());
    Settings.endGroup();
    Settings.endGroup();
}
Example #25
0
void UpdateManager::requestReceived()
{
	bool haveNewVersion = false;
	QMessageBox msgbox;
	QString msgTitle = tr("Check for updates.");
	QString msgText = "<h3>" + tr("Subsurface was unable to check for updates.") + "</h3>";

	QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
	if (reply->error() != QNetworkReply::NoError) {
		//Network Error
		msgText = msgText + "<br/><b>" + tr("The following error occurred:") + "</b><br/>" + reply->errorString()
				+ "<br/><br/><b>" + tr("Please check your internet connection.") + "</b>";
	} else {
		//No network error
		QString responseBody(reply->readAll());
		QString responseLink;
		if (responseBody.contains('"'))
			responseLink = responseBody.split("\"").at(1);

		msgbox.setIcon(QMessageBox::Information);
		if (responseBody == "OK") {
			msgText = tr("You are using the latest version of Subsurface.");
		} else if (responseBody.startsWith("[\"http")) {
			haveNewVersion = true;
			msgText = tr("A new version of Subsurface is available.<br/>Click on:<br/><a href=\"%1\">%1</a><br/> to download it.")
					.arg(responseLink);
		} else if (responseBody.startsWith("Latest version")) {
			// the webservice backend doesn't localize - but it's easy enough to just replace the
			// strings that it is likely to send back
			haveNewVersion = true;
			msgText = QString("<b>") + tr("A new version of Subsurface is available.") + QString("</b><br/><br/>") +
					tr("Latest version is %1, please check %2 our download page %3 for information in how to update.")
					.arg(responseLink).arg("<a href=\"http://subsurface-divelog.org/download\">").arg("</a>");
		} else {
			// the webservice backend doesn't localize - but it's easy enough to just replace the
			// strings that it is likely to send back
			if (!responseBody.contains("latest development") &&
			    !responseBody.contains("newer") &&
			    !responseBody.contains("beta", Qt::CaseInsensitive))
				haveNewVersion = true;
			if (responseBody.contains("Newest release version is "))
				responseBody.replace("Newest release version is ", tr("Newest release version is "));
			msgText = tr("The server returned the following information:").append("<br/><br/>").append(responseBody);
			msgbox.setIcon(QMessageBox::Warning);
		}
	}
#ifndef SUBSURFACE_MOBILE
	if (haveNewVersion || !isAutomaticCheck) {
		msgbox.setWindowTitle(msgTitle);
		msgbox.setWindowIcon(QIcon(":/subsurface-icon"));
		msgbox.setText(msgText);
		msgbox.setTextFormat(Qt::RichText);
		msgbox.exec();
	}
	if (isAutomaticCheck) {
		QSettings settings;
		settings.beginGroup("UpdateManager");
		if (!settings.contains("DontCheckForUpdates")) {
			// we allow an opt out of future checks
			QMessageBox response(MainWindow::instance());
			QString message = tr("Subsurface is checking every two weeks if a new version is available. If you don't want Subsurface to continue checking, please click Decline.");
			response.addButton(tr("Decline"), QMessageBox::RejectRole);
			response.addButton(tr("Accept"), QMessageBox::AcceptRole);
			response.setText(message);
			response.setWindowTitle(tr("Automatic check for updates"));
			response.setIcon(QMessageBox::Question);
			response.setWindowModality(Qt::WindowModal);
			int ret = response.exec();
			if (ret == QMessageBox::Accepted)
				settings.setValue("DontCheckForUpdates", "FALSE");
			else
				settings.setValue("DontCheckForUpdates", "TRUE");
		}
	}
#endif
}
void GeneralSettingsPage::apply()
{
    if (!m_ui) // page was never shown
        return;
    QFont newFont;
    const QString &family = m_ui->familyComboBox->currentFont().family();
    newFont.setFamily(family);

    int fontSize = 14;
    int currentIndex = m_ui->sizeComboBox->currentIndex();
    if (currentIndex != -1)
        fontSize = m_ui->sizeComboBox->itemData(currentIndex).toInt();
    newFont.setPointSize(fontSize);

    QString fontStyle = QLatin1String("Normal");
    currentIndex = m_ui->styleComboBox->currentIndex();
    if (currentIndex != -1)
        fontStyle = m_ui->styleComboBox->itemText(currentIndex);
    newFont.setBold(m_fontDatabase.bold(family, fontStyle));
    if (fontStyle.contains(QLatin1String("Italic")))
        newFont.setStyle(QFont::StyleItalic);
    else if (fontStyle.contains(QLatin1String("Oblique")))
        newFont.setStyle(QFont::StyleOblique);
    else
        newFont.setStyle(QFont::StyleNormal);

    const int weight = m_fontDatabase.weight(family, fontStyle);
    if (weight >= 0)    // Weight < 0 asserts...
        newFont.setWeight(weight);

    if (newFont != m_font) {
        m_font = newFont;
        HelpManager::setCustomValue(QLatin1String("font"), newFont);
        emit fontChanged();
    }

    QString homePage = QUrl::fromUserInput(m_ui->homePageLineEdit->text()).toString();
    if (homePage.isEmpty())
        homePage = Help::Constants::AboutBlank;
    m_ui->homePageLineEdit->setText(homePage);
    if (m_homePage != homePage) {
        m_homePage = homePage;
        HelpManager::setCustomValue(QLatin1String("HomePage"), homePage);
    }

    const int startOption = m_ui->helpStartComboBox->currentIndex();
    if (m_startOption != startOption) {
        m_startOption = startOption;
        HelpManager::setCustomValue(QLatin1String("StartOption"), startOption);
    }

    const int helpOption = m_ui->contextHelpComboBox->currentIndex();
    if (m_contextOption != helpOption) {
        m_contextOption = helpOption;
        HelpManager::setCustomValue(QLatin1String("ContextHelpOption"), helpOption);

        QSettings *settings = Core::ICore::settings();
        settings->beginGroup(QLatin1String(Help::Constants::ID_MODE_HELP));
        settings->setValue(QLatin1String("ContextHelpOption"), helpOption);
        settings->endGroup();

        emit contextHelpOptionChanged();
    }

    const bool close = m_ui->m_returnOnClose->isChecked();
    if (m_returnOnClose != close) {
        m_returnOnClose = close;
        HelpManager::setCustomValue(QLatin1String("ReturnOnClose"), close);
        emit returnOnCloseChanged();
    }
}
Example #27
0
/// \brief Save the settings to the harddisk.
/// \param fileName Optional filename to read the settings from an ini file.
/// \return 0 on success, negative on error.
int DsoSettings::save(const QString &fileName) {
	// Use main configuration and save everything if the fileName wasn't set
	QSettings *settingsSaver;
	bool complete = fileName.isEmpty();
	if(complete)
		settingsSaver = new QSettings(this);
	else
		settingsSaver = new QSettings(fileName, QSettings::IniFormat, this);
	if(settingsSaver->status() != QSettings::NoError)
		return -settingsSaver->status();

	if(complete) {
		// Main window layout and other general options
		settingsSaver->beginGroup("options");
		settingsSaver->beginGroup("window");
		// Docking windows and toolbars
		settingsSaver->beginGroup("docks");
		QList<DsoSettingsOptionsWindowPanel *> docks;
		docks.append(&(this->options.window.dock.horizontal));
		docks.append(&(this->options.window.dock.spectrum));
		docks.append(&(this->options.window.dock.trigger));
		docks.append(&(this->options.window.dock.voltage));
		QStringList dockNames;
		dockNames << "horizontal" << "spectrum" << "trigger" << "voltage";
		for(int dockId = 0; dockId < docks.size(); ++dockId) {
			settingsSaver->beginGroup(dockNames[dockId]);
			settingsSaver->setValue("floating", docks[dockId]->floating);
			settingsSaver->setValue("position", docks[dockId]->position);
			settingsSaver->setValue("visible", docks[dockId]->visible);
			settingsSaver->endGroup();
		}
		settingsSaver->endGroup();
		settingsSaver->beginGroup("toolbars");
		QList<DsoSettingsOptionsWindowPanel *> toolbars;
		toolbars.append(&(this->options.window.toolbar.file));
		toolbars.append(&(this->options.window.toolbar.oscilloscope));
		toolbars.append(&(this->options.window.toolbar.view));
		QStringList toolbarNames;
		toolbarNames << "file" << "oscilloscope" << "view";
		for(int toolbarId = 0; toolbarId < toolbars.size(); ++toolbarId) {
			settingsSaver->beginGroup(toolbarNames[toolbarId]);
			settingsSaver->setValue("floating", toolbars[toolbarId]->floating);
			settingsSaver->setValue("position", toolbars[toolbarId]->position);
			settingsSaver->setValue("visible", toolbars[toolbarId]->visible);
			settingsSaver->endGroup();
		}
		settingsSaver->endGroup();
		// Main window
		settingsSaver->setValue("pos", this->options.window.position);
		settingsSaver->setValue("size", this->options.window.size);
		settingsSaver->endGroup();
		settingsSaver->setValue("alwaysSave", this->options.alwaysSave);
		settingsSaver->setValue("imageSize", this->options.imageSize);
		settingsSaver->endGroup();
	}
	// Oszilloskope settings
	settingsSaver->beginGroup("scope");
	// Horizontal axis
	settingsSaver->beginGroup("horizontal");
	settingsSaver->setValue("format", this->scope.horizontal.format);
	settingsSaver->setValue("frequencybase", this->scope.horizontal.frequencybase);
	for(int marker = 0; marker < 2; ++marker)
		settingsSaver->setValue(QString("marker%1").arg(marker), this->scope.horizontal.marker[marker]);
	settingsSaver->setValue("timebase", this->scope.horizontal.timebase);
	settingsSaver->setValue("recordLength", this->scope.horizontal.recordLength);
	settingsSaver->setValue("samplerate", this->scope.horizontal.samplerate);
	settingsSaver->setValue("samplerateSet", this->scope.horizontal.samplerateSet);
	settingsSaver->endGroup();
	// Trigger
	settingsSaver->beginGroup("trigger");
	settingsSaver->setValue("filter", this->scope.trigger.filter);
	settingsSaver->setValue("mode", this->scope.trigger.mode);
	settingsSaver->setValue("position", this->scope.trigger.position);
	settingsSaver->setValue("slope", this->scope.trigger.slope);
	settingsSaver->setValue("source", this->scope.trigger.source);
	settingsSaver->setValue("special", this->scope.trigger.special);
	settingsSaver->endGroup();
	// Spectrum
	for(int channel = 0; channel < this->scope.spectrum.count(); ++channel) {
		settingsSaver->beginGroup(QString("spectrum%1").arg(channel));
		settingsSaver->setValue("magnitude", this->scope.spectrum[channel].magnitude);
		settingsSaver->setValue("offset", this->scope.spectrum[channel].offset);
		settingsSaver->setValue("used", this->scope.spectrum[channel].used);
		settingsSaver->endGroup();
	}
	// Vertical axis
	for(int channel = 0; channel < this->scope.voltage.count(); ++channel) {
		settingsSaver->beginGroup(QString("vertical%1").arg(channel));
		settingsSaver->setValue("gain", this->scope.voltage[channel].gain);
		settingsSaver->setValue("misc", this->scope.voltage[channel].misc);
		settingsSaver->setValue("offset", this->scope.voltage[channel].offset);
		settingsSaver->setValue("trigger", this->scope.voltage[channel].trigger);
		settingsSaver->setValue("used", this->scope.voltage[channel].used);
		settingsSaver->endGroup();
	}
	settingsSaver->setValue("spectrumLimit", this->scope.spectrumLimit);
	settingsSaver->setValue("spectrumReference", this->scope.spectrumReference);
	settingsSaver->setValue("spectrumWindow", this->scope.spectrumWindow);
	settingsSaver->endGroup();
	
	// View
	settingsSaver->beginGroup("view");
	// Colors
	if(complete) {
		settingsSaver->beginGroup("color");
		DsoSettingsColorValues *colors;
		for(int mode = 0; mode < 2; ++mode) {
			if(mode == 0) {
				colors = &this->view.color.screen;
				settingsSaver->beginGroup("screen");
			}
			else {
				colors = &this->view.color.print;
				settingsSaver->beginGroup("print");
			}
			
			settingsSaver->setValue("axes", colors->axes);
			settingsSaver->setValue("background", colors->background);
			settingsSaver->setValue("border", colors->border);
			settingsSaver->setValue("grid", colors->grid);
			settingsSaver->setValue("markers", colors->markers);
			for(int channel = 0; channel < this->scope.spectrum.count(); ++channel)
				settingsSaver->setValue(QString("spectrum%1").arg(channel), colors->spectrum[channel]);
			settingsSaver->setValue("text", colors->text);
			for(int channel = 0; channel < this->scope.voltage.count(); ++channel)
				settingsSaver->setValue(QString("voltage%1").arg(channel), colors->voltage[channel]);
			settingsSaver->endGroup();
		}
		settingsSaver->endGroup();
	}
	// Other view settings
	settingsSaver->setValue("digitalPhosphor", this->view.digitalPhosphor);
	if(complete) {
		settingsSaver->setValue("interpolation", this->view.interpolation);
		settingsSaver->setValue("screenColorImages", this->view.screenColorImages);
	}
	settingsSaver->setValue("zoom", this->view.zoom);
	settingsSaver->endGroup();
	
	delete settingsSaver;
	
	return 0;
}
bool QgsManageConnectionsDialog::populateConnections()
{
  // Export mode. Populate connections list from settings
  if ( mDialogMode == Export )
  {
    QSettings settings;
    switch ( mConnectionType )
    {
      case WMS:
        settings.beginGroup( QStringLiteral( "/Qgis/connections-wms" ) );
        break;
      case WFS:
        settings.beginGroup( QStringLiteral( "/Qgis/connections-wfs" ) );
        break;
      case WCS:
        settings.beginGroup( QStringLiteral( "/Qgis/connections-wcs" ) );
        break;
      case PostGIS:
        settings.beginGroup( QStringLiteral( "/PostgreSQL/connections" ) );
        break;
      case MSSQL:
        settings.beginGroup( QStringLiteral( "/MSSQL/connections" ) );
        break;
      case Oracle:
        settings.beginGroup( QStringLiteral( "/Oracle/connections" ) );
        break;
      case DB2:
        settings.beginGroup( QStringLiteral( "/DB2/connections" ) );
        break;
    }
    QStringList keys = settings.childGroups();
    QStringList::Iterator it = keys.begin();
    while ( it != keys.end() )
    {
      QListWidgetItem *item = new QListWidgetItem();
      item->setText( *it );
      listConnections->addItem( item );
      ++it;
    }
    settings.endGroup();
  }
  // Import mode. Populate connections list from file
  else
  {
    QFile file( mFileName );
    if ( !file.open( QIODevice::ReadOnly | QIODevice::Text ) )
    {
      QMessageBox::warning( this, tr( "Loading connections" ),
                            tr( "Cannot read file %1:\n%2." )
                            .arg( mFileName,
                                  file.errorString() ) );
      return false;
    }

    QDomDocument doc;
    QString errorStr;
    int errorLine;
    int errorColumn;

    if ( !doc.setContent( &file, true, &errorStr, &errorLine, &errorColumn ) )
    {
      QMessageBox::warning( this, tr( "Loading connections" ),
                            tr( "Parse error at line %1, column %2:\n%3" )
                            .arg( errorLine )
                            .arg( errorColumn )
                            .arg( errorStr ) );
      return false;
    }

    QDomElement root = doc.documentElement();
    switch ( mConnectionType )
    {
      case WMS:
        if ( root.tagName() != QLatin1String( "qgsWMSConnections" ) )
        {
          QMessageBox::information( this, tr( "Loading connections" ),
                                    tr( "The file is not an WMS connections exchange file." ) );
          return false;
        }
        break;

      case WFS:
        if ( root.tagName() != QLatin1String( "qgsWFSConnections" ) )
        {
          QMessageBox::information( this, tr( "Loading connections" ),
                                    tr( "The file is not an WFS connections exchange file." ) );
          return false;
        }
        break;

      case WCS:
        if ( root.tagName() != QLatin1String( "qgsWCSConnections" ) )
        {
          QMessageBox::information( this, tr( "Loading connections" ),
                                    tr( "The file is not an WCS connections exchange file." ) );
          return false;
        }
        break;

      case PostGIS:
        if ( root.tagName() != QLatin1String( "qgsPgConnections" ) )
        {
          QMessageBox::information( this, tr( "Loading connections" ),
                                    tr( "The file is not an PostGIS connections exchange file." ) );
          return false;
        }
        break;

      case MSSQL:
        if ( root.tagName() != QLatin1String( "qgsMssqlConnections" ) )
        {
          QMessageBox::information( this, tr( "Loading connections" ),
                                    tr( "The file is not an MSSQL connections exchange file." ) );
          return false;
        }
        break;
      case Oracle:
        if ( root.tagName() != QLatin1String( "qgsOracleConnections" ) )
        {
          QMessageBox::information( this, tr( "Loading connections" ),
                                    tr( "The file is not an Oracle connections exchange file." ) );
          return false;
        }
        break;
      case DB2:
        if ( root.tagName() != QLatin1String( "qgsDb2Connections" ) )
        {
          QMessageBox::information( this, tr( "Loading connections" ),
                                    tr( "The file is not an DB2 connections exchange file." ) );
          return false;
        }
        break;
    }

    QDomElement child = root.firstChildElement();
    while ( !child.isNull() )
    {
      QListWidgetItem *item = new QListWidgetItem();
      item->setText( child.attribute( QStringLiteral( "name" ) ) );
      listConnections->addItem( item );
      child = child.nextSiblingElement();
    }
  }
  return true;
}
void DiveCalculatedTissue::preferencesChanged()
{
	QSettings s;
	s.beginGroup("TecDetails");
	setVisible(s.value("calcalltissues").toBool() && s.value("calcceiling").toBool());
}
Example #30
0
QStringList QgsOracleConn::connectionList()
{
  QSettings settings;
  settings.beginGroup( "/Oracle/connections" );
  return settings.childGroups();
}