コード例 #1
0
ファイル: lxmainwin.cpp プロジェクト: azureidea/lomox
LxMainWindow::LxMainWindow( QWidget* prarent /*= 0*/ )
:QWebView(prarent)
{
	_initWidget();
	this->setRenderHints(QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing);
 	QObject::connect(this, SIGNAL(linkClicked(const QUrl&)), this, SLOT(linkClickedAction(const QUrl&)));

	QNetworkAccessManager* pNetworkAccessManager = this->page()->networkAccessManager();
	LxOption* pOption = lxCoreApp->getOption();
	if (pOption && pNetworkAccessManager)
	{
		QString strCookies = pOption->getCookieFilePath();
		LxNetWorkCookies* pCookies = new LxNetWorkCookies(strCookies, this);
		pNetworkAccessManager->setCookieJar(pCookies);

		QNetworkDiskCache *diskCache = new QNetworkDiskCache(this);
		QString location = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
		//QString location = QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
		diskCache->setCacheDirectory(location);
		diskCache->setMaximumCacheSize(1024);//byte
		pNetworkAccessManager->setCache(diskCache);

		pNetworkAccessManager->setNetworkAccessible(QNetworkAccessManager::Accessible);

		m_bLoadHrefInCurrent = pOption->getLoadHrefInCurrentMainDialog();

	}
	QString iconName = pOption->getSystemTrayIconName();
	QString iconPath = QCoreApplication::applicationDirPath() + "/" + iconName;
	qDebug("show path %s", qPrintable(iconPath));
	QIcon icon(iconPath);
	this->setWindowIcon(icon);
}
コード例 #2
0
ファイル: WebProcessQt.cpp プロジェクト: 3163504123/phantomjs
void WebProcess::platformSetCacheModel(CacheModel cacheModel)
{
    uint64_t physicalMemorySizeInMegabytes = WTF::ramSize() / 1024 / 1024;

    // The Mac port of WebKit2 uses a fudge factor of 1000 here to account for misalignment, however,
    // that tends to overestimate the memory quite a bit (1 byte misalignment ~ 48 MiB misestimation).
    // We use 1024 * 1023 for now to keep the estimation error down to +/- ~1 MiB.
    QNetworkDiskCache* diskCache = qobject_cast<QNetworkDiskCache*>(m_networkAccessManager->cache());
    uint64_t freeVolumeSpace = !diskCache ? 0 : WebCore::getVolumeFreeSizeForPath(diskCache->cacheDirectory().toLocal8Bit().constData()) / 1024 / 1023;

    // The following variables are initialised to 0 because WebProcess::calculateCacheSizes might not
    // set them in some rare cases.
    unsigned cacheTotalCapacity = 0;
    unsigned cacheMinDeadCapacity = 0;
    unsigned cacheMaxDeadCapacity = 0;
    double deadDecodedDataDeletionInterval = 0;
    unsigned pageCacheCapacity = 0;
    unsigned long urlCacheMemoryCapacity = 0;
    unsigned long urlCacheDiskCapacity = 0;

    calculateCacheSizes(cacheModel, physicalMemorySizeInMegabytes, freeVolumeSpace,
                        cacheTotalCapacity, cacheMinDeadCapacity, cacheMaxDeadCapacity, deadDecodedDataDeletionInterval,
                        pageCacheCapacity, urlCacheMemoryCapacity, urlCacheDiskCapacity);

    if (diskCache)
        diskCache->setMaximumCacheSize(urlCacheDiskCapacity);

    memoryCache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
    memoryCache()->setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);

    pageCache()->setCapacity(pageCacheCapacity);

    // FIXME: Implement hybrid in-memory- and disk-caching as e.g. the Mac port does.
}
コード例 #3
0
QNetworkAccessManager* TBNetworkAccessManagerFactory::create(QObject *parent)
{
    QMutexLocker lock(&mutex);
    Q_UNUSED(lock);
    QNetworkAccessManager* manager = new TBNetworkAccessManager(parent);

#ifdef Q_OS_SYMBIAN
    bool useDiskCache = Utility::Instance()->qtVersion() >= 0x040800;
#else
    bool useDiskCache = true;
#endif
    if (useDiskCache){
        QNetworkDiskCache* diskCache = new QNetworkDiskCache(parent);
        QString dataPath = QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
        QDir dir(dataPath);
        if (!dir.exists()) dir.mkpath(dir.absolutePath());

        diskCache->setCacheDirectory(dataPath);
        diskCache->setMaximumCacheSize(3*1024*1024);
        manager->setCache(diskCache);
    }

    QNetworkCookieJar* cookieJar = TBNetworkCookieJar::GetInstance();
    manager->setCookieJar(cookieJar);
    cookieJar->setParent(0);

    return manager;
}
コード例 #4
0
ファイル: mainwindow.cpp プロジェクト: warchiefmarkus/VK
QNetworkAccessManager *MyNetworkAccessManagerFactory::create(QObject *parent)
{
    QNetworkAccessManager *nam = new QNetworkAccessManager(parent);
    QNetworkDiskCache* cache = new QNetworkDiskCache(parent);
    // 500 Mb
    cache->setMaximumCacheSize(500*1024*1024);
    cache->setCacheDirectory("cacheDir");
    nam->setCache(cache);

    return nam;
}
コード例 #5
0
ファイル: networkmanager.cpp プロジェクト: Fisiu/qupzilla
void NetworkManager::loadSettings()
{
    Settings settings;

    if (settings.value("Web-Browser-Settings/AllowLocalCache", true).toBool() && !mApp->isPrivateSession()) {
        QNetworkDiskCache* cache = mApp->networkCache();
        cache->setMaximumCacheSize(settings.value("MaximumCacheSize", 50).toInt() * 1024 * 1024); //MegaBytes
        setCache(cache);
    }

    settings.beginGroup("Web-Browser-Settings");
    m_doNotTrack = settings.value("DoNotTrack", false).toBool();
    m_sendReferer = settings.value("SendReferer", true).toBool();
    settings.endGroup();
    m_acceptLanguage = AcceptLanguage::generateHeader(settings.value("Language/acceptLanguage", AcceptLanguage::defaultLanguage()).toStringList());

    // Falling back to Qt 4.7 default behavior, use SslV3 by default
    // Fixes issue with some older servers closing the connection

    // However, it also makes some servers requesting TLS ClientHello
    // not working, or showing invalid certificates.
    // See #921

    // QSslConfiguration config = QSslConfiguration::defaultConfiguration();
    // config.setProtocol(QSsl::SslV3);
    // QSslConfiguration::setDefaultConfiguration(config);

#if defined(Q_OS_WIN) || defined(Q_OS_HAIKU) || defined(Q_OS_OS2)
    QString certDir = mApp->PROFILEDIR + "certificates";
    QString bundlePath = certDir + "/ca-bundle.crt";
    QString bundleVersionPath = certDir + "/bundle_version";

    if (!QDir(certDir).exists()) {
        QDir dir(mApp->PROFILEDIR);
        dir.mkdir("certificates");
    }

    if (!QFile::exists(bundlePath)) {
        QFile(":data/ca-bundle.crt").copy(bundlePath);
        QFile(bundlePath).setPermissions(QFile::ReadUser | QFile::WriteUser);

        QFile(":data/bundle_version").copy(bundleVersionPath);
        QFile(bundleVersionPath).setPermissions(QFile::ReadUser | QFile::WriteUser);
    }

    QSslSocket::setDefaultCaCertificates(QSslCertificate::fromPath(bundlePath));
#else
    QSslSocket::setDefaultCaCertificates(QSslSocket::systemCaCertificates());
#endif

    loadCertificates();

    m_proxyFactory->loadSettings();
}
コード例 #6
0
ファイル: qgsserver.cpp プロジェクト: SrNetoChan/Quantum-GIS
void QgsServer::setupNetworkAccessManager()
{
  QSettings settings;
  QgsNetworkAccessManager *nam = QgsNetworkAccessManager::instance();
  QNetworkDiskCache *cache = new QNetworkDiskCache( nullptr );
  qint64 cacheSize = sSettings.cacheSize();
  QString cacheDirectory = sSettings.cacheDirectory();
  cache->setCacheDirectory( cacheDirectory );
  cache->setMaximumCacheSize( cacheSize );
  QgsMessageLog::logMessage( QStringLiteral( "cacheDirectory: %1" ).arg( cache->cacheDirectory() ), QStringLiteral( "Server" ), Qgis::Info );
  QgsMessageLog::logMessage( QStringLiteral( "maximumCacheSize: %1" ).arg( cache->maximumCacheSize() ), QStringLiteral( "Server" ), Qgis::Info );
  nam->setCache( cache );
}
コード例 #7
0
ファイル: qgsserver.cpp プロジェクト: yingyuankai/QGIS
/**
 * @brief QgsServer::setupNetworkAccessManager
 */
