int Option::init(int argc, char **argv) { Option::application_argv0 = 0; Option::cpp_moc_mod = ""; Option::h_moc_mod = "moc_"; Option::lex_mod = "_lex"; Option::yacc_mod = "_yacc"; Option::prl_ext = ".prl"; Option::libtool_ext = ".la"; Option::pkgcfg_ext = ".pc"; Option::prf_ext = ".prf"; Option::js_ext = ".js"; Option::ui_ext = ".ui"; Option::h_ext << ".h" << ".hpp" << ".hh" << ".hxx"; Option::c_ext << ".c"; #ifndef Q_OS_WIN Option::h_ext << ".H"; #endif Option::cpp_moc_ext = ".moc"; Option::h_moc_ext = ".cpp"; Option::cpp_ext << ".cpp" << ".cc" << ".cxx"; #ifndef Q_OS_WIN Option::cpp_ext << ".C"; #endif Option::lex_ext = ".l"; Option::yacc_ext = ".y"; Option::pro_ext = ".pro"; #ifdef Q_OS_WIN Option::dirlist_sep = ";"; Option::shellPath = detectShellPath(); #else Option::dirlist_sep = ":"; #endif Option::sysenv_mod = "QMAKE_ENV_"; Option::field_sep = ' '; if(argc && argv) { Option::application_argv0 = argv[0]; QString argv0 = argv[0]; if(Option::qmake_mode == Option::QMAKE_GENERATE_NOTHING) Option::qmake_mode = default_mode(argv0); if(!argv0.isEmpty() && !QFileInfo(argv0).isRelative()) { Option::qmake_abslocation = argv0; } else if (argv0.contains(QLatin1Char('/')) #ifdef Q_OS_WIN || argv0.contains(QLatin1Char('\\')) #endif ) { //relative PWD Option::qmake_abslocation = QDir::current().absoluteFilePath(argv0); } else { //in the PATH QByteArray pEnv = qgetenv("PATH"); QDir currentDir = QDir::current(); #ifdef Q_OS_WIN QStringList paths = QString::fromLocal8Bit(pEnv).split(QLatin1String(";")); #else QStringList paths = QString::fromLocal8Bit(pEnv).split(QLatin1String(":")); #endif for (QStringList::const_iterator p = paths.constBegin(); p != paths.constEnd(); ++p) { if ((*p).isEmpty()) continue; QString candidate = currentDir.absoluteFilePath(*p + QLatin1Char('/') + argv0); #ifdef Q_OS_WIN candidate += ".exe"; #endif if (QFile::exists(candidate)) { Option::qmake_abslocation = candidate; break; } } } if(!Option::qmake_abslocation.isNull()) Option::qmake_abslocation = QDir::cleanPath(Option::qmake_abslocation); } else { Option::qmake_mode = Option::QMAKE_GENERATE_MAKEFILE; } const QByteArray envflags = qgetenv("QMAKEFLAGS"); if (!envflags.isNull()) { int env_argc = 0, env_size = 0, currlen=0; char quote = 0, **env_argv = NULL; for (int i = 0; i < envflags.size(); ++i) { if (!quote && (envflags.at(i) == '\'' || envflags.at(i) == '"')) { quote = envflags.at(i); } else if (envflags.at(i) == quote) { quote = 0; } else if (!quote && envflags.at(i) == ' ') { if (currlen && env_argv && env_argv[env_argc]) { env_argv[env_argc][currlen] = '\0'; currlen = 0; env_argc++; } } else { if(!env_argv || env_argc > env_size) { env_argv = (char **)realloc(env_argv, sizeof(char *)*(env_size+=10)); for(int i2 = env_argc; i2 < env_size; i2++) env_argv[i2] = NULL; } if(!env_argv[env_argc]) { currlen = 0; env_argv[env_argc] = (char*)malloc(255); } if(currlen < 255) env_argv[env_argc][currlen++] = envflags.at(i); } } if(env_argv) { if(env_argv[env_argc]) { env_argv[env_argc][currlen] = '\0'; currlen = 0; env_argc++; } parseCommandLine(env_argc, env_argv); for(int i2 = 0; i2 < env_size; i2++) { if(env_argv[i2]) free(env_argv[i2]); } free(env_argv); } } if(argc && argv) { int ret = parseCommandLine(argc, argv, 1); if(ret != Option::QMAKE_CMDLINE_SUCCESS) { if ((ret & Option::QMAKE_CMDLINE_SHOW_USAGE) != 0) usage(argv[0]); return ret; //return ret == QMAKE_CMDLINE_SHOW_USAGE ? usage(argv[0]) : false; } } //last chance for defaults if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE || Option::qmake_mode == Option::QMAKE_GENERATE_PRL) { if(Option::mkfile::qmakespec.isNull() || Option::mkfile::qmakespec.isEmpty()) Option::mkfile::qmakespec = QString::fromLocal8Bit(qgetenv("QMAKESPEC").constData()); //try REALLY hard to do it for them, lazy.. if(Option::mkfile::project_files.isEmpty()) { QString pwd = qmake_getpwd(), proj = pwd + "/" + pwd.right(pwd.length() - (pwd.lastIndexOf('/') + 1)) + Option::pro_ext; if(QFile::exists(proj)) { Option::mkfile::project_files.append(proj); } else { //last try.. QStringList profiles = QDir(pwd).entryList(QStringList("*" + Option::pro_ext)); if(profiles.count() == 1) Option::mkfile::project_files.append(pwd + "/" + profiles[0]); } #ifndef QT_BUILD_QMAKE_LIBRARY if(Option::mkfile::project_files.isEmpty()) { usage(argv[0]); return Option::QMAKE_CMDLINE_ERROR; } #endif } } //defaults for globals if(Option::target_mode == Option::TARG_WIN_MODE) { Option::dir_sep = "\\"; Option::obj_ext = ".obj"; Option::res_ext = ".res"; } else { if(Option::target_mode == Option::TARG_MAC9_MODE) Option::dir_sep = ":"; else Option::dir_sep = "/"; Option::obj_ext = ".o"; } Option::qmake_abslocation = Option::fixPathToTargetOS(Option::qmake_abslocation); return QMAKE_CMDLINE_SUCCESS; }
static QEglContext *createContext(QPaintDevice *device) { QEglContext *context; // Create the context object and open the display. context = new QEglContext(); context->setApi(QEgl::OpenVG); // Set the swap interval for the display. QByteArray interval = qgetenv("QT_VG_SWAP_INTERVAL"); if (!interval.isEmpty()) eglSwapInterval(QEgl::display(), interval.toInt()); else eglSwapInterval(QEgl::display(), 1); #ifdef EGL_RENDERABLE_TYPE // Has the user specified an explicit EGL configuration to use? QByteArray configId = qgetenv("QT_VG_EGL_CONFIG"); if (!configId.isEmpty()) { EGLint cfgId = configId.toInt(); EGLint properties[] = { EGL_CONFIG_ID, cfgId, EGL_NONE }; EGLint matching = 0; EGLConfig cfg; if (eglChooseConfig (QEgl::display(), properties, &cfg, 1, &matching) && matching > 0) { // Check that the selected configuration actually supports OpenVG // and then create the context with it. EGLint id = 0; EGLint type = 0; eglGetConfigAttrib (QEgl::display(), cfg, EGL_CONFIG_ID, &id); eglGetConfigAttrib (QEgl::display(), cfg, EGL_RENDERABLE_TYPE, &type); if (cfgId == id && (type & EGL_OPENVG_BIT) != 0) { context->setConfig(cfg); if (!context->createContext()) { delete context; return 0; } return context; } else { qWarning("QT_VG_EGL_CONFIG: %d is not a valid OpenVG configuration", int(cfgId)); } } } #endif // Choose an appropriate configuration for rendering into the device. QEglProperties configProps; configProps.setPaintDeviceFormat(device); int redSize = configProps.value(EGL_RED_SIZE); if (redSize == EGL_DONT_CARE || redSize == 0) configProps.setPixelFormat(QImage::Format_ARGB32); // XXX configProps.setValue(EGL_ALPHA_MASK_SIZE, 1); #ifdef EGL_VG_ALPHA_FORMAT_PRE_BIT configProps.setValue(EGL_SURFACE_TYPE, EGL_WINDOW_BIT | EGL_VG_ALPHA_FORMAT_PRE_BIT); configProps.setRenderableType(QEgl::OpenVG); if (!context->chooseConfig(configProps)) { // Try again without the "pre" bit. configProps.setValue(EGL_SURFACE_TYPE, EGL_WINDOW_BIT); if (!context->chooseConfig(configProps)) { delete context; return 0; } } #else configProps.setValue(EGL_SURFACE_TYPE, EGL_WINDOW_BIT); configProps.setRenderableType(QEgl::OpenVG); if (!context->chooseConfig(configProps)) { delete context; return 0; } #endif // Construct a new EGL context for the selected configuration. if (!context->createContext()) { delete context; return 0; } return context; }
void QRasterWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint &offset) { Q_D(QRasterWindowSurface); // Not ready for painting yet, bail out. This can happen in // QWidget::create_sys() if (!d->image || rgn.rectCount() == 0) return; #ifdef Q_WS_WIN QRect br = rgn.boundingRect(); #ifndef Q_WS_WINCE if (!qt_widget_private(window())->isOpaque && window()->testAttribute(Qt::WA_TranslucentBackground) && (qt_widget_private(window())->data.window_flags & Qt::FramelessWindowHint)) { QRect r = window()->frameGeometry(); QPoint frameOffset = qt_widget_private(window())->frameStrut().topLeft(); QRect dirtyRect = br.translated(offset + frameOffset); SIZE size = {r.width(), r.height()}; POINT ptDst = {r.x(), r.y()}; POINT ptSrc = {0, 0}; BLENDFUNCTION blend = {AC_SRC_OVER, 0, (int)(255.0 * window()->windowOpacity()), Q_AC_SRC_ALPHA}; RECT dirty = {dirtyRect.x(), dirtyRect.y(), dirtyRect.x() + dirtyRect.width(), dirtyRect.y() + dirtyRect.height()}; Q_UPDATELAYEREDWINDOWINFO info = {sizeof(info), NULL, &ptDst, &size, d->image->hdc, &ptSrc, 0, &blend, Q_ULW_ALPHA, &dirty}; ptrUpdateLayeredWindowIndirect(window()->internalWinId(), &info); } else #endif { QPoint wOffset = qt_qwidget_data(widget)->wrect.topLeft(); HDC widget_dc = widget->getDC(); QRect wbr = br.translated(-wOffset); BitBlt(widget_dc, wbr.x(), wbr.y(), wbr.width(), wbr.height(), d->image->hdc, br.x() + offset.x(), br.y() + offset.y(), SRCCOPY); widget->releaseDC(widget_dc); } #ifndef QT_NO_DEBUG static bool flush = !qgetenv("QT_FLUSH_WINDOWSURFACE").isEmpty(); if (flush) { SelectObject(qt_win_display_dc(), GetStockObject(BLACK_BRUSH)); Rectangle(qt_win_display_dc(), 0, 0, d->image->width() + 2, d->image->height() + 2); BitBlt(qt_win_display_dc(), 1, 1, d->image->width(), d->image->height(), d->image->hdc, 0, 0, SRCCOPY); } #endif #endif #ifdef Q_WS_X11 extern void *qt_getClipRects(const QRegion &r, int &num); // in qpaintengine_x11.cpp extern QWidgetData* qt_widget_data(QWidget *); QPoint wOffset = qt_qwidget_data(widget)->wrect.topLeft(); if (widget->window() != window()) { XFreeGC(X11->display, d_ptr->gc); d_ptr->gc = XCreateGC(X11->display, widget->handle(), 0, 0); } QRegion wrgn(rgn); if (!wOffset.isNull()) wrgn.translate(-wOffset); QRect wbr = wrgn.boundingRect(); if (wrgn.rectCount() != 1) { int num; XRectangle *rects = (XRectangle *)qt_getClipRects(wrgn, num); XSetClipRectangles(X11->display, d_ptr->gc, 0, 0, rects, num, YXBanded); } QRect br = rgn.boundingRect().translated(offset); #ifndef QT_NO_MITSHM if (d_ptr->image->xshmpm) { XCopyArea(X11->display, d_ptr->image->xshmpm, widget->handle(), d_ptr->gc, br.x(), br.y(), br.width(), br.height(), wbr.x(), wbr.y()); XSync(X11->display, False); } else if (d_ptr->image->xshmimg) { const QImage &src = d->image->image; br = br.intersected(src.rect()); XShmPutImage(X11->display, widget->handle(), d_ptr->gc, d_ptr->image->xshmimg, br.x(), br.y(), wbr.x(), wbr.y(), br.width(), br.height(), False); XSync(X11->display, False); } else #endif { const QImage &src = d->image->image; br = br.intersected(src.rect()); if (src.format() != QImage::Format_RGB32 || widget->x11Info().depth() < 24) { Q_ASSERT(src.depth() >= 16); const QImage sub_src(src.scanLine(br.y()) + br.x() * (uint(src.depth()) / 8), br.width(), br.height(), src.bytesPerLine(), src.format()); QX11PixmapData *data = new QX11PixmapData(QPixmapData::PixmapType); data->xinfo = widget->x11Info(); data->fromImage(sub_src, Qt::NoOpaqueDetection); QPixmap pm = QPixmap(data); XCopyArea(X11->display, pm.handle(), widget->handle(), d_ptr->gc, 0 , 0 , br.width(), br.height(), wbr.x(), wbr.y()); } else { // qpaintengine_x11.cpp extern void qt_x11_drawImage(const QRect &rect, const QPoint &pos, const QImage &image, Drawable hd, GC gc, Display *dpy, Visual *visual, int depth); qt_x11_drawImage(br, wbr.topLeft(), src, widget->handle(), d_ptr->gc, X11->display, (Visual *)widget->x11Info().visual(), widget->x11Info().depth()); } } if (wrgn.rectCount() != 1) XSetClipMask(X11->display, d_ptr->gc, XNone); #endif // FALCON #ifdef Q_WS_MAC // qDebug() << "Flushing" << widget << rgn << offset; // d->image->image.save("flush.png"); Q_UNUSED(offset); // Get a context for the widget. #ifndef QT_MAC_USE_COCOA CGContextRef context; CGrafPtr port = GetWindowPort(qt_mac_window_for(widget)); QDBeginCGContext(port, &context); #else extern CGContextRef qt_mac_graphicsContextFor(QWidget *); CGContextRef context = qt_mac_graphicsContextFor(widget); #endif CGContextSaveGState(context); // Flip context. CGContextTranslateCTM(context, 0, widget->height()); CGContextScaleCTM(context, 1, -1); // Clip to region. const QVector<QRect> &rects = rgn.rects(); for (int i = 0; i < rects.size(); ++i) { const QRect &rect = rects.at(i); CGContextAddRect(context, CGRectMake(rect.x(), rect.y(), rect.width(), rect.height())); } CGContextClip(context); QRect r = rgn.boundingRect(); const CGRect area = CGRectMake(r.x(), r.y(), r.width(), r.height()); CGImageRef image = CGBitmapContextCreateImage(d->image->cg); CGImageRef subImage = CGImageCreateWithImageInRect(image, area); qt_mac_drawCGImage(context, &area, subImage); CGImageRelease(subImage); CGImageRelease(image); // CGSize size = { d->image->image.width(), d->image->image.height() }; // CGLayerRef layer = CGLayerCreateWithContext(d->image->cg, size, 0); // CGPoint pt = { 0, 0 }; // CGContextDrawLayerAtPoint(context, pt, layer); // CGLayerRelease(layer); // Restore context. CGContextRestoreGState(context); #ifndef QT_MAC_USE_COCOA QDEndCGContext(port, &context); #endif #endif // Q_WS_MAC #ifdef Q_OS_SYMBIAN Q_UNUSED(widget); Q_UNUSED(rgn); Q_UNUSED(offset); #endif }
QQnxRootWindow::QQnxRootWindow(const QQnxScreen *screen) : m_screen(screen), m_window(0), m_windowGroupName(), m_translucent(false) { qRootWindowDebug() << Q_FUNC_INFO; // Create one top-level QNX window to act as a container for child windows // since navigator only supports one application window errno = 0; int result = screen_create_window(&m_window, m_screen->nativeContext()); int val[2]; if (result != 0) qFatal("QQnxRootWindow: failed to create window, errno=%d", errno); // Move window to proper display errno = 0; screen_display_t display = m_screen->nativeDisplay(); result = screen_set_window_property_pv(m_window, SCREEN_PROPERTY_DISPLAY, (void **)&display); if (result != 0) qFatal("QQnxRootWindow: failed to set window display, errno=%d", errno); // Make sure window is above navigator but below keyboard if running as root // since navigator won't automatically set our z-order in this case if (getuid() == 0) { errno = 0; val[0] = MAGIC_ZORDER_FOR_NO_NAV; result = screen_set_window_property_iv(m_window, SCREEN_PROPERTY_ZORDER, val); if (result != 0) qFatal("QQnxRootWindow: failed to set window z-order, errno=%d", errno); } // Window won't be visible unless it has some buffers so make one dummy buffer that is 1x1 errno = 0; val[0] = SCREEN_USAGE_NATIVE; result = screen_set_window_property_iv(m_window, SCREEN_PROPERTY_USAGE, val); if (result != 0) qFatal("QQnxRootWindow: failed to set window buffer usage, errno=%d", errno); errno = 0; val[0] = m_screen->nativeFormat(); result = screen_set_window_property_iv(m_window, SCREEN_PROPERTY_FORMAT, val); if (result != 0) qFatal("QQnxRootWindow: failed to set window pixel format, errno=%d", errno); errno = 0; val[0] = 1; val[1] = 1; result = screen_set_window_property_iv(m_window, SCREEN_PROPERTY_BUFFER_SIZE, val); if (result != 0) qFatal("QQnxRootWindow: failed to set window buffer size, errno=%d", errno); errno = 0; result = screen_create_window_buffers(m_window, 1); if (result != 0) qFatal("QQNX: failed to create window buffer, errno=%d", errno); // Window is always the size of the display errno = 0; QRect geometry = m_screen->geometry(); val[0] = geometry.width(); val[1] = geometry.height(); result = screen_set_window_property_iv(m_window, SCREEN_PROPERTY_SIZE, val); if (result != 0) qFatal("QQnxRootWindow: failed to set window size, errno=%d", errno); // Fill the window with solid black. Note that the LSB of the pixel value // 0x00000000 just happens to be 0x00, so if and when this root window's // alpha blending mode is changed from None to Source-Over, it will then // be interpreted as transparent. errno = 0; val[0] = 0; result = screen_set_window_property_iv(m_window, SCREEN_PROPERTY_COLOR, val); if (result != 0) qFatal("QQnxRootWindow: failed to set window colour, errno=%d", errno); // Make the window opaque errno = 0; val[0] = SCREEN_TRANSPARENCY_NONE; result = screen_set_window_property_iv(m_window, SCREEN_PROPERTY_TRANSPARENCY, val); if (result != 0) qFatal("QQnxRootWindow: failed to set window transparency, errno=%d", errno); // Set the swap interval to 1 errno = 0; val[0] = 1; result = screen_set_window_property_iv(m_window, SCREEN_PROPERTY_SWAP_INTERVAL, val); if (result != 0) qFatal("QQnxRootWindow: failed to set window swap interval, errno=%d", errno); // Set viewport size equal to window size but move outside buffer so the fill colour is used exclusively errno = 0; val[0] = geometry.width(); val[1] = geometry.height(); result = screen_set_window_property_iv(m_window, SCREEN_PROPERTY_SOURCE_SIZE, val); if (result != 0) qFatal("QQnxRootWindow: failed to set window source size, errno=%d", errno); errno = 0; val[0] = 0; val[1] = 0; result = screen_set_window_property_iv(m_window, SCREEN_PROPERTY_SOURCE_POSITION, val); if (result != 0) qFatal("QQnxRootWindow: failed to set window source position, errno=%d", errno); // Optionally disable the screen power save bool ok = false; const int disablePowerSave = qgetenv("QQNX_DISABLE_POWER_SAVE").toInt(&ok); if (ok && disablePowerSave) { const int mode = SCREEN_IDLE_MODE_KEEP_AWAKE; result = screen_set_window_property_iv(m_window, SCREEN_PROPERTY_IDLE_MODE, &mode); if (result != 0) qWarning("QQnxRootWindow: failed to disable power saving mode"); } createWindowGroup(); // Don't post yet. This will be lazily done from QQnxScreen upon first posting of // a child window. Doing it now pre-emptively would create a flicker if one of // the QWindow's about to be created sets its Qt::WA_TranslucentBackground flag // and immediately triggers the buffer re-creation in makeTranslucent(). }
bool Options::showDisassembly() { static bool showCode = !qgetenv("QV4_SHOW_ASM").isNull(); return showCode; }
static QString cartaGetEnv( const QString & name) { std::string fullName = ("CARTAVIS_" + name).toStdString(); return qgetenv( fullName.c_str()); }
Vector<String> PluginDatabase::defaultPluginDirectories() { Vector<String> paths; // Add paths specific to each platform #if defined(XP_UNIX) String userPluginPath = homeDirectoryPath(); userPluginPath.append(String("/.mozilla/plugins")); paths.append(userPluginPath); userPluginPath = homeDirectoryPath(); userPluginPath.append(String("/.netscape/plugins")); paths.append(userPluginPath); paths.append("/usr/lib/browser/plugins"); paths.append("/usr/local/lib/mozilla/plugins"); paths.append("/usr/lib/firefox/plugins"); paths.append("/usr/lib64/browser-plugins"); paths.append("/usr/lib/browser-plugins"); paths.append("/usr/lib/mozilla/plugins"); paths.append("/usr/local/netscape/plugins"); paths.append("/opt/mozilla/plugins"); paths.append("/opt/mozilla/lib/plugins"); paths.append("/opt/netscape/plugins"); paths.append("/opt/netscape/communicator/plugins"); paths.append("/usr/lib/netscape/plugins"); paths.append("/usr/lib/netscape/plugins-libc5"); paths.append("/usr/lib/netscape/plugins-libc6"); paths.append("/usr/lib64/netscape/plugins"); paths.append("/usr/lib64/mozilla/plugins"); paths.append("/usr/lib/nsbrowser/plugins"); paths.append("/usr/lib64/nsbrowser/plugins"); String mozHome(getenv("MOZILLA_HOME")); mozHome.append("/plugins"); paths.append(mozHome); Vector<String> mozPaths; String mozPath(getenv("MOZ_PLUGIN_PATH")); mozPath.split(UChar(':'), /* allowEmptyEntries */ false, mozPaths); paths.append(mozPaths); #elif defined(XP_MACOSX) String userPluginPath = homeDirectoryPath(); userPluginPath.append(String("/Library/Internet Plug-Ins")); paths.append(userPluginPath); paths.append("/Library/Internet Plug-Ins"); #elif defined(XP_WIN) String userPluginPath = homeDirectoryPath(); userPluginPath.append(String("\\Application Data\\Mozilla\\plugins")); paths.append(userPluginPath); #endif // Add paths specific to each port #if PLATFORM(QT) Vector<String> qtPaths; String qtPath(qgetenv("QTWEBKIT_PLUGIN_PATH").constData()); qtPath.split(UChar(':'), /* allowEmptyEntries */ false, qtPaths); paths.append(qtPaths); #endif return paths; }
PlayEngine::PlayEngine() : d(new Data(this)) { Q_ASSERT(d->confDir.isValid()); _Debug("Create audio/video plugins"); d->audio = new AudioController(this); d->video = new VideoOutput(this); d->filter = new VideoFilter; d->chapterInfo = new ChapterInfoObject(this, this); d->updateMediaName(); _Debug("Make registrations and connections"); connect(d->video, &VideoOutput::formatChanged, this, &PlayEngine::updateVideoFormat); connect(d->video, &VideoOutput::droppedFramesChanged, this, &PlayEngine::droppedFramesChanged); d->handle = mpv_create(); auto verbose = qgetenv("CMPLAYER_MPV_VERBOSE").toLower().trimmed(); const QVector<QByteArray> lvs = {"no", "fatal", "error", "warn", "info", "status", "v", "debug", "trace"}; if (lvs.indexOf(verbose) < lvs.indexOf("info")) verbose = "info"; mpv_request_log_messages(d->handle, verbose.constData()); d->observe(); connect(this, &PlayEngine::beginChanged, this, &PlayEngine::endChanged); connect(this, &PlayEngine::durationChanged, this, &PlayEngine::endChanged); connect(this, &PlayEngine::videoStreamsChanged, this, [=] () { if (_Change(d->hasVideo, !d->streams[StreamVideo].tracks.isEmpty())) emit hasVideoChanged(); d->videoInfo.setTracks(d->streams[StreamVideo].tracks); }); connect(this, &PlayEngine::audioStreamsChanged, this, [=] () { d->audioInfo.setTracks(d->streams[StreamAudio].tracks); }); connect(this, &PlayEngine::subtitleStreamsChanged, this, [=] () { d->subInfo.setTracks(d->streams[StreamSubtitle].tracks); }); connect(this, &PlayEngine::currentVideoStreamChanged, this, [=] (int id) { d->videoInfo.setTrack(d->streams[StreamVideo].tracks.value(id)); }); connect(this, &PlayEngine::currentAudioStreamChanged, this, [=] (int id) { d->audioInfo.setTrack(d->streams[StreamAudio].tracks.value(id)); }); connect(this, &PlayEngine::currentSubtitleStreamChanged, this, [=] () { d->subInfo.setTracks(d->streams[StreamSubtitle].tracks); }); auto checkDeint = [=] () { auto act = Unavailable; if (d->filter->isInputInterlaced()) act = d->filter->isOutputInterlaced() ? Deactivated : Activated; d->videoInfo.setDeinterlacer(act); }; connect(d->filter, &VideoFilter::inputInterlacedChanged, this, checkDeint, Qt::QueuedConnection); connect(d->filter, &VideoFilter::outputInterlacedChanged, this, checkDeint, Qt::QueuedConnection); connect(d->audio, &AudioController::inputFormatChanged, this, [=] () { d->audioInfo.output()->setFormat(d->audio->inputFormat()); }, Qt::QueuedConnection); connect(d->audio, &AudioController::outputFormatChanged, this, [=] () { d->audioInfo.renderer()->setFormat(d->audio->outputFormat()); }, Qt::QueuedConnection); connect(d->audio, &AudioController::samplerateChanged, this, [=] (int sr) { d->audioInfo.renderer()->setSampleRate(sr, true); }, Qt::QueuedConnection); connect(d->audio, &AudioController::gainChanged, &d->audioInfo, &AudioInfoObject::setNormalizer); auto setOption = [this] (const char *name, const char *data) { const auto err = mpv_set_option_string(d->handle, name, data); d->fatal(err, "Couldn't set option %%=%%.", name, data); }; setOption("fs", "no"); setOption("input-cursor", "yes"); setOption("softvol", "yes"); setOption("softvol-max", "1000.0"); setOption("sub-auto", "no"); setOption("osd-level", "0"); setOption("quiet", "yes"); setOption("input-terminal", "no"); setOption("ad-lavc-downmix", "no"); setOption("title", "\"\""); setOption("vo", d->vo().constData()); setOption("fixed-vo", "yes"); auto overrides = qgetenv("CMPLAYER_MPV_OPTIONS").trimmed(); if (!overrides.isEmpty()) { const auto opts = QString::fromLocal8Bit(overrides); const auto args = opts.split(QRegEx(uR"([\s\t]+)"_q), QString::SkipEmptyParts); for (int i=0; i<args.size(); ++i) { if (!args[i].startsWith("--"_a)) { _Error("Cannot parse option %%.", args[i]); continue; } const auto arg = args[i].midRef(2); const int index = arg.indexOf('='_q); if (index < 0) { if (arg.startsWith("no-"_a)) setOption(arg.mid(3).toLatin1(), "no"); else setOption(arg.toLatin1(), "yes"); } else { const auto key = arg.left(index).toLatin1(); const auto value = arg.mid(index+1).toLatin1(); setOption(key, value); } } } d->fatal(mpv_initialize(d->handle), "Couldn't initialize mpv."); _Debug("Initialized"); d->initialized = true; }
void SyncEngine::slotDiscoveryJobFinished(int discoveryResult) { // To clean the progress info emit folderDiscovered(false, QString()); if (discoveryResult < 0 ) { handleSyncError(_csync_ctx, "csync_update"); return; } qDebug() << "<<#### Discovery end #################################################### " << _stopWatch.addLapTime(QLatin1String("Discovery Finished")); // Sanity check if (!_journal->isConnected()) { qDebug() << "Bailing out, DB failure"; emit csyncError(tr("Cannot open the sync journal")); finalize(); return; } else { // Commits a possibly existing (should not though) transaction and starts a new one for the propagate phase _journal->commitIfNeededAndStartNewTransaction("Post discovery"); } if( csync_reconcile(_csync_ctx) < 0 ) { handleSyncError(_csync_ctx, "csync_reconcile"); return; } qDebug() << "<<#### Reconcile end #################################################### " << _stopWatch.addLapTime(QLatin1String("Reconcile Finished")); _hasNoneFiles = false; _hasRemoveFile = false; bool walkOk = true; _seenFiles.clear(); _temporarilyUnavailablePaths.clear(); if( csync_walk_local_tree(_csync_ctx, &treewalkLocal, 0) < 0 ) { qDebug() << "Error in local treewalk."; walkOk = false; } if( walkOk && csync_walk_remote_tree(_csync_ctx, &treewalkRemote, 0) < 0 ) { qDebug() << "Error in remote treewalk."; } if (_csync_ctx->remote.root_perms) { _remotePerms[QLatin1String("")] = _csync_ctx->remote.root_perms; qDebug() << "Permissions of the root folder: " << _remotePerms[QLatin1String("")]; } // Re-init the csync context to free memory csync_commit(_csync_ctx); // The map was used for merging trees, convert it to a list: _syncedItems = _syncItemMap.values().toVector(); _syncItemMap.clear(); // free memory // Adjust the paths for the renames. for (SyncFileItemVector::iterator it = _syncedItems.begin(); it != _syncedItems.end(); ++it) { (*it)->_file = adjustRenamedPath((*it)->_file); } // Sort items per destination std::sort(_syncedItems.begin(), _syncedItems.end()); // make sure everything is allowed checkForPermission(); // To announce the beginning of the sync emit aboutToPropagate(_syncedItems); // it's important to do this before ProgressInfo::start(), to announce start of new sync emit transmissionProgress(*_progressInfo); _progressInfo->start(); if (!_hasNoneFiles && _hasRemoveFile) { qDebug() << Q_FUNC_INFO << "All the files are going to be changed, asking the user"; bool cancel = false; emit aboutToRemoveAllFiles(_syncedItems.first()->_direction, &cancel); if (cancel) { qDebug() << Q_FUNC_INFO << "Abort sync"; finalize(); return; } } // FIXME: The propagator could create his session in propagator_legacy.cpp // There's no reason to keep csync_owncloud.c around ne_session_s *session = 0; // that call to set property actually is a get which will return the session csync_set_module_property(_csync_ctx, "get_dav_session", &session); // post update phase script: allow to tweak stuff by a custom script in debug mode. if( !qgetenv("OWNCLOUD_POST_UPDATE_SCRIPT").isEmpty() ) { #ifndef NDEBUG QString script = qgetenv("OWNCLOUD_POST_UPDATE_SCRIPT"); qDebug() << "OOO => Post Update Script: " << script; QProcess::execute(script.toUtf8()); #else qWarning() << "**** Attention: POST_UPDATE_SCRIPT installed, but not executed because compiled with NDEBUG"; #endif } // do a database commit _journal->commit("post treewalk"); _propagator = QSharedPointer<OwncloudPropagator>( new OwncloudPropagator (_account, session, _localPath, _remoteUrl, _remotePath, _journal, &_thread)); connect(_propagator.data(), SIGNAL(completed(const SyncFileItem &)), this, SLOT(slotJobCompleted(const SyncFileItem &))); connect(_propagator.data(), SIGNAL(progress(const SyncFileItem &,quint64)), this, SLOT(slotProgress(const SyncFileItem &,quint64))); connect(_propagator.data(), SIGNAL(adjustTotalTransmissionSize(qint64)), this, SLOT(slotAdjustTotalTransmissionSize(qint64))); connect(_propagator.data(), SIGNAL(finished()), this, SLOT(slotFinished()), Qt::QueuedConnection); // apply the network limits to the propagator setNetworkLimits(_uploadLimit, _downloadLimit); deleteStaleDownloadInfos(); deleteStaleUploadInfos(); deleteStaleErrorBlacklistEntries(); _journal->commit("post stale entry removal"); // Emit the started signal only after the propagator has been set up. if (_needsUpdate) emit(started()); _propagator->start(_syncedItems); qDebug() << "<<#### Post-Reconcile end #################################################### " << _stopWatch.addLapTime(QLatin1String("Post-Reconcile Finished")); }
void PropagateUploadFileQNAM::startNextChunk() { if (_propagator->_abortRequested.fetchAndAddRelaxed(0)) return; if (! _jobs.isEmpty() && _currentChunk + _startChunk >= _chunkCount - 1) { // Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that // https://github.com/owncloud/core/issues/11106 // We return now and when the _jobs will be finished we will proceed the last chunk return; } quint64 fileSize = _item._size; QMap<QByteArray, QByteArray> headers; headers["OC-Total-Length"] = QByteArray::number(fileSize); headers["OC-Async"] = "1"; headers["Content-Type"] = "application/octet-stream"; headers["X-OC-Mtime"] = QByteArray::number(qint64(_item._modtime)); if (!_item._etag.isEmpty() && _item._etag != "empty_etag" && _item._instruction != CSYNC_INSTRUCTION_NEW // On new files never send a If-Match ) { // We add quotes because the owncloud server always add quotes around the etag, and // csync_owncloud.c's owncloud_file_id always strip the quotes. headers["If-Match"] = '"' + _item._etag + '"'; } QString path = _item._file; UploadDevice *device = 0; if (_chunkCount > 1) { int sendingChunk = (_currentChunk + _startChunk) % _chunkCount; // XOR with chunk size to make sure everything goes well if chunk size change between runs uint transid = _transferId ^ chunkSize(); path += QString("-chunking-%1-%2-%3").arg(transid).arg(_chunkCount).arg(sendingChunk); headers["OC-Chunked"] = "1"; int currentChunkSize = chunkSize(); if (sendingChunk == _chunkCount - 1) { // last chunk currentChunkSize = (fileSize % chunkSize()); if( currentChunkSize == 0 ) { // if the last chunk pretents to be 0, its actually the full chunk size. currentChunkSize = chunkSize(); } } device = new UploadDevice(_file, chunkSize() * quint64(sendingChunk), currentChunkSize, &_propagator->_bandwidthManager); } else { device = new UploadDevice(_file, 0, fileSize, &_propagator->_bandwidthManager); } bool isOpen = true; if (!device->isOpen()) { isOpen = device->open(QIODevice::ReadOnly); } if( isOpen ) { PUTFileJob* job = new PUTFileJob(AccountManager::instance()->account(), _propagator->_remoteFolder + path, device, headers, _currentChunk); _jobs.append(job); job->setTimeout(_propagator->httpTimeout() * 1000); connect(job, SIGNAL(finishedSignal()), this, SLOT(slotPutFinished())); connect(job, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(slotUploadProgress(qint64,qint64))); connect(job, SIGNAL(uploadProgress(qint64,qint64)), device, SLOT(slotJobUploadProgress(qint64,qint64))); connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*))); job->start(); _propagator->_activeJobs++; _currentChunk++; QByteArray env = qgetenv("OWNCLOUD_PARALLEL_CHUNK"); bool parallelChunkUpload = env=="true" || env =="1";; if (_currentChunk + _startChunk >= _chunkCount - 1) { // Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that // https://github.com/owncloud/core/issues/11106 parallelChunkUpload = false; } if (parallelChunkUpload && (_propagator->_activeJobs < _propagator->maximumActiveJob()) && _currentChunk < _chunkCount ) { startNextChunk(); } if (!parallelChunkUpload || _chunkCount - _currentChunk <= 0) { emitReady(); } } else {
//!--------------------------------------------------------------------------------------------------------- //! //! \brief get_username //! \return //! QString SystemDispatcher::get_username(){ QString name = qgetenv("USER"); if (name.isEmpty()) name = qgetenv("USERNAME"); return name; }
QStringList QStandardPaths::standardLocations(StandardLocation type) { if (type == MusicLocation) { return QStringList() << writableLocation(type) << getExternalFilesDir("DIRECTORY_MUSIC") << getExternalStoragePublicDirectory("DIRECTORY_PODCASTS") << getExternalFilesDir("DIRECTORY_PODCASTS") << getExternalStoragePublicDirectory("DIRECTORY_NOTIFICATIONS") << getExternalFilesDir("DIRECTORY_NOTIFICATIONS") << getExternalStoragePublicDirectory("DIRECTORY_ALARMS") << getExternalFilesDir("DIRECTORY_ALARMS"); } if (type == MoviesLocation) { return QStringList() << writableLocation(type) << getExternalFilesDir("DIRECTORY_MOVIES"); } if (type == PicturesLocation) { return QStringList() << writableLocation(type) << getExternalFilesDir("DIRECTORY_PICTURES"); } if (type == DocumentsLocation) { if (QtAndroidPrivate::androidSdkVersion() > 18) { return QStringList() << writableLocation(type) << getExternalFilesDir("DIRECTORY_DOCUMENTS"); } else { return QStringList() << writableLocation(type) << getExternalFilesDir() + QLatin1String("/Documents"); } } if (type == DownloadLocation) { return QStringList() << writableLocation(type) << getExternalFilesDir("DIRECTORY_DOWNLOADS"); } if (type == AppDataLocation || type == AppLocalDataLocation) { return QStringList() << writableLocation(type) << getExternalFilesDir(); } if (type == CacheLocation) { return QStringList() << writableLocation(type) << getExternalCacheDir(); } if (type == FontsLocation) { QString &fontLocation = (*androidDirCache)[QStringLiteral("FONT_LOCATION")]; if (!fontLocation.isEmpty()) return QStringList(fontLocation); const QByteArray ba = qgetenv("QT_ANDROID_FONT_LOCATION"); if (!ba.isEmpty()) return QStringList((fontLocation = QDir::cleanPath(QString::fromLocal8Bit(ba)))); return QStringList((fontLocation = QLatin1String("/system/fonts"))); } return QStringList(writableLocation(type)); }
bool QVFbScreen::connect(const QString &displaySpec) { QStringList displayArgs = displaySpec.split(QLatin1Char(':')); if (displayArgs.contains(QLatin1String("Gray"))) grayscale = true; key_t key = ftok(QT_VFB_MOUSE_PIPE(displayId).toLocal8Bit(), 'b'); if (key == -1) return false; #if Q_BYTE_ORDER == Q_BIG_ENDIAN #ifndef QT_QWS_FRAMEBUFFER_LITTLE_ENDIAN if (displayArgs.contains(QLatin1String("littleendian"))) #endif QScreen::setFrameBufferLittleEndian(true); #endif int shmId = shmget(key, 0, 0); if (shmId != -1) d_ptr->shmrgn = (unsigned char *)shmat(shmId, 0, 0); else return false; if ((long)d_ptr->shmrgn == -1 || d_ptr->shmrgn == 0) { qDebug("No shmrgn %ld", (long)d_ptr->shmrgn); return false; } d_ptr->hdr = (QVFbHeader *)d_ptr->shmrgn; data = d_ptr->shmrgn + d_ptr->hdr->dataoffset; dw = w = d_ptr->hdr->width; dh = h = d_ptr->hdr->height; d = d_ptr->hdr->depth; switch (d) { case 1: setPixelFormat(QImage::Format_Mono); break; case 8: setPixelFormat(QImage::Format_Indexed8); break; case 12: setPixelFormat(QImage::Format_RGB444); break; case 15: setPixelFormat(QImage::Format_RGB555); break; case 16: setPixelFormat(QImage::Format_RGB16); break; case 18: setPixelFormat(QImage::Format_RGB666); break; case 24: setPixelFormat(QImage::Format_RGB888); break; case 32: setPixelFormat(QImage::Format_ARGB32_Premultiplied); break; } lstep = d_ptr->hdr->linestep; // Handle display physical size spec. int dimIdxW = -1; int dimIdxH = -1; for (int i = 0; i < displayArgs.size(); ++i) { if (displayArgs.at(i).startsWith(QLatin1String("mmWidth"))) { dimIdxW = i; break; } } for (int i = 0; i < displayArgs.size(); ++i) { if (displayArgs.at(i).startsWith(QLatin1String("mmHeight"))) { dimIdxH = i; break; } } if (dimIdxW >= 0) { bool ok; int pos = 7; if (displayArgs.at(dimIdxW).at(pos) == QLatin1Char('=')) ++pos; int pw = displayArgs.at(dimIdxW).mid(pos).toInt(&ok); if (ok) { physWidth = pw; if (dimIdxH < 0) physHeight = dh*physWidth/dw; } } if (dimIdxH >= 0) { bool ok; int pos = 8; if (displayArgs.at(dimIdxH).at(pos) == QLatin1Char('=')) ++pos; int ph = displayArgs.at(dimIdxH).mid(pos).toInt(&ok); if (ok) { physHeight = ph; if (dimIdxW < 0) physWidth = dw*physHeight/dh; } } if (dimIdxW < 0 && dimIdxH < 0) { const int dpi = 72; physWidth = qRound(dw * 25.4 / dpi); physHeight = qRound(dh * 25.4 / dpi); } qDebug("Connected to VFB server %s: %d x %d x %d %dx%dmm (%dx%ddpi)", displaySpec.toLatin1().data(), w, h, d, physWidth, physHeight, qRound(dw*25.4/physWidth), qRound(dh*25.4/physHeight) ); size = lstep * h; mapsize = size; screencols = d_ptr->hdr->numcols; memcpy(screenclut, d_ptr->hdr->clut, sizeof(QRgb) * screencols); connected = this; if (qgetenv("QT_QVFB_BGR").toInt()) pixeltype = BGRPixel; return true; }
void AndroidAssetsFileEngineHandler::prepopulateCache() const { Q_ASSERT(!m_hasTriedPrepopulatingCache); m_hasTriedPrepopulatingCache = true; Q_ASSERT(m_assetsCache.isEmpty()); // Failsafe: Don't read cache files that are larger than 1MB static qint64 maxPrepopulatedCacheSize = qMax(1024LL * 1024LL, qgetenv("QT_ANDROID_MAX_PREPOPULATED_ASSETS_CACHE_SIZE").toLongLong()); const char *fileName = "--Added-by-androiddeployqt--/qt_cache_pregenerated_file_list"; AAsset *asset = AAssetManager_open(m_assetManager, fileName, AASSET_MODE_BUFFER); if (asset) { m_hasPrepopulatedCache = true; AndroidAbstractFileEngine fileEngine(asset, QString::fromLatin1(fileName)); if (fileEngine.open(QIODevice::ReadOnly)) { qint64 size = fileEngine.size(); if (size <= maxPrepopulatedCacheSize) { QByteArray bytes(size, Qt::Uninitialized); qint64 read = fileEngine.read(bytes.data(), size); if (read != size) { qWarning("Failed to read prepopulated cache"); return; } QDataStream stream(&bytes, QIODevice::ReadOnly); stream.setVersion(QDataStream::Qt_5_3); if (stream.status() != QDataStream::Ok) { qWarning("Failed to read prepopulated cache"); return; } while (!stream.atEnd()) { QString directoryName; stream >> directoryName; int fileCount; stream >> fileCount; QVector<QString> fileList; fileList.reserve(fileCount); while (fileCount--) { QString fileName; stream >> fileName; fileList.append(fileName); } QSharedPointer<AndroidAssetDir> *aad = new QSharedPointer<AndroidAssetDir>(new AndroidAssetDir(0)); (*aad)->m_items = fileList; // Cost = 0, because we should always cache everything if there's a prepopulated cache QByteArray key = directoryName != QLatin1String("/") ? QByteArray("assets:/") + directoryName.toUtf8() : QByteArray("assets:"); bool ok = m_assetsCache.insert(key, aad, 0); if (!ok) qWarning("Failed to insert in cache: %s", qPrintable(directoryName)); } } else {
QString QStandardPaths::writableLocation(StandardLocation type) { switch (type) { case HomeLocation: return QDir::homePath(); case TempLocation: return QDir::tempPath(); case CacheLocation: case GenericCacheLocation: { // http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html QString xdgCacheHome = QFile::decodeName(qgetenv("XDG_CACHE_HOME")); if (isTestModeEnabled()) xdgCacheHome = QDir::homePath() + QLatin1String("/.qttest/cache"); if (xdgCacheHome.isEmpty()) xdgCacheHome = QDir::homePath() + QLatin1String("/.cache"); if (type == QStandardPaths::CacheLocation) appendOrganizationAndApp(xdgCacheHome); return xdgCacheHome; } case DataLocation: case GenericDataLocation: { QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME")); if (isTestModeEnabled()) xdgDataHome = QDir::homePath() + QLatin1String("/.qttest/share"); if (xdgDataHome.isEmpty()) xdgDataHome = QDir::homePath() + QLatin1String("/.local/share"); if (type == QStandardPaths::DataLocation) appendOrganizationAndApp(xdgDataHome); return xdgDataHome; } case ConfigLocation: { // http://standards.freedesktop.org/basedir-spec/latest/ QString xdgConfigHome = QFile::decodeName(qgetenv("XDG_CONFIG_HOME")); if (isTestModeEnabled()) xdgConfigHome = QDir::homePath() + QLatin1String("/.qttest/config"); if (xdgConfigHome.isEmpty()) xdgConfigHome = QDir::homePath() + QLatin1String("/.config"); return xdgConfigHome; } case RuntimeLocation: { const uid_t myUid = geteuid(); // http://standards.freedesktop.org/basedir-spec/latest/ QString xdgRuntimeDir = QFile::decodeName(qgetenv("XDG_RUNTIME_DIR")); if (xdgRuntimeDir.isEmpty()) { const QString userName = _resolveUserName(myUid); xdgRuntimeDir = QDir::tempPath() + QLatin1String("/runtime-") + userName; QDir dir(xdgRuntimeDir); if (!dir.exists()) { if (!QDir().mkdir(xdgRuntimeDir)) { qWarning("QStandardPaths: error creating runtime directory %s: %s", qPrintable(xdgRuntimeDir), qPrintable(qt_error_string(errno))); return QString(); } } } // "The directory MUST be owned by the user" QFileInfo fileInfo(xdgRuntimeDir); if (fileInfo.ownerId() != myUid) { qWarning("QStandardPaths: wrong ownership on runtime directory %s, %d instead of %d", qPrintable(xdgRuntimeDir), fileInfo.ownerId(), myUid); return QString(); } // "and he MUST be the only one having read and write access to it. Its Unix access mode MUST be 0700." QFile file(xdgRuntimeDir); const QFile::Permissions wantedPerms = QFile::ReadUser | QFile::WriteUser | QFile::ExeUser; if (file.permissions() != wantedPerms && !file.setPermissions(wantedPerms)) { qWarning("QStandardPaths: wrong permissions on runtime directory %s", qPrintable(xdgRuntimeDir)); return QString(); } return xdgRuntimeDir; } default: break; } // http://www.freedesktop.org/wiki/Software/xdg-user-dirs QString xdgConfigHome = QFile::decodeName(qgetenv("XDG_CONFIG_HOME")); if (xdgConfigHome.isEmpty()) xdgConfigHome = QDir::homePath() + QLatin1String("/.config"); QFile file(xdgConfigHome + QLatin1String("/user-dirs.dirs")); if (!isTestModeEnabled() && file.open(QIODevice::ReadOnly)) { QHash<QString, QString> lines; QTextStream stream(&file); // Only look for lines like: XDG_DESKTOP_DIR="$HOME/Desktop" QRegExp exp(QLatin1String("^XDG_(.*)_DIR=(.*)$")); while (!stream.atEnd()) { const QString &line = stream.readLine(); if (exp.indexIn(line) != -1) { const QStringList lst = exp.capturedTexts(); const QString key = lst.at(1); QString value = lst.at(2); if (value.length() > 2 && value.startsWith(QLatin1Char('\"')) && value.endsWith(QLatin1Char('\"'))) value = value.mid(1, value.length() - 2); // Store the key and value: "DESKTOP", "$HOME/Desktop" lines[key] = value; } } QString key; switch (type) { case DesktopLocation: key = QLatin1String("DESKTOP"); break; case DocumentsLocation: key = QLatin1String("DOCUMENTS"); break; case PicturesLocation: key = QLatin1String("PICTURES"); break; case MusicLocation: key = QLatin1String("MUSIC"); break; case MoviesLocation: key = QLatin1String("VIDEOS"); break; case DownloadLocation: key = QLatin1String("DOWNLOAD"); break; default: break; } if (!key.isEmpty()) { QString value = lines.value(key); if (!value.isEmpty()) { // value can start with $HOME if (value.startsWith(QLatin1String("$HOME"))) value = QDir::homePath() + value.mid(5); return value; } } } QString path; switch (type) { case DesktopLocation: path = QDir::homePath() + QLatin1String("/Desktop"); break; case DocumentsLocation: path = QDir::homePath() + QLatin1String("/Documents"); break; case PicturesLocation: path = QDir::homePath() + QLatin1String("/Pictures"); break; case FontsLocation: path = QDir::homePath() + QLatin1String("/.fonts"); break; case MusicLocation: path = QDir::homePath() + QLatin1String("/Music"); break; case MoviesLocation: path = QDir::homePath() + QLatin1String("/Videos"); break; case DownloadLocation: path = QDir::homePath() + QLatin1String("/Downloads"); break; case ApplicationsLocation: path = writableLocation(GenericDataLocation) + QLatin1String("/applications"); break; default: break; } return path; }
int main(int argc, char *argv[]) { // Assume the xcb platform if the DISPLAY environment variable is defined, // otherwise go for kms if (!qgetenv("DISPLAY").isEmpty()) setenv("QT_QPA_PLATFORM", "xcb", 0); else { setenv("QT_QPA_PLATFORM", "kms", 0); setenv("QT_QPA_GENERIC_PLUGINS", "evdevmouse,evdevkeyboard,evdevtouch", 0); setenv("QT_KMS_TTYKBD", "1", 0); } GreenIsland app(argc, argv); // Print the banner qDebug() << qPrintable(QString("Green Island v%1\n").arg(GREENISLAND_VERSION)) << " http://www.maui-project.org\n" << " Bug reports to: https://github.com/hawaii-desktop/greenisland/issues\n" << qPrintable(QString(" Build: %1-%2") .arg(GREENISLAND_VERSION).arg(GIT_REV)); // Print the current system struct utsname uts; if (uname(&uts) != -1) qDebug() << qPrintable(QString("OS: %1, %2, %3, %4").arg(uts.sysname) .arg(uts.release).arg(uts.version).arg(uts.machine)); else qDebug() << "OS: Unknown"; // Shell plugin (defaults to desktop for the moment) QString pluginName = QStringLiteral("desktop"); // Command line arguments QStringList arguments = QCoreApplication::instance()->arguments(); // Usage instructions if (arguments.contains(QLatin1String("-h")) || arguments.contains(QLatin1String("--help"))) { printf("Usage: greenisland [options]\n"); printf("Arguments are:\n"); printf("\t--fullscreen\t\trun in fullscreen mode\n"); printf("\t--synthesize-touch\tsynthesize touch for unhandled mouse events\n"); printf("\t--plugin NAME\t\tuse the NAME shell plugin (default 'desktop')\n"); return 0; } // Check whether XDG_RUNTIME_DIR is ok or not verifyXdgRuntimeDir(); // Synthesize touch for unhandled mouse events if (arguments.contains(QLatin1String("--synthesize-touch"))) app.setAttribute(Qt::AA_SynthesizeTouchForUnhandledMouseEvents, true); // Compositor plugin argument int pluginArg = arguments.indexOf(QLatin1String("--plugin")); if (pluginArg != -1 && pluginArg + 1 < arguments.size()) pluginName = arguments.at(pluginArg + 1).toLocal8Bit(); // Load the compositor plugin VCompositor *compositor = app.loadCompositor(pluginName); if (!compositor) qFatal("Unable to run the compositor because the '%s' plugin was not found", pluginName.toLocal8Bit().constData()); // Ensure the compositor renders into a window if (!compositor->window()) qFatal("The compositor '%s' doesn't render into a window", pluginName.toLocal8Bit().constData()); // Set window title compositor->window()->setTitle(QLatin1String("Green Island")); // Run the shell compositor->runShell(); // Show the compositor if (arguments.contains(QLatin1String("--fullscreen"))) { compositor->window()->setGeometry(QGuiApplication::primaryScreen()->geometry()); compositor->window()->showFullScreen(); } else { compositor->window()->setGeometry(QGuiApplication::primaryScreen()->availableGeometry()); compositor->window()->showMaximized(); } return app.exec(); }
void PropagateUploadFile::startNextChunk() { if (_propagator->_abortRequested.fetchAndAddRelaxed(0)) return; if (! _jobs.isEmpty() && _currentChunk + _startChunk >= _chunkCount - 1) { // Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that // https://github.com/owncloud/core/issues/11106 // We return now and when the _jobs are finished we will proceed with the last chunk // NOTE: Some other parts of the code such as slotUploadProgress also assume that the last chunk // is sent last. return; } quint64 fileSize = _item->_size; QMap<QByteArray, QByteArray> headers; headers["OC-Total-Length"] = QByteArray::number(fileSize); headers["OC-Async"] = "1"; headers["OC-Chunk-Size"]= QByteArray::number(quint64(chunkSize())); headers["Content-Type"] = "application/octet-stream"; headers["X-OC-Mtime"] = QByteArray::number(qint64(_item->_modtime)); if(_item->_file.contains(".sys.admin#recall#")) { // This is a file recall triggered by the admin. Note: the // recall list file created by the admin and downloaded by the // client (.sys.admin#recall#) also falls into this category // (albeit users are not supposed to mess up with it) // We use a special tag header so that the server may decide to store this file away in some admin stage area // And not directly in the user's area (which would trigger redownloads etc). headers["OC-Tag"] = ".sys.admin#recall#"; } if (!_item->_etag.isEmpty() && _item->_etag != "empty_etag" && _item->_instruction != CSYNC_INSTRUCTION_NEW // On new files never send a If-Match && _item->_instruction != CSYNC_INSTRUCTION_TYPE_CHANGE && !_deleteExisting ) { // We add quotes because the owncloud server always adds quotes around the etag, and // csync_owncloud.c's owncloud_file_id always strips the quotes. headers["If-Match"] = '"' + _item->_etag + '"'; } QString path = _item->_file; UploadDevice *device = new UploadDevice(&_propagator->_bandwidthManager); qint64 chunkStart = 0; qint64 currentChunkSize = fileSize; bool isFinalChunk = false; if (_chunkCount > 1) { int sendingChunk = (_currentChunk + _startChunk) % _chunkCount; // XOR with chunk size to make sure everything goes well if chunk size changes between runs uint transid = _transferId ^ chunkSize(); qDebug() << "Upload chunk" << sendingChunk << "of" << _chunkCount << "transferid(remote)=" << transid; path += QString("-chunking-%1-%2-%3").arg(transid).arg(_chunkCount).arg(sendingChunk); headers["OC-Chunked"] = "1"; chunkStart = chunkSize() * quint64(sendingChunk); currentChunkSize = chunkSize(); if (sendingChunk == _chunkCount - 1) { // last chunk currentChunkSize = (fileSize % chunkSize()); if( currentChunkSize == 0 ) { // if the last chunk pretends to be 0, its actually the full chunk size. currentChunkSize = chunkSize(); } isFinalChunk = true; } } else { // if there's only one chunk, it's the final one isFinalChunk = true; } if (isFinalChunk && !_transmissionChecksumType.isEmpty()) { headers[checkSumHeaderC] = makeChecksumHeader( _transmissionChecksumType, _transmissionChecksum); } const QString fileName = _propagator->getFilePath(_item->_file); if (! device->prepareAndOpen(fileName, chunkStart, currentChunkSize)) { qDebug() << "ERR: Could not prepare upload device: " << device->errorString(); // If the file is currently locked, we want to retry the sync // when it becomes available again. if (FileSystem::isFileLocked(fileName)) { emit _propagator->seenLockedFile(fileName); } // Soft error because this is likely caused by the user modifying his files while syncing abortWithError( SyncFileItem::SoftError, device->errorString() ); delete device; return; } // job takes ownership of device via a QScopedPointer. Job deletes itself when finishing PUTFileJob* job = new PUTFileJob(_propagator->account(), _propagator->_remoteFolder + path, device, headers, _currentChunk); _jobs.append(job); connect(job, SIGNAL(finishedSignal()), this, SLOT(slotPutFinished())); connect(job, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(slotUploadProgress(qint64,qint64))); connect(job, SIGNAL(uploadProgress(qint64,qint64)), device, SLOT(slotJobUploadProgress(qint64,qint64))); connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*))); job->start(); _propagator->_activeJobList.append(this); _currentChunk++; bool parallelChunkUpload = true; QByteArray env = qgetenv("OWNCLOUD_PARALLEL_CHUNK"); if (!env.isEmpty()) { parallelChunkUpload = env != "false" && env != "0"; } else { int versionNum = _propagator->account()->serverVersionInt(); if (versionNum < 0x080003) { // Disable parallel chunk upload severs older than 8.0.3 to avoid too many // internal sever errors (#2743, #2938) parallelChunkUpload = false; } } if (_currentChunk + _startChunk >= _chunkCount - 1) { // Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that // https://github.com/owncloud/core/issues/11106 parallelChunkUpload = false; } if (parallelChunkUpload && (_propagator->_activeJobList.count() < _propagator->maximumActiveJob()) && _currentChunk < _chunkCount ) { startNextChunk(); } if (!parallelChunkUpload || _chunkCount - _currentChunk <= 0) { emit ready(); } }
void Settings::load() { if(config.allKeys().size()) //if exist - reading settings { notes_path = config.value("NotesPath").toString(); last_note = config.value("LastNote").toString(); hide_start = config.value("HideStart").toBool(); // dialog_geometry = config.value("DialogGeometry").toByteArray(); dialog_state = config.value("DialogState").toByteArray(); // tab_position = TabPosition(config.value("TabPosition").toInt()); show_hidden = config.value("ShowHidden").toBool(); show_extensions = config.value("ShowExtensions").toBool(); // hide_frame = config.value("HideFrame").toBool(); stay_top = config.value("StayTop").toBool(); // single_instance = config.value("SingleInstance").toBool(); copy_start_raise = config.value("CopyStartRaise").toBool(); // note_font.fromString(config.value("NoteFont").toString()); note_links_open = config.value("NoteLinksOpen").toBool(); note_paste_plaintext = config.value("NotePastePlaintext").toBool(); // int ScriptCount = config.value("ComandCount").toInt(); for(int i=0; i<ScriptCount; ++i) { script_model.append( config.value(QString("ComandName%1").arg(i)).toString(), config.value(QString("ComandFile%1").arg(i)).toString(), config.value(QString("ComandIcon%1").arg(i)).toString()); } note_highlight = config.value("NoteHighlight").toBool(); int HighlightRuleCount = config.beginReadArray("HighlightRules"); highlight_rules.resize(HighlightRuleCount); for(int i=0; i<highlight_rules.size(); ++i) { config.setArrayIndex(i); highlight_rules[i].enabled = config.value("enabled").toBool(); highlight_rules[i].regexp = config.value("regexp").toString(); highlight_rules[i].color = QColor(config.value("color").toString()); } config.endArray(); script_show_output = config.value("ScriptShowOutput").toBool(); script_copy_output = config.value("ScriptCopyOutput").toBool(); // language_custom = config.value("LanguageCustom").toBool(); locale_current = QLocale(config.value("LanguageCurrent").toString()); // if(config.contains("Toolbar/itemCount")) { tb_items.resize(config.value("Toolbar/itemCount").toInt()); for(int i=itemAdd; i<itemMax; ++i) { int pos = config.value(ToolbarAction(item_enum(i)).pref_name(), tb_items.size()).toInt(); if(pos<tb_items.size()) tb_items[pos] = i; //Item's position } } } /* * If settings don't exist - setup default settings */ //Setting default path to notes if(notes_path.isEmpty()) { #ifdef Q_WS_X11 notes_path = QDir::homePath()+"/.local/share/notes"; #elif Q_WS_WIN QSettings win_settings("Microsoft", "Windows"); QString mydocuments_path = win_settings->value("CurrentVersion/Explorer/Shell Folders/Personal", "").toString(); if(!mydocuments_path.isEmpty()) notes_path = mydocuments_path+"/Notes"; else if(!QDir::homePath().isEmpty()) notes_path = QDir::homePath()+"/Notes"; #else if(!QDir::homePath().isEmpty()) notes_path = QDir::homePath()+"/Notes"; #endif config.setValue("NotesPath", notes_path); } //Settings single instance options if(!config.contains("SingleInstance")) { single_instance = true; config.setValue("SingleInstance", single_instance); copy_start_raise = true; config.setValue("CopyStartRaise", copy_start_raise); } //Setting default note options if(!config.contains("NoteLinksOpen")) { note_links_open = true; config.setValue("NoteLinksOpen", note_links_open); } if(!config.contains("NotePastePlaintext")) { note_paste_plaintext = false; config.setValue("NotePastePlaintext", note_paste_plaintext); } //Setting default highlight rules if(!config.contains("NoteHighlight")) { if(config.contains("NoteLinksHighlight")) note_highlight = config.value("NoteLinksHighlight").toBool(); else note_highlight = true; config.setValue("NoteHighlight", note_highlight); highlight_rules.append(HighlightRule(true, "(http|https|ftp)://\\S+", QColor(Qt::blue))); highlight_rules.append(HighlightRule(false, "(\\d{1,3}\\.){3,3}\\d{1,3}(\\:\\d+)?", QColor("#500000"))); highlight_rules.append(HighlightRule(false, "(0x|)\\d+", QColor("#147E16"))); highlight_rules.append(HighlightRule(false, "#[0-9a-fA-F]{6,6}", QColor("#CEC51B"))); config.beginWriteArray("HighlightRules", highlight_rules.size()); for(int i=0; i<highlight_rules.size(); ++i) { config.setArrayIndex(i); config.setValue("enabled", highlight_rules.at(i).enabled); config.setValue("regexp", highlight_rules.at(i).regexp); config.setValue("color", highlight_rules.at(i).color); } config.endArray(); } //Setting default scripts if((script_model.rowCount()==0) && !config.contains("ComandCount")) { #ifdef unix script_model.append("Print note's content", "cat", ""); #elif Q_WS_WIN // #endif config.setValue("ComandCount", script_model.rowCount()); for(int i=0; i<script_model.rowCount(); ++i) { config.setValue(QString("ComandName%1").arg(i), script_model.getName(i)); config.setValue(QString("ComandFile%1").arg(i), script_model.getFile(i)); config.setValue(QString("ComandIcon%1").arg(i), script_model.getIcon(i)); } } //Setting default tab position if(!config.contains("TabPosition")) { tab_position = West; config.setValue("TabPosition", tab_position); } //Setting default toolbar items if((tb_items.size()==0) && !config.contains("Toolbar/itemCount")) { tb_items.append(itemAdd); tb_items.append(itemRemove); tb_items.append(itemRename); tb_items.append(itemSeparator); tb_items.append(itemPrev); tb_items.append(itemNext); tb_items.append(itemSeparator); tb_items.append(itemCopy); tb_items.append(itemSeparator); tb_items.append(itemSetup); tb_items.append(itemInfo); tb_items.append(itemSeparator); tb_items.append(itemRun); tb_items.append(itemSearch); tb_items.append(itemSeparator); tb_items.append(itemExit); config.setValue("Toolbar/itemCount", tb_items.size()); for(int i=0; i<tb_items.size(); ++i) if(tb_items[i]!=itemSeparator) config.setValue(ToolbarAction(item_enum(tb_items[i])).pref_name(), i); } loadLanguages(); // #ifdef unix //Fixing Qt's problem on unix systems... QString system_lang(qgetenv("LANG").constData()); system_lang.truncate(system_lang.indexOf('.')); if(system_lang.size()) locale_system = QLocale(system_lang); else locale_system = QLocale::system().language(); #else locale_system = QLocale::system().language(); #endif locale = (language_custom)?locale_current:locale_system; QMap<int, QMap<int, QString> >::const_iterator it = translations.find(locale.language()); if(it!=translations.end()) //if translation list has locale language { const QMap<int, QString>& country_list = it.value(); if(!country_list.contains(locale.country())) { QList<QLocale::Country> language_countries = QLocale::countriesForLanguage(locale.language()); if(!language_countries.empty() && country_list.contains(language_countries[0])) { QLocale::Country country = language_countries[0]; locale = QLocale(locale.language(), country); } else if(!country_list.empty()) { QLocale::Country country = QLocale::Country(country_list.begin().key()); locale = QLocale(locale.language(), country); } else locale = QLocale::c(); } } else locale = QLocale::c(); updateLocale(); qApp->installTranslator(&qtranslator); qApp->installTranslator(&translator); }
void Settings::init(){ if(!qApp->arguments().contains("-server")){ QString font_path = value("DefaultFontPath", "font/girl.ttf").toString(); int font_id = QFontDatabase::addApplicationFont(font_path); if(font_id!=-1){ QString font_family = QFontDatabase::applicationFontFamilies(font_id).first(); BigFont.setFamily(font_family); SmallFont.setFamily(font_family); TinyFont.setFamily(font_family); }else QMessageBox::warning(NULL, tr("Warning"), tr("Font file %1 could not be loaded!").arg(font_path)); BigFont.setPixelSize(56); SmallFont.setPixelSize(27); TinyFont.setPixelSize(18); SmallFont.setWeight(QFont::Bold); AppFont = value("AppFont", QApplication::font("QMainWindow")).value<QFont>(); UIFont = value("UIFont", QApplication::font("QTextEdit")).value<QFont>(); TextEditColor = QColor(value("TextEditColor", "white").toString()); } CountDownSeconds = value("CountDownSeconds", 3).toInt(); GameMode = value("GameMode", "02p").toString(); if(!contains("BanPackages")){ QStringList banlist; banlist << "nostalgia" << "yitian" << "wisdom" << "test" << "disaster" << "god" << "YJCM" << "yitian_cards" << "sp" << "sp_cards" << "joy" << "joy_equip"; setValue("BanPackages", banlist); } BanPackages = value("BanPackages").toStringList(); ContestMode = value("ContestMode", false).toBool(); FreeChoose = value("FreeChoose", false).toBool(); ForbidSIMC = value("ForbidSIMC", false).toBool(); DisableChat = value("DisableChat", false).toBool(); Enable2ndGeneral = value("Enable2ndGeneral", false).toBool(); EnableScene = value("EnableScene", false).toBool(); //changjing MaxHpScheme = value("MaxHpScheme", 0).toInt(); AnnounceIP = value("AnnounceIP", false).toBool(); Address = value("Address", QString()).toString(); EnableAI = value("EnableAI", false).toBool(); AIDelay = value("AIDelay", 1000).toInt(); ServerPort = value("ServerPort", 9527u).toUInt(); #ifdef Q_OS_WIN32 UserName = value("UserName", qgetenv("USERNAME")).toString(); #else UserName = value("USERNAME", qgetenv("USER")).toString(); #endif if(UserName == "Admin" || UserName == "Administrator") UserName = tr("Sanguosha-fans"); ServerName = value("ServerName", tr("%1's server").arg(UserName)).toString(); HostAddress = value("HostAddress", "127.0.0.1").toString(); UserAvatar = value("UserAvatar", "zhangliao").toString(); HistoryIPs = value("HistoryIPs").toStringList(); DetectorPort = value("DetectorPort", 9526u).toUInt(); MaxCards = value("MaxCards", 15).toInt(); FitInView = value("FitInView", false).toBool(); EnableHotKey = value("EnableHotKey", true).toBool(); NeverNullifyMyTrick = value("NeverNullifyMyTrick", true).toBool(); EnableAutoTarget = value("EnableAutoTarget", false).toBool(); NullificationCountDown = value("NullificationCountDown", 8).toInt(); OperationTimeout = value("OperationTimeout", 15).toInt(); OperationNoLimit = value("OperationNoLimit", false).toBool(); EnableEffects = value("EnableEffects", true).toBool(); EnableLastWord = value("EnableLastWord", true).toBool(); EnableBgMusic = value("EnableBgMusic", true).toBool(); BGMVolume = value("BGMVolume", 1.0f).toFloat(); EffectVolume = value("EffectVolume", 1.0f).toFloat(); EffectEdition = value("EffectEdition", "classical/").toString(); BackgroundBrush = value("BackgroundBrush", "backdrop/chibi.jpg").toString(); if(!contains("1v1/Banlist")){ QStringList banlist; banlist << "sunquan" << "huatuo" << "zhangliao" << "liubei"; setValue("1v1/Banlist", banlist); } }
void QEglFSScreen::createAndSetPlatformContext() { QPlatformWindowFormat platformFormat = QPlatformWindowFormat::defaultFormat(); platformFormat.setWindowApi(QPlatformWindowFormat::OpenGL); QByteArray depthString = qgetenv("QT_QPA_EGLFS_DEPTH"); if (depthString.toInt() == 16) { platformFormat.setDepth(16); platformFormat.setRedBufferSize(5); platformFormat.setGreenBufferSize(6); platformFormat.setBlueBufferSize(5); m_depth = 16; m_format = QImage::Format_RGB16; } else { platformFormat.setDepth(32); platformFormat.setRedBufferSize(8); platformFormat.setGreenBufferSize(8); platformFormat.setBlueBufferSize(8); m_depth = 32; m_format = QImage::Format_RGB32; } if (!qgetenv("QT_QPA_EGLFS_MULTISAMPLE").isEmpty()) { platformFormat.setSampleBuffers(true); } EGLConfig config = q_configFromQPlatformWindowFormat(m_dpy, platformFormat); EGLNativeWindowType eglWindow = 0; #ifdef Q_OPENKODE if (kdInitializeNV() == KD_ENOTINITIALIZED) { qFatal("Did not manage to initialize openkode"); } KDWindow *window = kdCreateWindow(m_dpy,config,0); kdRealizeWindow(window,&eglWindow); #endif m_surface = eglCreateWindowSurface(m_dpy, config, eglWindow, NULL); if (m_surface == EGL_NO_SURFACE) { qWarning("Could not create the egl surface: error = 0x%x\n", eglGetError()); eglTerminate(m_dpy); qFatal("EGL error"); } // qWarning("Created surface %dx%d\n", w, h); #ifdef QEGL_EXTRA_DEBUG qWarning("Configuration %d matches requirements\n", (int)config); for (index = 0; attrs[index].attr != -1; ++index) { EGLint value; if (eglGetConfigAttrib(m_dpy, config, attrs[index].attr, &value)) { qWarning("\t%s: %d\n", attrs[index].name, (int)value); } } qWarning("\n"); #endif EGLint temp; EGLint attribList[32]; temp = 0; attribList[temp++] = EGL_CONTEXT_CLIENT_VERSION; attribList[temp++] = 2; // GLES version 2 attribList[temp++] = EGL_NONE; QEGLPlatformContext *platformContext = new QEGLPlatformContext(m_dpy,config,attribList,m_surface,EGL_OPENGL_ES_API); m_platformContext = platformContext; EGLint w,h; // screen size detection eglQuerySurface(m_dpy, m_surface, EGL_WIDTH, &w); eglQuerySurface(m_dpy, m_surface, EGL_HEIGHT, &h); m_geometry = QRect(0,0,w,h); }
#include <QSslError> #include <QQmlFile> #include <QMetaMethod> #include <private/qqmlprofilerservice_p.h> #define IMAGEREQUEST_MAX_REQUEST_COUNT 8 #define IMAGEREQUEST_MAX_REDIRECT_RECURSION 16 #define CACHE_EXPIRE_TIME 30 #define CACHE_REMOVAL_FRACTION 4 QT_BEGIN_NAMESPACE #ifndef QT_NO_DEBUG static bool qsg_leak_check = !qgetenv("QML_LEAK_CHECK").isEmpty(); #endif // The cache limit describes the maximum "junk" in the cache. static int cache_limit = 2048 * 1024; // 2048 KB cache limit for embedded in qpixmapcache.cpp static inline QString imageProviderId(const QUrl &url) { return url.host(); } static inline QString imageId(const QUrl &url) { return url.toString(QUrl::RemoveScheme | QUrl::RemoveAuthority).mid(1); }
int main(int argc, char** argv) { Application app(argc, argv); if (app.isRunning()) { app.sendMessage(app.files().join(QLatin1String("\n"))); return 0; } QString appdir = app.applicationDirPath(); // Set locations of fallback icons QStringList paths = QIcon::themeSearchPaths(); paths.prepend(appdir + "/../share/focuswriter/icons"); paths.prepend(appdir + "/icons"); QIcon::setThemeSearchPaths(paths); // Find sounds paths.clear(); paths.append(appdir + "/sounds/"); paths.append(appdir + "/../share/focuswriter/sounds/"); paths.append(appdir + "/../Resources/sounds"); foreach (const QString& path, paths) { if (QFile::exists(path)) { Sound::setPath(path); break; } } // Find unicode names paths.clear(); paths.append(appdir + "/symbols.dat"); paths.append(appdir + "/../share/focuswriter/symbols.dat"); paths.append(appdir + "/../Resources/symbols.dat"); foreach (const QString& path, paths) { if (QFile::exists(path)) { SymbolsModel::setData(path); break; } } // Find data paths QStringList locations; #if defined(Q_OS_MAC) QFileInfo portable(appdir + "/../../../Data"); QString path = QDir::homePath() + "/Library/Application Support/GottCode/FocusWriter/"; #elif defined(Q_OS_UNIX) QFileInfo portable(appdir + "/Data"); QString path = qgetenv("XDG_DATA_HOME"); if (path.isEmpty()) { path = QDir::homePath() + "/.local/share"; } path += "/focuswriter/"; QStringList xdg = QString(qgetenv("XDG_DATA_DIRS")).split(QChar(':'), QString::SkipEmptyParts); if (xdg.isEmpty()) { xdg.append("/usr/local/share"); xdg.append("/usr/share"); } QStringList subdirs = QStringList() << "/hunspell" << "/myspell/dicts" << "/myspell"; foreach (const QString& subdir, subdirs) { foreach (const QString& dir, xdg) { QString path = dir + subdir; if (!locations.contains(path)) { locations.append(path); } }
QString QDesktopServices::storageLocation(StandardLocation type) { if (type == QDesktopServices::HomeLocation) return QDir::homePath(); if (type == QDesktopServices::TempLocation) return QDir::tempPath(); // http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html if (type == QDesktopServices::CacheLocation) { QString xdgCacheHome = QLatin1String(qgetenv("XDG_CACHE_HOME")); if (xdgCacheHome.isEmpty()) xdgCacheHome = QDir::homePath() + QLatin1String("/.cache"); xdgCacheHome += QLatin1Char('/') + QCoreApplication::organizationName() + QLatin1Char('/') + QCoreApplication::applicationName(); return xdgCacheHome; } if (type == QDesktopServices::DataLocation) { QString xdgDataHome = QLatin1String(qgetenv("XDG_DATA_HOME")); if (xdgDataHome.isEmpty()) xdgDataHome = QDir::homePath() + QLatin1String("/.local/share"); xdgDataHome += QLatin1String("/data/") + QCoreApplication::organizationName() + QLatin1Char('/') + QCoreApplication::applicationName(); return xdgDataHome; } // http://www.freedesktop.org/wiki/Software/xdg-user-dirs QString xdgConfigHome = QLatin1String(qgetenv("XDG_CONFIG_HOME")); if (xdgConfigHome.isEmpty()) xdgConfigHome = QDir::homePath() + QLatin1String("/.config"); QFile file(xdgConfigHome + QLatin1String("/user-dirs.dirs")); if (file.exists() && file.open(QIODevice::ReadOnly)) { QHash<QString, QString> lines; QTextStream stream(&file); // Only look for lines like: XDG_DESKTOP_DIR="$HOME/Desktop" QRegExp exp(QLatin1String("^XDG_(.*)_DIR=(.*)$")); while (!stream.atEnd()) { QString line = stream.readLine(); if (exp.indexIn(line) != -1) { QStringList lst = exp.capturedTexts(); QString key = lst.at(1); QString value = lst.at(2); if (value.length() > 2 && value.startsWith(QLatin1Char('\"')) && value.endsWith(QLatin1Char('\"'))) value = value.mid(1, value.length() - 2); // Store the key and value: "DESKTOP", "$HOME/Desktop" lines[key] = value; } } QString key; switch (type) { case DesktopLocation: key = QLatin1String("DESKTOP"); break; case DocumentsLocation: key = QLatin1String("DOCUMENTS"); break; case PicturesLocation: key = QLatin1String("PICTURES"); break; case MusicLocation: key = QLatin1String("MUSIC"); break; case MoviesLocation: key = QLatin1String("VIDEOS"); break; default: break; } if (!key.isEmpty() && lines.contains(key)) { QString value = lines[key]; // value can start with $HOME if (value.startsWith(QLatin1String("$HOME"))) value = QDir::homePath() + value.mid(5); return value; } } QDir emptyDir; QString path; switch (type) { case DesktopLocation: path = QDir::homePath() + QLatin1String("/Desktop"); break; case DocumentsLocation: path = QDir::homePath() + QLatin1String("/Documents"); break; case PicturesLocation: path = QDir::homePath() + QLatin1String("/Pictures"); break; case FontsLocation: path = QDir::homePath() + QLatin1String("/.fonts"); break; case MusicLocation: path = QDir::homePath() + QLatin1String("/Music"); break; case MoviesLocation: path = QDir::homePath() + QLatin1String("/Videos"); break; case ApplicationsLocation: default: break; } return path; }
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); Q_INIT_RESOURCE(actionicons); Q_INIT_RESOURCE(providericons); // Configure mbox settings QScopedPointer<Dekko::Settings::SettingsFileBase> mboxSettings(new Dekko::Settings::SettingsFileBase); Dekko::Settings::MailboxSettings::setDefaultFile(mboxSettings.data()); mboxSettings.data()->setPath(Dekko::configLocation(QStringLiteral("mailboxConfig.json"))); // Notification settings QScopedPointer<Dekko::Settings::SettingsFileBase> notificationSettings(new Dekko::Settings::SettingsFileBase); Dekko::Settings::NotificationSettings::setSettingsFile(notificationSettings.data()); notificationSettings.data()->setPath(Dekko::configLocation(QStringLiteral("notifications.json"))); //Install translations QTranslator dekkoTranslater; QTranslator dekkoBuildTranslater; // It would appear Qt has a real problem loading translations for anywhere but in the same directory // as the executable. I have no idea if this is click package related or a bug in Qt but this works // so i'm not going to complain.... (*much*) if (dekkoTranslater.load(QLocale::system().name(), app.applicationDirPath())) { qDebug() << "Translation loaded" ; app.installTranslator(&dekkoTranslater); } else if (dekkoTranslater.load(QLocale::system().name(), QCoreApplication::applicationDirPath() + QLatin1String("/locale/"))) { qDebug() << "Installing translations in build dir"; app.installTranslator(&dekkoBuildTranslater); } qQuickViewer = new QQuickView(); qQuickViewer->setResizeMode(QQuickView::SizeRootObjectToView); app.addLibraryPath(QCoreApplication::applicationDirPath()); // let's first check all standard locations QString qmlFile = Dekko::findQmlFile(QString::fromLatin1("qml/dekko.qml")); Common::registerMetaTypes(); Common::Application::name = QString::fromLatin1("dekko"); Common::Application::organization = QString::fromLatin1("dekko.dekkoproject"); AppVersion::setVersion(); AppVersion::setCoreApplicationData(); QUrl addressbookStoreLocation(QString::fromLatin1( "file://%1/.local/share/dekko.dekkoproject/addressbook.vcard") .arg(QDir::homePath())); qQuickViewer->engine()->rootContext()->setContextProperty(QLatin1String("addressbookStoreLocation"), QVariant::fromValue(addressbookStoreLocation)); Dekko::MsgPartNetAccessManagerFactory msgPartNetAccessManagerFactory; qQuickViewer->engine()->setNetworkAccessManagerFactory(&msgPartNetAccessManagerFactory); qQuickViewer->engine()->rootContext()->setContextProperty(QLatin1String("msgPartNetAccessManagerFactory"), &msgPartNetAccessManagerFactory); qQuickViewer->engine()->rootContext()->setContextProperty(QLatin1String("appUris"), QString::fromLatin1(qgetenv("APP_URIS"))); registerDekkoTypes("DekkoCore"); registerTrojitaCoreTypes("TrojitaCore"); qQuickViewer->setTitle(QObject::trUtf8("Dekko")); qQuickViewer->setSource(QUrl::fromLocalFile(qmlFile)); qQuickViewer->show(); return app.exec(); }
// Chooses the EGL config and creates the EGL context bool QGLContext::chooseContext(const QGLContext* shareContext) // almost same as in qgl_x11egl.cpp { Q_D(QGLContext); if (!device()) return false; int devType = device()->devType(); if ((devType != QInternal::Widget) && (devType != QInternal::Pbuffer)) { qWarning("WARNING: Creating a QGLContext not supported on device type %d", devType); return false; } // Get the display and initialize it. if (d->eglContext == 0) { d->eglContext = new QEglContext(); d->ownsEglContext = true; d->eglContext->setApi(QEgl::OpenGL); if (d->glFormat.samples() == EGL_DONT_CARE) { // Allow apps to override ability to use multisampling by setting an environment variable. Eg: // qputenv("QT_SYMBIAN_DISABLE_GL_MULTISAMPLE", "1"); // Added to allow camera app to start with limited memory. if (!QSymbianGraphicsSystemEx::hasBCM2727() && !qgetenv("QT_SYMBIAN_DISABLE_GL_MULTISAMPLE").toInt()) { // Most likely we have hw support for multisampling // so let's enable it. d->glFormat.setSampleBuffers(1); d->glFormat.setSamples(4); } else { d->glFormat.setSampleBuffers(0); d->glFormat.setSamples(0); } } // If the device is a widget with WA_TranslucentBackground set, make sure the glFormat // has the alpha channel option set: if (devType == QInternal::Widget) { QWidget* widget = static_cast<QWidget*>(device()); if (widget->testAttribute(Qt::WA_TranslucentBackground)) d->glFormat.setAlpha(true); } // Construct the configuration we need for this surface. QEglProperties configProps; configProps.setDeviceType(devType); configProps.setPaintDeviceFormat(device()); configProps.setRenderableType(QEgl::OpenGL); configProps.setValue(EGL_SURFACE_TYPE, EGL_WINDOW_BIT|EGL_SWAP_BEHAVIOR_PRESERVED_BIT); qt_eglproperties_set_glformat(configProps, d->glFormat); if (!d->eglContext->chooseConfig(configProps, QEgl::BestPixelFormat)) { delete d->eglContext; d->eglContext = 0; return false; } // Create a new context for the configuration. QEglContext* eglSharedContext = shareContext ? shareContext->d_func()->eglContext : 0; if (!d->eglContext->createContext(eglSharedContext)) { delete d->eglContext; d->eglContext = 0; return false; } d->sharing = d->eglContext->isSharing(); if (d->sharing && shareContext) const_cast<QGLContext *>(shareContext)->d_func()->sharing = true; } // Inform the higher layers about the actual format properties qt_glformat_from_eglconfig(d->glFormat, d->eglContext->config()); // Do don't create the EGLSurface for everything. // QWidget - yes, create the EGLSurface and store it in QGLContextPrivate::eglSurface // QGLWidget - yes, create the EGLSurface and store it in QGLContextPrivate::eglSurface // QGLPixelBuffer - no, it creates the surface itself and stores it in QGLPixelBufferPrivate::pbuf if (devType == QInternal::Widget) { if (d->eglSurface != EGL_NO_SURFACE) eglDestroySurface(d->eglContext->display(), d->eglSurface); d->eglSurface = QEgl::createSurface(device(), d->eglContext->config()); eglGetError(); // Clear error state first. #ifdef QGL_NO_PRESERVED_SWAP eglSurfaceAttrib(QEgl::display(), d->eglSurface, EGL_SWAP_BEHAVIOR, EGL_BUFFER_DESTROYED); if (eglGetError() != EGL_SUCCESS) qWarning("QGLContext: could not enable destroyed swap behaviour"); #else eglSurfaceAttrib(QEgl::display(), d->eglSurface, EGL_SWAP_BEHAVIOR, EGL_BUFFER_PRESERVED); if (eglGetError() != EGL_SUCCESS) qWarning("QGLContext: could not enable preserved swap behaviour"); #endif setWindowCreated(true); } return true; }
int main(int argc, char **argv) { //QTime t = QTime::currentTime(); Q_UNUSED(copyrightString); #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) qInstallMessageHandler(debugOutput); #else qInstallMsgHandler(debugOutput); #endif #ifndef KTIKZ_USE_KDE // discard session (X11 calls QApplication::saveState() also when the app // has been started, but then also calls QSessionManager::discardCommand() // which we define as below in order to remove unnecessary session // information) if (argc == 3 && !strcmp(argv[1], "--discard")) { QSettings settings(QString::fromLocal8Bit(ORGNAME), QString::fromLocal8Bit(APPNAME)); settings.remove(QLatin1String("Session") + QLatin1String(argv[2])); // argv[2] contains the session id settings.sync(); return 0; } #endif #ifdef KTIKZ_USE_KDE Q_INIT_RESOURCE(ktikz); KAboutData aboutData("ktikz", "ktikz", ki18n("KtikZ"), APPVERSION); aboutData.setShortDescription(ki18n("A TikZ Editor")); aboutData.setLicense(KAboutData::License_GPL_V2); aboutData.setCopyrightStatement(ki18n("Copyright 2007-2014 Florian Hackenberger, Glad Deschrijver")); aboutData.setOtherText(ki18n("This is a program for creating TikZ (from the LaTeX pgf package) diagrams.")); aboutData.setBugAddress("*****@*****.**"); aboutData.addAuthor(ki18n("Florian Hackenberger"), ki18n("Maintainer"), "*****@*****.**"); aboutData.addAuthor(ki18n("Glad Deschrijver"), ki18n("Developer"), "*****@*****.**"); KCmdLineArgs::init(argc, argv, &aboutData); KCmdLineOptions options; options.add("+[URL]", ki18n("TikZ document to open")); KCmdLineArgs::addCmdLineOptions(options); #else Q_INIT_RESOURCE(qtikz); #endif KtikzApplication app(argc, argv); // slow QCoreApplication::setOrganizationName(QString::fromLocal8Bit(ORGNAME)); #ifndef KTIKZ_USE_KDE QCoreApplication::setApplicationName(QString::fromLocal8Bit(APPNAME)); QCoreApplication::setApplicationVersion(QString::fromLocal8Bit(APPVERSION)); #endif const QString translationsDirPath = QString::fromLocal8Bit(qgetenv("KTIKZ_TRANSLATIONS_DIR").constData()); QTranslator qtTranslator; QTranslator qtikzTranslator; createTranslator(&qtTranslator, QLatin1String("qt"), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); createTranslator(&qtikzTranslator, QLatin1String("qtikz"), translationsDirPath); app.installTranslator(&qtTranslator); app.installTranslator(&qtikzTranslator); app.init(); //qCritical() << t.msecsTo(QTime::currentTime()); return app.exec(); }
QGLGraphicsSystem::QGLGraphicsSystem(bool useX11GL) : QGraphicsSystem(), m_useX11GL(useX11GL) { #if defined(Q_WS_X11) && !defined(QT_OPENGL_ES) // only override the system defaults if the user hasn't already // picked a visual if (X11->visual == 0 && X11->visual_id == -1 && X11->visual_class == -1) { // find a double buffered, RGBA visual that supports OpenGL // and set that as the default visual for windows in Qt int i = 0; int spec[16]; spec[i++] = GLX_RGBA; spec[i++] = GLX_DOUBLEBUFFER; if (!qgetenv("QT_GL_SWAPBUFFER_PRESERVE").isNull()) { spec[i++] = GLX_DEPTH_SIZE; spec[i++] = 8; spec[i++] = GLX_STENCIL_SIZE; spec[i++] = 8; spec[i++] = GLX_SAMPLE_BUFFERS_ARB; spec[i++] = 1; spec[i++] = GLX_SAMPLES_ARB; spec[i++] = 4; } spec[i++] = XNone; XVisualInfo *vi = glXChooseVisual(X11->display, X11->defaultScreen, spec); if (vi) { X11->visual_id = vi->visualid; X11->visual_class = vi->c_class; QGLFormat format; int res; glXGetConfig(X11->display, vi, GLX_LEVEL, &res); format.setPlane(res); glXGetConfig(X11->display, vi, GLX_DOUBLEBUFFER, &res); format.setDoubleBuffer(res); glXGetConfig(X11->display, vi, GLX_DEPTH_SIZE, &res); format.setDepth(res); if (format.depth()) format.setDepthBufferSize(res); glXGetConfig(X11->display, vi, GLX_RGBA, &res); format.setRgba(res); glXGetConfig(X11->display, vi, GLX_RED_SIZE, &res); format.setRedBufferSize(res); glXGetConfig(X11->display, vi, GLX_GREEN_SIZE, &res); format.setGreenBufferSize(res); glXGetConfig(X11->display, vi, GLX_BLUE_SIZE, &res); format.setBlueBufferSize(res); glXGetConfig(X11->display, vi, GLX_ALPHA_SIZE, &res); format.setAlpha(res); if (format.alpha()) format.setAlphaBufferSize(res); glXGetConfig(X11->display, vi, GLX_ACCUM_RED_SIZE, &res); format.setAccum(res); if (format.accum()) format.setAccumBufferSize(res); glXGetConfig(X11->display, vi, GLX_STENCIL_SIZE, &res); format.setStencil(res); if (format.stencil()) format.setStencilBufferSize(res); glXGetConfig(X11->display, vi, GLX_STEREO, &res); format.setStereo(res); glXGetConfig(X11->display, vi, GLX_SAMPLE_BUFFERS_ARB, &res); format.setSampleBuffers(res); if (format.sampleBuffers()) { glXGetConfig(X11->display, vi, GLX_SAMPLES_ARB, &res); format.setSamples(res); } QGLWindowSurface::surfaceFormat = format; XFree(vi); printf("using visual class %x, id %x\n", X11->visual_class, X11->visual_id); } } #elif defined(Q_WS_WIN) QGLWindowSurface::surfaceFormat.setDoubleBuffer(true); qt_win_owndc_required = true; #endif }
// Called also from WebKit2's WebProcess. Q_DECL_EXPORT void initializeWebKit2Theme() { if (qgetenv("QT_WEBKIT_THEME_NAME") == "qstyle") WebCore::RenderThemeQt::setCustomTheme(WebCore::RenderThemeQStyle::create, new WebCore::ScrollbarThemeQStyle); }
void TestController::initializeTestPluginDirectory() { m_testPluginDirectory.adopt(WKStringCreateWithUTF8CString(qgetenv("QTWEBKIT_PLUGIN_PATH").constData())); }
int main(int argc, const char* argv[]) { #ifdef Q_OS_WIN // Run only one instance of Interface at a time. HANDLE mutex = CreateMutex(NULL, FALSE, "High Fidelity Interface - " + qgetenv("USERNAME")); DWORD result = GetLastError(); if (result == ERROR_ALREADY_EXISTS || result == ERROR_ACCESS_DENIED) { // Interface is already running. HWND otherInstance = NULL; EnumWindows(enumWindowsCallback, (LPARAM)&otherInstance); if (otherInstance) { // Show other instance. SendMessage(otherInstance, UWM_SHOW_APPLICATION, 0, 0); // Send command line --url value to other instance. if (argc >= 3) { QStringList arguments; for (int i = 0; i < argc; i += 1) { arguments << argv[i]; } QCommandLineParser parser; QCommandLineOption urlOption("url", "", "value"); parser.addOption(urlOption); parser.process(arguments); if (parser.isSet(urlOption)) { QUrl url = QUrl(parser.value(urlOption)); if (url.isValid() && url.scheme() == HIFI_URL_SCHEME) { QByteArray urlBytes = url.toString().toLatin1(); const char* urlChars = urlBytes.data(); COPYDATASTRUCT cds; cds.cbData = urlBytes.length() + 1; cds.lpData = (PVOID)urlChars; SendMessage(otherInstance, WM_COPYDATA, 0, (LPARAM)&cds); } } } } return 0; } #endif QElapsedTimer startupTime; startupTime.start(); // Debug option to demonstrate that the client's local time does not // need to be in sync with any other network node. This forces clock // skew for the individual client const char* CLOCK_SKEW = "--clockSkew"; const char* clockSkewOption = getCmdOption(argc, argv, CLOCK_SKEW); if (clockSkewOption) { int clockSkew = atoi(clockSkewOption); usecTimestampNowForceClockSkew(clockSkew); qCDebug(interfaceapp, "clockSkewOption=%s clockSkew=%d", clockSkewOption, clockSkew); } // Oculus initialization MUST PRECEDE OpenGL context creation. // The nature of the Application constructor means this has to be either here, // or in the main window ctor, before GL startup. Application::initPlugins(); int exitCode; { QSettings::setDefaultFormat(QSettings::IniFormat); Application app(argc, const_cast<char**>(argv), startupTime); QTranslator translator; translator.load("interface_en"); app.installTranslator(&translator); qCDebug(interfaceapp, "Created QT Application."); exitCode = app.exec(); } Application::shutdownPlugins(); #ifdef Q_OS_WIN ReleaseMutex(mutex); #endif qCDebug(interfaceapp, "Normal exit."); return exitCode; }