void QgsServer::setupNetworkAccessManager()
{
  QSettings settings;
  QgsNetworkAccessManager *nam = QgsNetworkAccessManager::instance();
  QNetworkDiskCache *cache = new QNetworkDiskCache( 0 );
  QString cacheDirectory = settings.value( "cache/directory", QgsApplication::qgisSettingsDirPath() + "cache" ).toString();
  qint64 cacheSize = settings.value( "cache/size", 50 * 1024 * 1024 ).toULongLong();
  QgsDebugMsg( QString( "setCacheDirectory: %1" ).arg( cacheDirectory ) );
  QgsDebugMsg( QString( "setMaximumCacheSize: %1" ).arg( cacheSize ) );
  cache->setCacheDirectory( cacheDirectory );
  cache->setMaximumCacheSize( cacheSize );
  QgsDebugMsg( QString( "cacheDirectory: %1" ).arg( cache->cacheDirectory() ) );
  QgsDebugMsg( QString( "maximumCacheSize: %1" ).arg( cache->maximumCacheSize() ) );
  nam->setCache( cache );
}
コード例 #8
0
ファイル: networkmanager.cpp プロジェクト: Mikino89/QupZilla
void NetworkManager::loadSettings()
{
    Settings settings;
    settings.beginGroup("Web-Browser-Settings");

    if (settings.value("AllowLocalCache", true).toBool() && !mApp->isPrivateSession()) {
        QNetworkDiskCache* cache = mApp->networkCache();
        cache->setMaximumCacheSize(settings.value("MaximumCacheSize", 50).toInt() * 1024 * 1024); //MegaBytes
        setCache(cache);
    }

    m_doNotTrack = settings.value("DoNotTrack", false).toBool();
    m_sendReferer = settings.value("SendReferer", true).toBool();
    settings.endGroup();
    m_acceptLanguage = AcceptLanguage::generateHeader(settings.value("Language/acceptLanguage", AcceptLanguage::defaultLanguage()).toStringList());

#ifdef Q_OS_WIN
    // From doc:
    // QSslSocket::VerifyNone ... The connection will still be encrypted, and your socket
    // will still send its local certificate to the peer if it's requested.

    QSslConfiguration config = QSslConfiguration::defaultConfiguration();
    config.setPeerVerifyMode(QSslSocket::VerifyNone);
    QSslConfiguration::setDefaultConfiguration(config);
#endif

    QString certDir = mApp->PROFILEDIR + "certificates";
    QString bundlePath = certDir + "/ca-bundle.crt";
    QString bundleVersionPath = certDir + "/bundle_version";

    if (!QDir(certDir).exists()) {
        QDir dir(mApp->PROFILEDIR);
        dir.mkdir("certificates");
    }

    if (!QFile::exists(bundlePath)) {
        QFile(":data/ca-bundle.crt").copy(bundlePath);
        QFile(bundlePath).setPermissions(QFile::ReadUser | QFile::WriteUser);

        QFile(":data/bundle_version").copy(bundleVersionPath);
        QFile(bundleVersionPath).setPermissions(QFile::ReadUser | QFile::WriteUser);
    }

    QSslSocket::setDefaultCaCertificates(QSslCertificate::fromPath(bundlePath));

    m_proxyFactory->loadSettings();
}
コード例 #9
0
ファイル: AssetClient.cpp プロジェクト: kencooke/hifi
void AssetClient::init() {
    Q_ASSERT(QThread::currentThread() == thread());

    // Setup disk cache if not already
    auto& networkAccessManager = NetworkAccessManager::getInstance();
    if (!networkAccessManager.cache()) {
        QString cachePath = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
        cachePath = !cachePath.isEmpty() ? cachePath : "interfaceCache";

        QNetworkDiskCache* cache = new QNetworkDiskCache();
        cache->setMaximumCacheSize(MAXIMUM_CACHE_SIZE);
        cache->setCacheDirectory(cachePath);
        networkAccessManager.setCache(cache);
        qInfo() << "ResourceManager disk cache setup at" << cachePath
                << "(size:" << MAXIMUM_CACHE_SIZE / BYTES_PER_GIGABYTES << "GB)";
    }
}
コード例 #10
0
ファイル: AssetClient.cpp プロジェクト: disigma/hifi
void AssetClient::init() {
    if (QThread::currentThread() != thread()) {
        QMetaObject::invokeMethod(this, "init", Qt::BlockingQueuedConnection);
    }
    
    // Setup disk cache if not already
    QNetworkAccessManager& networkAccessManager = NetworkAccessManager::getInstance();
    if (!networkAccessManager.cache()) {
        QString cachePath = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
        cachePath = !cachePath.isEmpty() ? cachePath : "interfaceCache";
        
        QNetworkDiskCache* cache = new QNetworkDiskCache();
        cache->setMaximumCacheSize(MAXIMUM_CACHE_SIZE);
        cache->setCacheDirectory(cachePath);
        networkAccessManager.setCache(cache);
        qCDebug(asset_client) << "AssetClient disk cache setup at" << cachePath
                                << "(size:" << MAXIMUM_CACHE_SIZE / BYTES_PER_GIGABYTES << "GB)";
    }
}
コード例 #11
0
ファイル: mywebpage.cpp プロジェクト: keystore00/AskMona-qt
MyWebPage::MyWebPage(QObject *parent) :
  QWebPage(parent)
{
  auto pNAM = networkAccessManager();
  QNetworkDiskCache * pNDC = new QNetworkDiskCache(parent);
  pNDC->setCacheDirectory(getDataDir()+"/cache");

  qint64 size = pNDC->cacheSize();
  size = pNDC->maximumCacheSize();
  const qint64 desired = 1024*1024*1024;

  if (size < desired) {
    pNDC->setMaximumCacheSize(desired);
    size = pNDC->maximumCacheSize();
  }

  QString dir = pNDC->cacheDirectory();
  pNAM->setCache(pNDC);

  auto cj = new CookieJar(parent);
  pNAM->setCookieJar(cj);
}
コード例 #12
0
QGeoMappingManagerEngineGoogle::QGeoMappingManagerEngineGoogle(const QMap<QString, QVariant> &parameters, QGeoServiceProvider::Error *error, QString *errorString)
    : QGeoTiledMappingManagerEngine(parameters),
      m_parameters(parameters),
      m_nam(NULL)
{
    QNetworkDiskCache *cache = NULL;

    Q_UNUSED(error)
    Q_UNUSED(errorString)

    setTileSize(QSize(256, 256));
    setMinimumZoomLevel(0.0);
    setMaximumZoomLevel(17.0);

    QList<QGraphicsGeoMap::MapType> types;
    types << QGraphicsGeoMap::StreetMap;
    types << QGraphicsGeoMap::SatelliteMapDay;
    setSupportedMapTypes(types);

    QList<QGraphicsGeoMap::ConnectivityMode> modes;
    modes << QGraphicsGeoMap::OnlineMode;
    setSupportedConnectivityModes(modes);

    QList<QString> keys = m_parameters.keys();

    if (keys.contains("mapping.networkaccessmanager")) {
	QNetworkAccessManager *nam;
	nam = (QNetworkAccessManager *)m_parameters
	    .value("mapping.networkaccessmanager").value<void *>();
	if (nam)
	    m_nam = nam;
    }

    if (!m_nam) {
	m_nam = new QNetworkAccessManager(this);
	cache = new QNetworkDiskCache(this);
    }

    if (cache) {
	QDir dir = QDir::temp();
	dir.mkdir("maptiles-google");
	dir.cd("maptiles-google");

	cache->setCacheDirectory(dir.path());
    }

    if (keys.contains("mapping.proxy")) {
        QString proxy = m_parameters.value("mapping.proxy").toString();
        if (!proxy.isEmpty())
	  m_nam->setProxy(parseProxy(proxy));
    }

    if (cache && keys.contains("mapping.cache.directory")) {
        QString cacheDir = m_parameters.value("mapping.cache.directory").toString();
        if (!cacheDir.isEmpty())
            cache->setCacheDirectory(cacheDir);
    }

    if (cache && keys.contains("mapping.cache.size")) {
        bool ok = false;
        qint64 cacheSize = m_parameters.value("mapping.cache.size").toString().toLongLong(&ok);
        if (ok)
            cache->setMaximumCacheSize(cacheSize);
    }

    if (cache)
	m_nam->setCache(cache);
}
コード例 #13
0
int main( int argc, char * argv[] )
{
#ifndef _MSC_VER
  qInstallMsgHandler( dummyMessageHandler );
#endif

  QgsApplication qgsapp( argc, argv, getenv( "DISPLAY" ) );

  //Default prefix path may be altered by environment variable
  char* prefixPath = getenv( "QGIS_PREFIX_PATH" );
  if ( prefixPath )
  {
    QgsApplication::setPrefixPath( prefixPath, TRUE );
  }
#if !defined(Q_OS_WIN)
  else
  {
    // init QGIS's paths - true means that all path will be inited from prefix
    QgsApplication::setPrefixPath( CMAKE_INSTALL_PREFIX, TRUE );
  }
#endif

#if defined(MAPSERVER_SKIP_ECW)
  QgsDebugMsg( "Skipping GDAL ECW drivers in server." );
  QgsApplication::skipGdalDriver( "ECW" );
  QgsApplication::skipGdalDriver( "JP2ECW" );
#endif

  QSettings settings;

  QgsNetworkAccessManager *nam = QgsNetworkAccessManager::instance();
  QNetworkDiskCache *cache = new QNetworkDiskCache( 0 );

  QString cacheDirectory = settings.value( "cache/directory", QgsApplication::qgisSettingsDirPath() + "cache" ).toString();
  qint64 cacheSize = settings.value( "cache/size", 50 * 1024 * 1024 ).toULongLong();
  QgsDebugMsg( QString( "setCacheDirectory: %1" ).arg( cacheDirectory ) );
  QgsDebugMsg( QString( "setMaximumCacheSize: %1" ).arg( cacheSize ) );
  cache->setCacheDirectory( cacheDirectory );
  cache->setMaximumCacheSize( cacheSize );
  QgsDebugMsg( QString( "cacheDirectory: %1" ).arg( cache->cacheDirectory() ) );
  QgsDebugMsg( QString( "maximumCacheSize: %1" ).arg( cache->maximumCacheSize() ) );

  nam->setCache( cache );

  QDomImplementation::setInvalidDataPolicy( QDomImplementation::DropInvalidChars );

  // Instantiate the plugin directory so that providers are loaded
  QgsProviderRegistry::instance( QgsApplication::pluginPath() );
  QgsDebugMsg( "Prefix  PATH: " + QgsApplication::prefixPath() );
  QgsDebugMsg( "Plugin  PATH: " + QgsApplication::pluginPath() );
  QgsDebugMsg( "PkgData PATH: " + QgsApplication::pkgDataPath() );
  QgsDebugMsg( "User DB PATH: " + QgsApplication::qgisUserDbFilePath() );

  QgsDebugMsg( qgsapp.applicationDirPath() + "/qgis_wms_server.log" );
  QgsApplication::createDB(); //init qgis.db (e.g. necessary for user crs)

  //create config cache and search for config files in the current directory.
  //These configurations are used if no mapfile parameter is present in the request
  QString defaultConfigFilePath;
  QFileInfo projectFileInfo = defaultProjectFile(); //try to find a .qgs file in the server directory
  if ( projectFileInfo.exists() )
  {
    defaultConfigFilePath = projectFileInfo.absoluteFilePath();
  }
  else
  {
    QFileInfo adminSLDFileInfo = defaultAdminSLD();
    if ( adminSLDFileInfo.exists() )
    {
      defaultConfigFilePath = adminSLDFileInfo.absoluteFilePath();
    }
  }

  //create cache for capabilities XML
  QgsCapabilitiesCache capabilitiesCache;

  //creating QgsMapRenderer is expensive (access to srs.db), so we do it here before the fcgi loop
  QgsMapRenderer* theMapRenderer = new QgsMapRenderer();
  theMapRenderer->setLabelingEngine( new QgsPalLabeling() );

  while ( fcgi_accept() >= 0 )
  {
    printRequestInfos(); //print request infos if in debug mode

    //use QgsGetRequestHandler in case of HTTP GET and QgsSOAPRequestHandler in case of HTTP POST
    QgsRequestHandler* theRequestHandler = 0;
    char* requestMethod = getenv( "REQUEST_METHOD" );
    if ( requestMethod != NULL )
    {
      if ( strcmp( requestMethod, "POST" ) == 0 )
      {
        //QgsDebugMsg( "Creating QgsSOAPRequestHandler" );
        //theRequestHandler = new QgsSOAPRequestHandler();
        theRequestHandler = new QgsPostRequestHandler();
      }
      else
      {
        QgsDebugMsg( "Creating QgsGetRequestHandler" );
        theRequestHandler = new QgsGetRequestHandler();
      }
    }
    else
    {
      QgsDebugMsg( "Creating QgsGetRequestHandler" );
      theRequestHandler = new QgsGetRequestHandler();
    }

    QMap<QString, QString> parameterMap;

    try
    {
      parameterMap = theRequestHandler->parseInput();
    }
    catch ( QgsMapServiceException& e )
    {
      QgsDebugMsg( "An exception was thrown during input parsing" );
      theRequestHandler->sendServiceException( e );
      continue;
    }

    QMap<QString, QString>::const_iterator paramIt;

    //set admin config file to wms server object
    QString configFilePath( defaultConfigFilePath );

    paramIt = parameterMap.find( "MAP" );
    if ( paramIt == parameterMap.constEnd() )
    {
      QgsDebugMsg( QString( "Using default configuration file path: %1" ).arg( defaultConfigFilePath ) );
    }
    else
    {
      configFilePath = paramIt.value();
    }

    QgsConfigParser* adminConfigParser = QgsConfigCache::instance()->searchConfiguration( configFilePath );
    if ( !adminConfigParser )
    {
      QgsDebugMsg( "parse error on config file " + configFilePath );
      theRequestHandler->sendServiceException( QgsMapServiceException( "", "Configuration file problem : perhaps you left off the .qgs extension?" ) );
      continue;
    }

    //sld parser might need information about request parameters
    adminConfigParser->setParameterMap( parameterMap );

    //request to WMS?
    QString serviceString;
    paramIt = parameterMap.find( "SERVICE" );
    if ( paramIt == parameterMap.constEnd() )
    {
#ifndef QGISDEBUG
      serviceString = parameterMap.value( "SERVICE", "WMS" );
#else
      QgsDebugMsg( "unable to find 'SERVICE' parameter, exiting..." );
      theRequestHandler->sendServiceException( QgsMapServiceException( "ServiceNotSpecified", "Service not specified. The SERVICE parameter is mandatory" ) );
      delete theRequestHandler;
      continue;
#endif
    }
    else
    {
      serviceString = paramIt.value();
    }

    QgsWMSServer* theServer = 0;
    if ( serviceString == "WFS" )
    {
      delete theServer;
      QgsWFSServer* theServer = 0;
      try
      {
        theServer = new QgsWFSServer( parameterMap );
      }
      catch ( QgsMapServiceException e ) //admin.sld may be invalid
      {
        theRequestHandler->sendServiceException( e );
        continue;
      }

      theServer->setAdminConfigParser( adminConfigParser );


      //request type
      QString request = parameterMap.value( "REQUEST" );
      if ( request.isEmpty() )
      {
        //do some error handling
        QgsDebugMsg( "unable to find 'REQUEST' parameter, exiting..." );
        theRequestHandler->sendServiceException( QgsMapServiceException( "OperationNotSupported", "Please check the value of the REQUEST parameter" ) );
        delete theRequestHandler;
        delete theServer;
        continue;
      }

      if ( request.compare( "GetCapabilities", Qt::CaseInsensitive ) == 0 )
      {
        QDomDocument capabilitiesDocument;
        try
        {
          capabilitiesDocument = theServer->getCapabilities();
        }
        catch ( QgsMapServiceException& ex )
        {
          theRequestHandler->sendServiceException( ex );
          delete theRequestHandler;
          delete theServer;
          continue;
        }
        QgsDebugMsg( "sending GetCapabilities response" );
        theRequestHandler->sendGetCapabilitiesResponse( capabilitiesDocument );
        delete theRequestHandler;
        delete theServer;
        continue;
      }
      else if ( request.compare( "DescribeFeatureType", Qt::CaseInsensitive ) == 0 )
      {
        QDomDocument describeDocument;
        try
        {
          describeDocument = theServer->describeFeatureType();
        }
        catch ( QgsMapServiceException& ex )
        {
          theRequestHandler->sendServiceException( ex );
          delete theRequestHandler;
          delete theServer;
          continue;
        }
        QgsDebugMsg( "sending GetCapabilities response" );
        theRequestHandler->sendGetCapabilitiesResponse( describeDocument );
        delete theRequestHandler;
        delete theServer;
        continue;
      }
      else if ( request.compare( "GetFeature", Qt::CaseInsensitive ) == 0 )
      {
        //output format for GetFeature
        QString outputFormat = parameterMap.value( "OUTPUTFORMAT" );
        try
        {
          if ( theServer->getFeature( *theRequestHandler, outputFormat ) != 0 )
          {
            delete theRequestHandler;
            delete theServer;
            continue;
          }
          else
          {
            delete theRequestHandler;
            delete theServer;
            continue;
          }
        }
        catch ( QgsMapServiceException& ex )
        {
          theRequestHandler->sendServiceException( ex );
          delete theRequestHandler;
          delete theServer;
          continue;
        }
      }
      else if ( request.compare( "Transaction", Qt::CaseInsensitive ) == 0 )
      {
        QDomDocument transactionDocument;
        try
        {
          transactionDocument = theServer->transaction( parameterMap.value( "REQUEST_BODY" ) );
        }
        catch ( QgsMapServiceException& ex )
        {
          theRequestHandler->sendServiceException( ex );
          delete theRequestHandler;
          delete theServer;
          continue;
        }
        QgsDebugMsg( "sending Transaction response" );
        theRequestHandler->sendGetCapabilitiesResponse( transactionDocument );
        delete theRequestHandler;
        delete theServer;
        continue;
      }

      return 0;
    }

    try
    {
      theServer = new QgsWMSServer( parameterMap, theMapRenderer );
    }
    catch ( QgsMapServiceException e ) //admin.sld may be invalid
    {
      theRequestHandler->sendServiceException( e );
      continue;
    }

    theServer->setAdminConfigParser( adminConfigParser );


    //request type
    QString request = parameterMap.value( "REQUEST" );
    if ( request.isEmpty() )
    {
      //do some error handling
      QgsDebugMsg( "unable to find 'REQUEST' parameter, exiting..." );
      theRequestHandler->sendServiceException( QgsMapServiceException( "OperationNotSupported", "Please check the value of the REQUEST parameter" ) );
      delete theRequestHandler;
      delete theServer;
      continue;
    }

    QString version = parameterMap.value( "VERSION", "1.3.0" );
    bool getProjectSettings = ( request.compare( "GetProjectSettings", Qt::CaseInsensitive ) == 0 );
    if ( getProjectSettings )
    {
      version = "1.3.0"; //getProjectSettings extends WMS 1.3.0 capabilities
    }

    if ( request.compare( "GetCapabilities", Qt::CaseInsensitive ) == 0 || getProjectSettings )
    {
      const QDomDocument* capabilitiesDocument = capabilitiesCache.searchCapabilitiesDocument( configFilePath, getProjectSettings ? "projectSettings" : version );
      if ( !capabilitiesDocument ) //capabilities xml not in cache. Create a new one
      {
        QgsDebugMsg( "Capabilities document not found in cache" );
        QDomDocument doc;
        try
        {
          doc = theServer->getCapabilities( version, getProjectSettings );
        }
        catch ( QgsMapServiceException& ex )
        {
          theRequestHandler->sendServiceException( ex );
          delete theRequestHandler;
          delete theServer;
          continue;
        }
        capabilitiesCache.insertCapabilitiesDocument( configFilePath, getProjectSettings ? "projectSettings" : version, &doc );
        capabilitiesDocument = capabilitiesCache.searchCapabilitiesDocument( configFilePath, getProjectSettings ? "projectSettings" : version );
      }
      else
      {
        QgsDebugMsg( "Found capabilities document in cache" );
      }

      if ( capabilitiesDocument )
      {
        theRequestHandler->sendGetCapabilitiesResponse( *capabilitiesDocument );
      }
      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.compare( "GetMap", Qt::CaseInsensitive ) == 0 )
    {
      QImage* result = 0;
      try
      {
        result = theServer->getMap();
      }
      catch ( QgsMapServiceException& ex )
      {
        QgsDebugMsg( "Caught exception during GetMap request" );
        theRequestHandler->sendServiceException( ex );
        delete theRequestHandler;
        delete theServer;
        continue;
      }

      if ( result )
      {
        QgsDebugMsg( "Sending GetMap response" );
        theRequestHandler->sendGetMapResponse( serviceString, result );
        QgsDebugMsg( "Response sent" );
      }
      else
      {
        //do some error handling
        QgsDebugMsg( "result image is 0" );
      }
      delete result;
      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.compare( "GetFeatureInfo", Qt::CaseInsensitive ) == 0 )
    {
      QDomDocument featureInfoDoc;
      try
      {
        if ( theServer->getFeatureInfo( featureInfoDoc, version ) != 0 )
        {
          delete theRequestHandler;
          delete theServer;
          continue;
        }
      }
      catch ( QgsMapServiceException& ex )
      {
        theRequestHandler->sendServiceException( ex );
        delete theRequestHandler;
        delete theServer;
        continue;
      }

      QString infoFormat = parameterMap.value( "INFO_FORMAT" );
      theRequestHandler->sendGetFeatureInfoResponse( featureInfoDoc, infoFormat );
      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.compare( "GetContext", Qt::CaseInsensitive ) == 0 )
    {
      try
      {
        QDomDocument doc = theServer->getContext();
        theRequestHandler->sendGetStyleResponse( doc );
      }
      catch ( QgsMapServiceException& ex )
      {
        theRequestHandler->sendServiceException( ex );
      }

      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.compare( "GetStyles", Qt::CaseInsensitive ) == 0 || request.compare( "GetStyle", Qt::CaseInsensitive ) == 0 ) // GetStyle for compatibility with earlier QGIS versions
    {
      try
      {
        QDomDocument doc = theServer->getStyle();
        theRequestHandler->sendGetStyleResponse( doc );
      }
      catch ( QgsMapServiceException& ex )
      {
        theRequestHandler->sendServiceException( ex );
      }

      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.compare( "GetLegendGraphic", Qt::CaseInsensitive ) == 0 ||
              request.compare( "GetLegendGraphics", Qt::CaseInsensitive ) == 0 )
      // GetLegendGraphics for compatibility with earlier QGIS versions
    {
      QImage* result = 0;
      try
      {
        result = theServer->getLegendGraphics();
      }
      catch ( QgsMapServiceException& ex )
      {
        QgsDebugMsg( "Caught exception during GetLegendGraphic request" );
        theRequestHandler->sendServiceException( ex );
      }

      if ( result )
      {
        QgsDebugMsg( "Sending GetLegendGraphic response" );
        //sending is the same for GetMap and GetLegendGraphic
        theRequestHandler->sendGetMapResponse( serviceString, result );
        QgsDebugMsg( "Response sent" );
      }
      else
      {
        //do some error handling
        QgsDebugMsg( "result image is 0" );
      }
      delete result;
      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else if ( request.compare( "GetPrint", Qt::CaseInsensitive ) == 0 )
    {
      QByteArray* printOutput = 0;
      try
      {
        printOutput = theServer->getPrint( theRequestHandler->format() );
      }
      catch ( QgsMapServiceException& ex )
      {
        theRequestHandler->sendServiceException( ex );
      }

      if ( printOutput )
      {
        theRequestHandler->sendGetPrintResponse( printOutput );
      }
      delete printOutput;
      delete theRequestHandler;
      delete theServer;
      continue;
    }
    else//unknown request
    {
      QgsMapServiceException e( "OperationNotSupported", "Operation " + request + " not supported" );
      theRequestHandler->sendServiceException( e );
      delete theRequestHandler;
      delete theServer;
    }
  }

  delete theMapRenderer;
  QgsDebugMsg( "************* all done ***************" );
  return 0;
}
コード例 #14
0
ファイル: main.cpp プロジェクト: djdarkbeat/ZTopo
int main(int argc, char **argv)
{
  qRegisterMetaType<Cache::Key>("Key");
  qRegisterMetaType<Tile>("Tile");
  qRegisterMetaType<qkey>("qkey");

  QCoreApplication::setOrganizationName("ZTopo");
  QCoreApplication::setApplicationName("ZTopo");

  QApplication app(argc, argv);

#if defined(Q_WS_MAC)
  QApplication::instance()->setAttribute(Qt::AA_DontShowIconsInMenus);
  // Mac OS specific code to find resources within a bundle
  CFURLRef appUrlRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
  CFStringRef macPath = CFURLCopyFileSystemPath(appUrlRef,
                                                kCFURLPOSIXPathStyle);
  const char *pathPtr = CFStringGetCStringPtr(macPath,
                                              CFStringGetSystemEncoding());
  if (!pathPtr) {
    qFatal("Could not find Mac application bundle path!");
  }
  QString rootPath = QString(pathPtr) % "/Contents/Resources/";
  QByteArray rootPathArray = QString(rootPath % "proj4").toLatin1();
  //qDebug("proj root '%s'\n", rootPathArray.data());

  const char *path[] = { rootPathArray.data() };
  pj_set_searchpath(1, (const char **)&path);
  CFRelease(appUrlRef);
  CFRelease(macPath);  
#elif defined(Q_WS_WIN)
  /* On Windows, use the proj4 subdirectory of the directory containing the 
     application */
  QString projPath = app.applicationDirPath() % "/proj4";
  //qDebug() << "proj root" << projPath;
  const char *path[] = { QDir::toNativeSeparators(projPath).toLatin1().data() };
  pj_set_searchpath(1, (const char **)&path);
#endif

  // On other operating systems, we assume the proj4 library can find its own datum
  // shift grids.

  QSettings settings;
  QString cachePath = settings.value("cachePath", 
      QDesktopServices::storageLocation(QDesktopServices::CacheLocation)).toString();
  QDir::current().mkpath(cachePath);

  QNetworkAccessManager networkManager;
  QNetworkDiskCache diskCache;
  diskCache.setCacheDirectory(cachePath % "/meta");
  diskCache.setMaximumCacheSize(maxDiskCacheSize);
  networkManager.setCache(&diskCache);
 

  RootData rootData(&networkManager);

  if (rootData.maps().size() == 0) {
    qFatal("No maps in root data file!");
  }
  Map *map = rootData.maps().values()[0];

  int maxMemCache = settings.value(settingMemCache, 64).toInt();
  int maxDiskCache = settings.value(settingDiskCache, 200).toInt();
  Cache::Cache tileCache(map, networkManager, maxMemCache, maxDiskCache, cachePath);
  MapRenderer renderer(map, tileCache);
  MainWindow *window = new MainWindow(rootData, map, &renderer, tileCache, 
                                      networkManager);

  window->show();

  if (rootData.majorVersion() > majorVersion || 
      (rootData.majorVersion() == majorVersion 
       && rootData.minorVersion() > minorVersion)) {
    QMessageBox mbox;
    mbox.setText("A new version of ZTopo is available.");
    mbox.setInformativeText(QString("A new version of ZTopo (%1.%2) is available for download. Would you like to open the ZTopo home page?").arg(rootData.majorVersion()).arg(rootData.minorVersion()));
    mbox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    mbox.setDefaultButton(QMessageBox::Yes);
    int ret = mbox.exec();
    if (ret == QMessageBox::Yes) {
      QDesktopServices::openUrl(QUrl(rootData.homePageUrl()));
    }
  }

  return app.exec();
}
コード例 #15
0
ファイル: mainwindow.cpp プロジェクト: Grandge/KanmusuMemory
MainWindow::Private::Private(MainWindow *parent)
    : q(parent)
    , settings(SETTING_FILE_NAME, SETTING_FILE_FORMAT)
    , trayIcon(QIcon(":/resources/KanmusuMemory32.png"))
{
    ui.setupUi(q);
    ui.webView->page()->networkAccessManager()->setCookieJar(new CookieJar(q));
    QNetworkDiskCache *cache = new QNetworkDiskCache(q);
    cache->setCacheDirectory(QStandardPaths::writableLocation(QStandardPaths::CacheLocation));
    cache->setMaximumCacheSize(1073741824); //about 1024MB
    ui.webView->page()->networkAccessManager()->setCache(cache);

    //通知タイマーのダイアログ作成
    m_timerDialog = new TimerDialog(q, &trayIcon, &settings);

    //メニュー
    connect(ui.capture, &QAction::triggered, [this](){ captureGame(); });
    connect(ui.actionCaptureAndEdit, &QAction::triggered, [this]() { captureGame(true); });
#ifndef DISABLE_CATALOG_AND_DETAIL_FLEET
    connect(ui.captureCatalog, &QAction::triggered, [this](){ captureCatalog(); });
    connect(ui.captureFleetDetail, &QAction::triggered, [this](){ captureFleetDetail(); });
#endif
    connect(ui.reload, &QAction::triggered, ui.webView, &QWebView::reload);
    connect(ui.exit, &QAction::triggered, q, &MainWindow::close);
    connect(ui.actionReturn_to_Kan_Colle, &QAction::triggered, [this]() {
        //艦これ読込み
        ui.webView->load(QUrl(URL_KANCOLLE));
    });
    connect(ui.actionClearAccessCache, &QAction::triggered, [this]() {
        //キャッシュをクリア
        ui.webView->page()->networkAccessManager()->cache()->clear();
    });
    //画像リスト
    connect(ui.viewMemory, &QAction::triggered, [this]() {
        checkSavePath();
        MemoryDialog dlg(settings.value(QStringLiteral("path")).toString(), q);
        dlg.exec();
        if(QFile::exists(dlg.imagePath())){
            switch(dlg.nextOperation()){
            case MemoryDialog::Tweet:
                //つぶやく
                openTweetDialog(dlg.imagePath());
                break;
            case MemoryDialog::Edit:
            {
                //編集
                QString format;
                if(settings.value(SETTING_GENERAL_SAVE_PNG, false).toBool())
                    format = QStringLiteral("png");
                else
                    format = QStringLiteral("jpg");
                QString path = makeFileName(format);
                QString editPath = makeFileName(format);
                openImageEditDialog(path ,dlg.imagePath(), editPath);
                break;
            }
            default:
                break;
            }
        }
    });
    //通知タイマー
    connect(ui.notificationTimer, &QAction::triggered, [this]() {
        m_timerDialog->show();
    });

    //設定ダイアログ表示
    connect(ui.preferences, &QAction::triggered, [this]() {
        SettingsDialog dlg(q);
        dlg.setSavePath(settings.value(QStringLiteral("path")).toString());
        dlg.setUnusedTwitter(settings.value(SETTING_GENERAL_UNUSED_TWITTER, false).toBool());
        dlg.setSavePng(settings.value(SETTING_GENERAL_SAVE_PNG, false).toBool());
        dlg.setMaskAdmiralName(settings.value(SETTING_GENERAL_MASK_ADMIRAL_NAME, false).toBool());
        dlg.setMaskHqLevel(settings.value(SETTING_GENERAL_MASK_HQ_LEVEL, false).toBool());
        if (dlg.exec()) {
            //設定更新
            settings.setValue(QStringLiteral("path"), dlg.savePath());
            settings.setValue(SETTING_GENERAL_UNUSED_TWITTER, dlg.unusedTwitter());
            settings.setValue(SETTING_GENERAL_SAVE_PNG, dlg.savePng());
            settings.setValue(SETTING_GENERAL_MASK_ADMIRAL_NAME, dlg.isMaskAdmiralName());
            settings.setValue(SETTING_GENERAL_MASK_HQ_LEVEL, dlg.isMaskHqLevel());
        }
    });

    //アバウト
    connect(ui.about, &QAction::triggered, [this]() {
        AboutDialog dlg(q);
        dlg.setVersion(KANMEMO_VERSION);
        dlg.setDevelopers(KANMEMO_DEVELOPERS);
        dlg.exec();
    });

    //フルスクリーン
    q->addAction(ui.actionFullScreen);
    connect(ui.actionFullScreen, &QAction::triggered, [this]() {
        if(q->isFullScreen()){
            //フルスクリーン解除
            q->setWindowState(q->windowState() ^ Qt::WindowFullScreen);
        }else if(ui.webView->gameExists()){
            //フルスクリーンじゃなくてゲームがある
            q->setWindowState(q->windowState() ^ Qt::WindowFullScreen);
        }else{
            //フルスクリーンでゲームがないときは何もしない
        }
    });

    //WebViewの読込み開始
    connect(ui.webView, &QWebView::loadStarted, [this](){
       ui.progressBar->show();
    });
    //WebViewの読込み完了
    connect(ui.webView, &QWebView::loadFinished, [this](bool ok) {
        if (ok) {
            ui.statusBar->showMessage(MainWindow::tr("complete"), STATUS_BAR_MSG_TIME);
//            if(ui.webView->url().toString().compare(URL_KANCOLLE) == 0){
//                setFullScreen();
//            }
        } else {
            ui.statusBar->showMessage(MainWindow::tr("error"), STATUS_BAR_MSG_TIME);
        }
        ui.progressBar->hide();
    });
    //WebViewの読込み状態
    connect(ui.webView, &QWebView::loadProgress, ui.progressBar, &QProgressBar::setValue);

    //通知アイコン
#ifdef Q_OS_WIN
    trayIcon.show();
#endif

#ifdef DISABLE_CATALOG_AND_DETAIL_FLEET
    ui.captureCatalog->setVisible(false);
    ui.captureFleetDetail->setVisible(false);
#endif
}