Example #1
0
void KonfUpdate::gotScript(const QString &_script)
{
    QString script, interpreter;
    int i = _script.indexOf(',');
    if (i == -1) {
        script = _script.trimmed();
    } else {
        script = _script.left(i).trimmed();
        interpreter = _script.mid(i + 1).trimmed();
    }


    if (script.isEmpty()) {
        logFileError() << "Script fails to specify filename";
        m_skip = true;
        return;
    }



    QString path = KStandardDirs::locate("data", "kconf_update/" + script);
    if (path.isEmpty()) {
        if (interpreter.isEmpty()) {
            path = KStandardDirs::locate("lib", "kconf_update_bin/" + script);
        }

        if (path.isEmpty()) {
            logFileError() << "Script '" << script << "' not found" << endl;
            m_skip = true;
            return;
        }
    }

    if (!m_arguments.isNull()) {
        log() << m_currentFilename << ": Running script '" << script << "' with arguments '" << m_arguments << "'" << endl;
    } else {
        log() << m_currentFilename << ": Running script '" << script << "'" << endl;
    }

    QString cmd;
    if (interpreter.isEmpty()) {
        cmd = path;
    } else {
        cmd = interpreter + ' ' + path;
    }

    if (!m_arguments.isNull()) {
        cmd += ' ';
        cmd += m_arguments;
    }

    KTemporaryFile scriptIn;
    scriptIn.open();
    KTemporaryFile scriptOut;
    scriptOut.open();
    KTemporaryFile scriptErr;
    scriptErr.open();

    int result;
    if (m_oldConfig1) {
        if (m_debug) {
            scriptIn.setAutoRemove(false);
            log() << "Script input stored in " << scriptIn.fileName() << endl;
        }
        KConfig cfg(scriptIn.fileName(), KConfig::SimpleConfig);

        if (m_oldGroup.isEmpty()) {
            // Write all entries to tmpFile;
            const QStringList grpList = m_oldConfig1->groupList();
            for (QStringList::ConstIterator it = grpList.begin();
                    it != grpList.end();
                    ++it) {
                copyGroup(m_oldConfig1, *it, &cfg, *it);
            }
        } else {
            KConfigGroup cg1 = KConfigUtils::openGroup(m_oldConfig1, m_oldGroup);
            KConfigGroup cg2(&cfg, QString());
            copyGroup(cg1, cg2);
        }
        cfg.sync();
#ifndef _WIN32_WCE
        result = system(QFile::encodeName(QString("%1 < %2 > %3 2> %4").arg(cmd, scriptIn.fileName(), scriptOut.fileName(), scriptErr.fileName())));
#else
        QString path_ = QDir::convertSeparators ( QFileInfo ( cmd ).absoluteFilePath() );
        QString file_ = QFileInfo ( cmd ).fileName();
        SHELLEXECUTEINFO execInfo;
        memset ( &execInfo,0,sizeof ( execInfo ) );
        execInfo.cbSize = sizeof ( execInfo );
        execInfo.fMask =  SEE_MASK_FLAG_NO_UI;
        execInfo.lpVerb = L"open";
        execInfo.lpFile = (LPCWSTR) path_.utf16();
        execInfo.lpDirectory = (LPCWSTR) file_.utf16();
        execInfo.lpParameters = (LPCWSTR) QString(" < %1 > %2 2> %3").arg( scriptIn.fileName(), scriptOut.fileName(), scriptErr.fileName()).utf16();
        result = ShellExecuteEx ( &execInfo );
        if (result != 0)
        {
            result = 0;
        }
        else
        {
            result = -1;
        }
#endif
    } else {
        // No config file
#ifndef _WIN32_WCE
        result = system(QFile::encodeName(QString("%1 2> %2").arg(cmd, scriptErr.fileName())));
#else
        QString path_ = QDir::convertSeparators ( QFileInfo ( cmd ).absoluteFilePath() );
        QString file_ = QFileInfo ( cmd ).fileName();
        SHELLEXECUTEINFO execInfo;
        memset ( &execInfo,0,sizeof ( execInfo ) );
        execInfo.cbSize = sizeof ( execInfo );
        execInfo.fMask =  SEE_MASK_FLAG_NO_UI;
        execInfo.lpVerb = L"open";
        execInfo.lpFile = (LPCWSTR) path_.utf16();
        execInfo.lpDirectory = (LPCWSTR) file_.utf16();
        execInfo.lpParameters = (LPCWSTR) QString(" 2> %1").arg( scriptErr.fileName()).utf16();
        result = ShellExecuteEx ( &execInfo );
        if (result != 0)
        {
            result = 0;
        }
        else
        {
            result = -1;
        }
#endif
    }

    // Copy script stderr to log file
    {
        QFile output(scriptErr.fileName());
        if (output.open(QIODevice::ReadOnly)) {
            QTextStream ts(&output);
            ts.setCodec(QTextCodec::codecForName("UTF-8"));
            while (!ts.atEnd()) {
                QString line = ts.readLine();
                log() << "[Script] " << line << endl;
            }
        }
    }

    if (result) {
        log() << m_currentFilename << ": !! An error occurred while running '" << cmd << "'" << endl;
        return;
    }

    if (!m_oldConfig1) {
        return; // Nothing to merge
    }

    if (m_debug) {
        scriptOut.setAutoRemove(false);
        log() << "Script output stored in " << scriptOut.fileName() << endl;
    }

    // Deleting old entries
    {
        QStringList group = m_oldGroup;
        QFile output(scriptOut.fileName());
        if (output.open(QIODevice::ReadOnly)) {
            QTextStream ts(&output);
            ts.setCodec(QTextCodec::codecForName("UTF-8"));
            while (!ts.atEnd()) {
                QString line = ts.readLine();
                if (line.startsWith('[')) {
                    group = parseGroupString(line);
                } else if (line.startsWith(QLatin1String("# DELETE "))) {
                    QString key = line.mid(9);
                    if (key[0] == '[') {
                        int j = key.lastIndexOf(']') + 1;
                        if (j > 0) {
                            group = parseGroupString(key.left(j));
                            key = key.mid(j);
                        }
                    }
                    KConfigGroup cg = KConfigUtils::openGroup(m_oldConfig2, group);
                    cg.deleteEntry(key);
                    log() << m_currentFilename << ": Script removes " << m_oldFile << ":" << group << ":" << key << endl;
                    /*if (m_oldConfig2->deleteGroup(group, KConfig::Normal)) { // Delete group if empty.
                       log() << m_currentFilename << ": Removing empty group " << m_oldFile << ":" << group << endl;
                    } (this should be automatic)*/
                } else if (line.startsWith(QLatin1String("# DELETEGROUP"))) {
                    QString str = line.mid(13).trimmed();
                    if (!str.isEmpty()) {
                        group = parseGroupString(str);
                    }
                    KConfigGroup cg = KConfigUtils::openGroup(m_oldConfig2, group);
                    cg.deleteGroup();
                    log() << m_currentFilename << ": Script removes group " << m_oldFile << ":" << group << endl;
                }
            }
        }
    }

    // Merging in new entries.
    KConfig scriptOutConfig(scriptOut.fileName(), KConfig::NoGlobals);
    if (m_newGroup.isEmpty()) {
        // Copy "default" keys as members of "default" keys
        copyGroup(&scriptOutConfig, QString(), m_newConfig, QString());
    } else {
        // Copy default keys as members of m_newGroup
        KConfigGroup srcCg = KConfigUtils::openGroup(&scriptOutConfig, QStringList());
        KConfigGroup dstCg = KConfigUtils::openGroup(m_newConfig, m_newGroup);
        copyGroup(srcCg, dstCg);
    }
    Q_FOREACH(const QString &group, scriptOutConfig.groupList()) {
        copyGroup(&scriptOutConfig, group, m_newConfig, group);
    }
}
Example #2
0
    QString Util::extractUrlData(const QString text, bool doHyperlinks)
    {
        // QTime timer;
        // timer.start();

        int pos = 0;
        int urlLen = 0;

        QString link;
        QString extractedText = text;
        QString insertText;
        QString protocol;
        QString href;
        QString append;

        URL_PATTERN.setCaseSensitivity(Qt::CaseInsensitive);

        if (doHyperlinks)
        {
            link = "<a href=\"#%1\">%2</a>";

            if (extractedText.contains("#"))
            {
                QRegExp chanExp("(^|\\s|^\"|\\s\"|,|'|\\(|\\:|!|@|%|\\+)(#[^,\\s;\\)\\:\\/\\(\\<\\>]*[^.,\\s;\\)\\:\\/\\(\"\''\\<\\>])");

                while ((pos = chanExp.indexIn(extractedText, pos)) >= 0)
                {
                    href = chanExp.cap(2);
                    urlLen = href.length();
                    pos += chanExp.cap(1).length();

                    insertText = link.arg(href, href);
                    extractedText.replace(pos, urlLen, insertText);
                    pos += insertText.length();
                }
            }

            link = "<a href=\"%1%2\">%3</a>";

            pos = 0;
            urlLen = 0;
        }

        while ((pos = URL_PATTERN.indexIn(extractedText, pos)) >= 0)
        {
            urlLen = URL_PATTERN.matchedLength();

            // check if the matched text is already replaced as a channel
            if (doHyperlinks && extractedText.lastIndexOf("<a", pos ) > extractedText.lastIndexOf("</a>", pos))
            {
                ++pos;
                continue;
            }

            protocol.clear();
            href = extractedText.mid(pos, urlLen);
            append.clear();

            // Don't consider trailing comma part of link.
            if (href.right(1) == ",")
            {
                href.truncate(href.length()-1);
                append = ',';
            }

            // Don't consider trailing semicolon part of link.
            if (href.right(1) == ";")
            {
                href.truncate(href.length()-1);
                append = ';';
            }

            // Don't consider trailing closing parenthesis part of link when
            // there's an opening parenthesis preceding the beginning of the
            // URL or there is no opening parenthesis in the URL at all.
            if (href.right(1) == ")" && (extractedText.mid(pos-1, 1) == "(" || !href.contains("(")))
            {
                href.truncate(href.length()-1);
                append.prepend(")");
            }

            if (doHyperlinks)
            {
                // Qt doesn't support (?<=pattern) so we do it here
                if ((pos > 0) && extractedText[pos-1].isLetterOrNumber())
                {
                    pos++;
                    continue;
                }

                if (URL_PATTERN.cap(1).startsWith(QLatin1String("www."), Qt::CaseInsensitive))
                    protocol = "http://";
                else if (URL_PATTERN.cap(1).isEmpty())
                    protocol = "mailto:";

                // Use \x0b as a placeholder for & so we can read them after changing all & in the normal text to &amp;
                insertText = link.arg(protocol, QString(href).replace('&', "\x0b"), href) + append;

                extractedText.replace(pos, urlLen, insertText);
            }
            else
                insertText = href + append;

                pos += insertText.length();
        }

        if (doHyperlinks)
        {
            // Change & to &amp; to prevent html entities to do strange things to the text
            extractedText.replace('&', "&amp;");
            extractedText.replace("\x0b", "&");
        }

        // kDebug() << "Took (msecs) : " << timer.elapsed() << " for " << extractedText;

        return extractedText;
    }
Example #3
0
void UpdateView::unfoldSelectedFolders()
{
    QApplication::setOverrideCursor(Qt::WaitCursor);

    int previousDepth = 0;
    bool isUnfolded = false;

    QStringList selection = multipleSelection();

    // setup name of selected folder
    QString selectedItem = selection.first();
    if( selectedItem.contains('/') )
        selectedItem.remove(0, selectedItem.lastIndexOf('/')+1);

    // avoid flicker
    const bool _updatesEnabled = updatesEnabled();
    setUpdatesEnabled(false);

    Q3ListViewItemIterator it(this);
    while( Q3ListViewItem* item = it.current() )
    {
        if( isDirItem(item) )
        {
            UpdateDirItem* dirItem = static_cast<UpdateDirItem*>(item);

            // below selected folder?
            if( previousDepth && dirItem->depth() > previousDepth )
            {
                // if this dir wasn't scanned already scan it recursive
                // (this is only a hack to reduce the processEvents() calls,
                // setOpen() would scan the dir too)
                if (dirItem->wasScanned() == false)
                {
                    const bool recursive = true;
                    dirItem->maybeScanDir(recursive);

                    // scanning can take some time so keep the gui alive
                    qApp->processEvents();
                }

                dirItem->setOpen(!isUnfolded);
            }
            // selected folder?
            else if( selectedItem == dirItem->entry().m_name )
            {
                previousDepth = dirItem->depth();
                isUnfolded = dirItem->isOpen();

                // if this dir wasn't scanned already scan it recursive
                // (this is only a hack to reduce the processEvents() calls,
                // setOpen() would scan the dir too)
                if (dirItem->wasScanned() == false)
                {
                    const bool recursive = true;
                    dirItem->maybeScanDir(recursive);

                    // scanning can take some time so keep the gui alive
                    qApp->processEvents();
                }

                dirItem->setOpen(!isUnfolded);
            }
            // back to the level of the selected folder or above?
            else if( previousDepth && dirItem->depth() >= previousDepth )
            {
                previousDepth = 0;
            }
        }

        ++it;
    }

    // maybe some UpdateDirItem was opened the first time so check the whole tree
    setFilter(filter());

    setUpdatesEnabled(_updatesEnabled);
    triggerUpdate();

    QApplication::restoreOverrideCursor();
}
Example #4
0
BookmarkItem* HtmlImporter::importBookmarks()
{
    QString bookmarks = QString::fromUtf8(m_file.readAll());
    m_file.close();

    // Converting tags to lower case -,-
    // For some reason Qt::CaseInsensitive is not everytime insensitive :-D

    bookmarks.replace(QLatin1String("<DL"), QLatin1String("<dl"));
    bookmarks.replace(QLatin1String("</DL"), QLatin1String("</dl"));
    bookmarks.replace(QLatin1String("<DT"), QLatin1String("<dt"));
    bookmarks.replace(QLatin1String("</DT"), QLatin1String("</dt"));
    bookmarks.replace(QLatin1String("<P"), QLatin1String("<p"));
    bookmarks.replace(QLatin1String("</P"), QLatin1String("</p"));
    bookmarks.replace(QLatin1String("<A"), QLatin1String("<a"));
    bookmarks.replace(QLatin1String("</A"), QLatin1String("</a"));
    bookmarks.replace(QLatin1String("HREF="), QLatin1String("href="));
    bookmarks.replace(QLatin1String("<H3"), QLatin1String("<h3"));
    bookmarks.replace(QLatin1String("</H3"), QLatin1String("</h3"));

    bookmarks = bookmarks.left(bookmarks.lastIndexOf(QLatin1String("</dl><p>")));
    int start = bookmarks.indexOf(QLatin1String("<dl><p>"));

    BookmarkItem* root = new BookmarkItem(BookmarkItem::Folder);
    root->setTitle("HTML Import");

    QList<BookmarkItem*> folders;
    folders.append(root);

    while (start > 0) {
        QString string = bookmarks.mid(start);

        int posOfFolder = string.indexOf(QLatin1String("<dt><h3"));
        int posOfEndFolder = string.indexOf(QLatin1String("</dl><p>"));
        int posOfLink = string.indexOf(QLatin1String("<dt><a"));

        int nearest = qzMin(posOfLink, qzMin(posOfFolder, posOfEndFolder));
        if (nearest == -1) {
            break;
        }

        if (nearest == posOfFolder) {
            // Next is folder
            QzRegExp rx("<dt><h3(.*)>(.*)</h3>");
            rx.setMinimal(true);
            rx.indexIn(string);

//            QString arguments = rx.cap(1);
            QString folderName = rx.cap(2).trimmed();

            BookmarkItem* folder = new BookmarkItem(BookmarkItem::Folder, folders.isEmpty() ? root : folders.last());
            folder->setTitle(folderName);
            folders.append(folder);

            start += posOfFolder + rx.cap(0).size();
        }
        else if (nearest == posOfEndFolder) {
            // Next is end of folder
            if (!folders.isEmpty()) {
                folders.removeLast();
            }

            start += posOfEndFolder + 8;
        }
        else {
            // Next is link
            QzRegExp rx("<dt><a(.*)>(.*)</a>");
            rx.setMinimal(true);
            rx.indexIn(string);

            QString arguments = rx.cap(1);
            QString linkName = rx.cap(2).trimmed();

            QzRegExp rx2("href=\"(.*)\"");
            rx2.setMinimal(true);
            rx2.indexIn(arguments);

            QUrl url = QUrl::fromEncoded(rx2.cap(1).trimmed().toUtf8());

            start += posOfLink + rx.cap(0).size();

            if (linkName.isEmpty() || url.isEmpty() || url.scheme() == QLatin1String("place")
                    || url.scheme() == QLatin1String("about")) {
                continue;
            }

            BookmarkItem* b = new BookmarkItem(BookmarkItem::Url, folders.isEmpty() ? root : folders.last());
            b->setTitle(linkName);
            b->setUrl(url);
        }
    }

    return root;
}
Example #5
0
void CeguiInject::InitReg() {
    // 初始化验证
    std::string LicenseKey, v_rsamod, v_rsapubkey;
    std::string v_pccode, s_notice;
    _int32 v_cstime, v_is2svr;
    // ★★★★★★如若你觉得验证模块取的机器码不够安全或经常变动,你可以自己写函数取机器码这个变量,要求最少五个字符,否则请留空
    v_pccode = __TEXT("");

    // ★★★★★★记录日志数据的文件 c:\kss.ini
    char dllname[MAX_PATH];
    GetModuleFileName(NULL, dllname, MAX_PATH);
    std::string strDll = dllname;
    //QString qstrDll = QString::fromStdString(strDll); // 此用法会造成中文乱码
    QString qstrDll = QString::fromLocal8Bit(strDll.c_str());
    QString strSplit = "\\";
    int index = qstrDll.lastIndexOf(strSplit);
    qstrDll = qstrDll.left(index);
    //strDll = qstrDll.toStdString(); // 此用法会造成程序崩溃
    std::string strIniPath = std::string((const char*)qstrDll.toLocal8Bit());
    strIniPath += TEXT("\\kss.ini");
    v_inipath = strIniPath;

    // ★★★★★★连接服务器超时默认为6000毫秒
    v_cstime = 31 * 1000;

    // ★★★★★★如果你装有验证备服,这里请填1,否则填0
    v_is2svr = 0;

    // ★★★★★★此参数请查阅管理端【软件列表】里[软件编号]的值
    v_softcode = 1000004;

    // ★★★★★★此参数请查阅管理端【软件列表】里[软件密钥]的值
    v_softkey = "Kq48cq8t1rqAkjYarYmC8KsP";

    //★★★★★★ 800商业版用户,下边两个参数设置请参见 http://www.hphu.com/news_14.html
    //五元服作者和体验用户请不要修改RSA参数
    /*    v_rsamod = __TEXT("80994089576198245488509154749313953201376381432243611978096896085511546099913");  // v_rsa mod = __TEXT("") 就是关闭RSA功能,服务端也应关闭RSA
    v_rsapubkey = __TEXT("65537");  //v_rsapubkey = __TEXT("")  就是关闭RSA功能,服务端也应关闭RSA*/
    v_rsamod = "56591083613825005903100788459095430353163052008239248775218519910075636714049";  // v_rsa mod = __TEXT("") 就是关闭RSA功能,服务端也应关闭RSA
    v_rsapubkey = "130859";  //v_rsapubkey = __TEXT("")  就是关闭RSA功能,服务端也应关闭RSA

    // ★★★★★★ 该数据从管理端获取后设置到这里:【软件列表】->右上角【新签名数据】按钮单击即可获取。
    signData = "";
    signData += "a4d2bd9314324ad47f748acf6d2d34504d38550fc7259cfd2d37c7a7678db6bd9cdb86cdb868f51582b82ff6eaa0e7e53d84";
    signData += "74df93827e4b07f8a50d295dd0ddd35ea1b69a510e9dda2a398b47b6de07f47cbd4e3a9889abea8c8ac2b45643190314c501";
    signData += "589219d7559eb2f02db5edf81ce9f0bb508faf6ea974c7b3bc813e84d54cc8ed68984fbfdb717822fd3c0fcc4db0d4eeb8e0";
    signData += "8dfbe6c3d7b83b3f5262ed2efa4107b424d848a445c7c235ada498661e5ec71ce5439d4c7078a8f90c52dca80b29ceac3c46";
    signData += "be3a7abf9dbd5145a0bdeffb4fd43fbfd17861acc75753a5f13df5145e6207f56471f3d6a91c0401b86de7a589b86001724f";
    signData += "6ab5b7fdd091c37af893889d98cb544931a4f591a96be5db264b744fc6b10f84ffac726a57fe446c668defa104ec06e4a62c";
    signData += "a3d1a70052872b9cd6040abcb61116b3c76fadd53ce6779f35087eb9fd50dc680d80ce76f96c9584de8a81be555ef2c8b92c";
    signData += "505db2246d37c6051543b70bc7b804d0e0636cb879bd874cd5ddc1bef4a0613415c8acf002ffdbcf64c23a07974d54258e7a";

    v_bdinfo = "";           // 用户的绑定信息。
    // 1、如果这里的值不为空,该数据会由服务端效验,也就是说如果服务端数据库里相应用户的绑定信息与该值不相同,会被服务端认为非法,也就是验证不能通过。
    // 2、如果这里的值为空,登陆成功后通过ks_GetData (4)取得服务器返回的用户绑定信息,也就是说你可以用ks_GetData (4)的值来处理你自己的应用。

    //★★★★★★ 800商业版用户,下边的参数里的字符串请修改为你自己的LicenseKey
    //五元服作者和体验用户请不要修改该参数
    LicenseKey = "";
    LicenseKey += "q6pEBYnyqtXar6uPbSTzmTXIL25+i4ouvmcSRzgVDwF/RL4XqmFoxB5I5kl8Tm3OR7G76cEnIH3A5CLL";
    LicenseKey += "XLAXm3eUh5cgEu9y7smCUUwt+o+Z67TqVv9EKUesgy7Q2ZpJh5XExlxf1zo9+5xmM9FFIx2isYXhg9gu";
    LicenseKey += "zD4rwg9L+er0HuSbmqlmpQLqS2OlN/z/Z4ByNp4XuahZmD8KOfUBIMXkX0ImxU79Dez4qvt7uZFZQeM3";
    LicenseKey += "dwPo7cjrvuo0prmKBJYTtlfrX9Dq+dGNorYjE6EsFnF3DKlfRdzGUWoS9IGrRdI37UZFHYoBVWfJl0Ry";
    LicenseKey += "2qUZVbiHkptKTH7lSKjnSSRHzto5QWVm/qdtDRfLR18lIQKJo7aAfvmkgWyEvVTt6l2UuVuxs6PUW4XK";
    LicenseKey += "Jfa5CgD0eeC7ICQmTAZ8AyH1SthbcvKF8aA1u5cMEizB0XRxKMyXP/bYKOqOftPbBQILj9Ya1Xo6NWwQ";
    LicenseKey += "9K6gZBdHy9y3OAj0D1gbhOuoHFeVO//2QJfhZ3H7bzeXtA5UI/rimJXMHCko2qoypXLa3z33KjSsCNfL";
    LicenseKey += "SaW1ALhe6Yz05joWKLBV5kxpFDzlbY9246ej29kEukVEqd0bAPDmLxknof4Wi3YDE/6kZ3erhBD0rH0Q";
    LicenseKey += "Av4ELHBuUsLTomIcQVTqlA+qKzHcVs0x8cRuUtfS+Mp6giLJZAvRS7oTYvCnhkJa+V9bXjV0msYIKivh";
    LicenseKey += "I4xYiSVu1sVntQvori5I0dAr0NoPwf157udfIa7d/SrgaFl8gvoWfUt56r5gkKNRDoR/EianEY8Np4Wa";
    LicenseKey += "SOFisKZqTB9MNkFnoWLfNz0G/B49uf/qEOONhIpAmrLprRfgYRWKFiSXU1xhbzbNPEZ88w0FLZQPWDP3";
    LicenseKey += "58dybdT7Z3N4Si+IIwrXJZV/DnsorJMlTEWJsztZOOh2yw96C229FwKrdKAkpGZPomfeFOmNduDG9KNA";
    LicenseKey += "YZ7DIZSn27PJOtO0vZ5GL1pciOGjGbxSyzXShvk41tEv9HFtNagDaVlWjIsN9iSuacSCFmEmxyvgIZDX";
    LicenseKey += "ANM64Jz31sthq+m3iNTZuy7xKcN+bFJJmpqVVYBk62YrIvbG0hlRNXx7XgPxaJ1Dh0IQTqgRzJYG/+bq";
    LicenseKey += "Rvdz3k7GAMmLkQk6dQsQEISX8lT5diZ4jSoYF+c7j3TBNrvKNdxIEbXr903+gDvno6zyvqnwtY2q/sX6";
    LicenseKey += "/FbNTz9zJV8f6Hh9dlhBiXUrkT3hGVWgBXIoNx2n4yv7ruhmrZ8xGjnKd5OTyZnvUkMZJuweKBg2AMsq";
    LicenseKey += "Y7jHM8o/KoOqeA0fv1QGpd2I7ZFAo8Nr/g1gnnJ18ybTvJ/zQ1QQlcsmOyAPYJx5keH4wbTvGn15zmtm";
    LicenseKey += "XW3TzZ6Rm6ORpTYL8JTlo+nWHwCupQbirkouByZJx+RuG0XIGYelS6W3TGtNDDM3/eOZbj9C4xgL+fkq";
    LicenseKey += "GDzfVz/8pWGt7ZTeJ+EDDzlEwUF6d+MXH5a5SxWNgbS3ZhZY5sp8I5D/ANe5YETCP4lc32ck1HbbrFt8";
    LicenseKey += "Jwyz2QFNrMZqq6R8VpQsEdRDEyJA80RNqO33N2RNa6f9TceRVZ2o/amPyo8xzvzgnaA4Vbk0tAYvrS7M";
    LicenseKey += "BlukmT7iOJE0wjHuwhBWvbstGjKCKefPcbKekdYWnnx+sfuAd+W47Gyp9WrD1K6XMsGRWWH5K6d3BD8n";
    LicenseKey += "HEsLFVDXLJ5s5GwY+559KXbqZQ==";

    //KS授权信息
    ks_setLicense((LPSTR)LicenseKey.c_str());

    //初始化扩展参数,一般情况下无需修改
    ks_setExtVal(0, (LPSTR)v_pccode.c_str()
        , (LPSTR)v_inipath.c_str()
        , v_cstime, v_is2svr, (LPSTR)v_rsamod.c_str()
        , (LPSTR)v_rsapubkey.c_str()
        , "", "", "");

    // 无论调用多少次ks_GetData(参数大于10000000),只会连接一次网络(无论参数是否相同)
    // 以下五行代码视你具体需求,你可以决定是否保留
    // s_isup = ks_GetData(v_softcode * 10 + 1);   //服务端软件是否强制更新
    // s_version = ks_GetData(v_softcode * 10 + 2);  //服务端软件版本
    // s_downurl = ks_GetData(v_softcode * 10 + 3);   //服务端软件下载地址
    s_notice = ks_GetData(v_softcode * 10 + 4);  //服务端软件公告
    s_notice = TEXT("公告: ") + s_notice;
    // MsgBox(s_notice);
}
Example #6
0
/*!
    Fetch extended information for all \a filePath

    \sa fetchExtendedInformation()
*/
void RemoteFileInfoGatherer::updateFile(const QString &filePath)
{
    QString dir = filePath.mid(0, filePath.lastIndexOf(QLatin1Char('/')));
    QString fileName = filePath.mid(dir.length() + 1);
    fetchExtendedInformation(dir, QStringList(fileName));
}
Example #7
0
void INDI_E::browseBlob()
{

    QFile fp;
    QString filename;
    QString format;
    QDataStream binaryStream;
    int data64_size=0, pos=0;
    unsigned char *data_file;
    KUrl currentURL;

    currentURL = KFileDialog::getOpenUrl( QDir::homePath(), "*");

    // if user presses cancel
    if (currentURL.isEmpty())
        return;

    if ( currentURL.isValid() )
        write_w->setText(currentURL.path());

    fp.setFileName(currentURL.path());

    if ( (pos = filename.lastIndexOf(".")) != -1)
        format = filename.mid (pos, filename.length());

    //qDebug() << "Filename is " << fp.fileName() << endl;

    if (!fp.open(QIODevice::ReadOnly))
    {
        KMessageBox::error(0, i18n("Cannot open file %1 for reading", filename));
        return;
    }

    binaryStream.setDevice(&fp);

    data_file = new unsigned char[fp.size()];

    bp->bloblen = fp.size();

    if (data_file == NULL)
    {
        KMessageBox::error(0, i18n("Not enough memory to load %1", filename));
        fp.close();
        return;
    }

    binaryStream.readRawData((char*)data_file, fp.size());

    bp->blob = new unsigned char[4*fp.size()/3+4];
    if (bp->blob == NULL)
    {
        KMessageBox::error(0, i18n("Not enough memory to convert file %1 to base64", filename));
        fp.close();
    }

    data64_size = to64frombits ( ((unsigned char *) bp->blob), data_file, fp.size());

    delete [] data_file;

    bp->size = data64_size;

    //qDebug() << "BLOB " << bp->name << " has size of " << bp->size << " and bloblen of " << bp->bloblen << endl;

    blobDirty = true;

}
Example #8
0
void ThemeModel::reload()
{
    reset();
    clearThemeList();

    // get all desktop themes
    QStringList themes = KGlobal::dirs()->findAllResources("data",
                                                            "aurorae/themes/*/metadata.desktop",
                                                            KStandardDirs::NoDuplicates);
    foreach(const QString &theme, themes) {
        int themeSepIndex = theme.lastIndexOf('/', -1);
        QString themeRoot = theme.left(themeSepIndex);
        int themeNameSepIndex = themeRoot.lastIndexOf('/', -1);
        QString packageName = themeRoot.right(themeRoot.length() - themeNameSepIndex - 1);

        KDesktopFile df(theme);
        QString name = df.readName();
        if (name.isEmpty()) {
            name = packageName;
        }
        QString comment = df.readComment();
        QString author = df.desktopGroup().readEntry("X-KDE-PluginInfo-Author", QString());
        QString email = df.desktopGroup().readEntry("X-KDE-PluginInfo-Email", QString());
        QString version = df.desktopGroup().readEntry("X-KDE-PluginInfo-Version", QString());
        QString license = df.desktopGroup().readEntry("X-KDE-PluginInfo-License", QString());
        QString website = df.desktopGroup().readEntry("X-KDE-PluginInfo-Website", QString());


        Plasma::FrameSvg *svg = new Plasma::FrameSvg(this);
        QString svgFile = themeRoot + "/decoration.svg";
        if (QFile::exists(svgFile)) {
            svg->setImagePath(svgFile);
        } else {
            svg->setImagePath(svgFile + 'z');
        }
        svg->setEnabledBorders(Plasma::FrameSvg::AllBorders);

        ThemeConfig *config = new ThemeConfig();
        KConfig conf("aurorae/themes/" + packageName + '/' + packageName + "rc", KConfig::FullConfig, "data");
        config->load(&conf);

        // buttons
        QHash<QString, Plasma::FrameSvg*> *buttons = new QHash<QString, Plasma::FrameSvg*>();
        initButtonFrame("minimize", packageName, buttons);
        initButtonFrame("maximize", packageName, buttons);
        initButtonFrame("restore", packageName, buttons);
        initButtonFrame("close", packageName, buttons);
        initButtonFrame("alldesktops", packageName, buttons);
        initButtonFrame("keepabove", packageName, buttons);
        initButtonFrame("keepbelow", packageName, buttons);
        initButtonFrame("shade", packageName, buttons);
        initButtonFrame("help", packageName, buttons);

        ThemeInfo info;
        info.package = packageName;
        info.description = comment;
        info.author = author;
        info.email = email;
        info.version = version;
        info.website = website;
        info.license = license;
        info.svg = svg;
        info.themeRoot = themeRoot;
        info.themeConfig = config;
        info.buttons = buttons;
        m_themes[name] = info;
    }
/**
 * Load vertices data from a OBJ file.
 */
void OBJLoader::load(const char* filename, std::vector<Vertex>& vertices) {
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly)) {
        return;
    }

    QTextStream in(&file);

    std::vector<float> raw_vertices;
    std::vector<float> raw_normals;
    std::vector<float> raw_texCoords;
    std::vector<unsigned int> v_elements;
    std::vector<unsigned int> t_elements;
    std::vector<unsigned int> n_elements;

    while (!in.atEnd()) {
        QString line = in.readLine();
        if (line.startsWith("v ")) {
            int index1 = line.indexOf(QRegExp("[0-9\\.\\-]"), 2);
            int index2 = line.lastIndexOf(QRegExp("[0-9]"));
            QStringList values = line.mid(index1, index2 - index1 + 1).split(" ");
            raw_vertices.push_back(values[0].toFloat());
            raw_vertices.push_back(values[1].toFloat());
            raw_vertices.push_back(values[2].toFloat());
        } else if (line.startsWith("vn ")) {
            int index1 = line.indexOf(QRegExp("[0-9\\.\\-]"), 2);
            int index2 = line.lastIndexOf(QRegExp("[0-9]"));
            QStringList values = line.mid(index1, index2 - index1 + 1).split(" ");
            raw_normals.push_back(values[0].toFloat());
            raw_normals.push_back(values[1].toFloat());
            raw_normals.push_back(values[2].toFloat());
        } else if (line.startsWith("vt ")) {
            int index1 = line.indexOf(QRegExp("[0-9\\.\\-]"), 2);
            int index2 = line.lastIndexOf(QRegExp("[0-9]"));
            QStringList values = line.mid(index1, index2 - index1 + 1).split(" ");
            raw_texCoords.push_back(values[0].toFloat());
            raw_texCoords.push_back(values[1].toFloat());
        } else if (line.startsWith("f ")) {
            int index1 = line.indexOf(QRegExp("[0-9]"), 2);
            int index2 = line.lastIndexOf(QRegExp("[0-9]"));
            QStringList values = line.mid(index1, index2 - index1 + 1).split(" ");
            for (int i = 0; i < values.size() - 2; ++i) {
                unsigned int a,b,c;
                a = values[0].split("/")[0].toUInt() - 1;
                b = values[i+1].split("/")[0].toUInt() - 1;
                c = values[i+2].split("/")[0].toUInt() - 1;
                v_elements.push_back(a);
                v_elements.push_back(b);
                v_elements.push_back(c);

                if (values[0].split("/").size() >= 2 && values[0].split("/")[1].size() > 0) {
                    a = values[0].split("/")[1].toUInt() - 1;
                    b = values[i+1].split("/")[1].toUInt() - 1;
                    c = values[i+2].split("/")[1].toUInt() - 1;
                    t_elements.push_back(a);
                    t_elements.push_back(b);
                    t_elements.push_back(c);
                }

                if (values[0].split("/").size() >= 3 && values[0].split("/")[2].size() > 0) {
                    a = values[0].split("/")[2].toUInt() - 1;
                    b = values[i+1].split("/")[2].toUInt() - 1;
                    c = values[i+2].split("/")[2].toUInt() - 1;
                    n_elements.push_back(a);
                    n_elements.push_back(b);
                    n_elements.push_back(c);
                }
            }
        } else if (line.size() == 0) {
            /* ignore empty line */
        } else if (line.startsWith("#")) {
            /* ignore comment line */
        } else {
            /* ignore this line */
        }
    }

    vertices.resize(v_elements.size());
    for (int i = 0; i < v_elements.size(); i+=3) {
        unsigned int ia = v_elements[i];
        unsigned int ib = v_elements[i+1];
        unsigned int ic = v_elements[i+2];

        for (int j = 0; j < 3; ++j) {
            vertices[i].position[j] = raw_vertices[ia*3 + j];
            vertices[i+1].position[j] = raw_vertices[ib*3 + j];
            vertices[i+2].position[j] = raw_vertices[ic*3 + j];
        }

        if (n_elements.size() > 0) {
            for (int j = 0; j < 3; ++j) {
                vertices[i].normal[j] = raw_normals[n_elements[i]*3 + j];
                vertices[i+1].normal[j] = raw_normals[n_elements[i+1]*3 + j];
                vertices[i+2].normal[j] = raw_normals[n_elements[i+2]*3 + j];
            }
        } else {
            glm::vec3 normal = glm::cross(
                                   glm::vec3(raw_vertices[ib*3], raw_vertices[ib*3+1], raw_vertices[ib*3+2]) - glm::vec3(raw_vertices[ia*3], raw_vertices[ia*3+1], raw_vertices[ia*3+2]),
                                   glm::vec3(raw_vertices[ic*3], raw_vertices[ic*3+1], raw_vertices[ic*3+2]) - glm::vec3(raw_vertices[ia*3], raw_vertices[ia*3+1], raw_vertices[ia*3+2]));
            normal = glm::normalize(normal);

            for (int j = 0; j < 3; ++j) {
                vertices[i].normal[j] = j == 0 ? normal.x : (j == 1 ? normal.y : normal.z);
                vertices[i+1].normal[j] = j == 0 ? normal.x : (j == 1 ? normal.y : normal.z);
                vertices[i+2].normal[j] = j == 0 ? normal.x : (j == 1 ? normal.y : normal.z);
            }
        }

        if (t_elements.size() > 0) {
            for (int j = 0; j < 2; ++j) {
                vertices[i].texCoord[j] = raw_texCoords[t_elements[i]*2 + j];
                vertices[i+1].texCoord[j] = raw_texCoords[t_elements[i+1]*2 + j];
                vertices[i+2].texCoord[j] = raw_texCoords[t_elements[i+2]*2 + j];
            }
        } else {
            for (int j = 0; j < 3; ++j) {
                vertices[i].texCoord[j] = 0.0f;
                vertices[i+1].texCoord[j] = j == 0 ? 1.0f : 0.0f;
                vertices[i+2].texCoord[j] = j == 0 ? 0.0f : 1.0f;
            }
        }

        // assign some colors
        for (int j = 0; j < 3; ++j) {
            vertices[i].color[j] = 1.0f;
            vertices[i+1].color[j] = 1.0f;
            vertices[i+2].color[j] = 1.0f;
        }
    }
}
Example #10
0
/**
 * Take a QString and load it into the Entry as appropriate
 * The format is basically: KANJI [KANA] /(general information) gloss/gloss/.../
 * Note that they can rudely place more (general information) in gloss's that are
 * not the first one.
 */
bool EntryEdict::loadEntry( const QString &entryLine )
{
  /* Set tempQString to be the reading and word portion of the entryLine */
  int endOfKanjiAndKanaSection = entryLine.indexOf( '/' );
  if( endOfKanjiAndKanaSection == -1 )
  {
    return false;
  }
  QString tempQString = entryLine.left( endOfKanjiAndKanaSection );
  /* The actual Word is the beginning of the line */
  int endOfKanji = tempQString.indexOf( ' ' );
  if( endOfKanji == -1 )
  {
    return false;
  }
  Word = tempQString.left( endOfKanji );

  /* The Reading is either Word or encased in '[' */
  Readings.clear();
  int startOfReading = tempQString.indexOf( '[' );
  if( startOfReading != -1 )  // This field is optional for EDICT (and kiten)
  {
    Readings.append( tempQString.left( tempQString.lastIndexOf( ']' ) ).mid( startOfReading + 1 ) );
  }
  /* TODO: use this code or not?
  * app does not handle only reading and no word entries
  * very well so far
  else
  {
    Readings.append(Word);
    Word.clear();
  }
  */

  /* set Meanings to be all of the meanings in the definition */
  QString remainingLine = entryLine.mid( endOfKanjiAndKanaSection );
  //Trim to last '/'
  remainingLine = remainingLine.left( remainingLine.lastIndexOf( '/' ) );
  Meanings = remainingLine.split( '/', QString::SkipEmptyParts );

  if( Meanings.size() == 0 )
  {
    return false;
  }

  if( Meanings.last() == "(P)" )
  {
    ExtendedInfo[ QString( "common" ) ] = "1";
    Meanings.removeLast();
  }

  QString firstWord = Meanings.first();
  QStringList stringTypes;

  //Pulls the various types out
  //TODO: Remove them from the original string
  for ( int i = firstWord.indexOf( "(" );
        i != -1;
        i = firstWord.indexOf( "(", i + 1 ) )
  {
    QString parantheses = firstWord.mid( i + 1, firstWord.indexOf( ")", i ) - i - 1 );
    stringTypes += parantheses.split( ',' );
  }

  foreach( const QString &str, stringTypes )
  {
    if( EdictFormatting::PartsOfSpeech.contains( str ) )
    {
      m_types += str;
    }
    else if( EdictFormatting::FieldOfApplication.contains( str ) )
    {
      ExtendedInfo[ "field" ] = str;
    }
    else if( EdictFormatting::MiscMarkings.contains( str ) )
    {
      m_miscMarkings += str;
    }
  }

  return true;
}
Example #11
0
void MainWindow::SetADirectoryCMakeListFile(QString current_dir, QString cmakelists_file, QList<QString> sub_lists, bool root)// A directory
{
    QString str;
    qDebug()<<cmakelists_file;
    QFile cmake_config_file(cmakelists_file);

    cmake_config_file.open(QIODevice::ReadWrite);

    bool status = cmake_config_file.isOpen();

    if(cmake_config_file.isOpen())
    {
        QString last_dir_name = current_dir.right(current_dir.length()- current_dir.lastIndexOf("/")-1);
        QString source_dir_argv =  last_dir_name + "SRC" ;

        QString include_dir_argv = last_dir_name + "INCLUDE_DIR";




        str = cmake_build::cmake_minimum_required("VERSION 3.10");
        cmake_config_file.write(str.toLatin1());
        cmake_config_file.write("\n");

        if(root)
        str = cmake_build::project(this->project_config.project_name);
        else
        str = cmake_build::project(last_dir_name);

            cmake_config_file.write(str.toLatin1());
            cmake_config_file.write("\n");

          //  QString RelativePath =  GetRelativePath(current_dir);
            str = cmake_build::aux_source_directory(current_dir,source_dir_argv,CMAKE_STRING);
            qDebug()<<str;
            cmake_config_file.write(str.toLatin1());
            cmake_config_file.write("\n");

    //set_include
            str.clear();
            QString include_argv = "INCLUDE_DIR";
            str = cmake_build::set(include_dir_argv,source_dir_argv,CMAKE_ARGV);
            qDebug()<<str;
            cmake_config_file.write(str.toLatin1());
            cmake_config_file.write("\n");


            str.clear();
            str = cmake_build::include_directories(include_dir_argv,CMAKE_ARGV);
            qDebug()<<str;
            cmake_config_file.write(str.toLatin1());
            cmake_config_file.write("\n");

            qDebug()<<"ERootProjectTypeKKKKKKKKKKKKKKK"<<project_config.project_type;

            if(project_config.project_type == ERootProjectType::EXEC)
            {
               if(root)
               {
                   str.clear();
                   str = cmake_build::add_executable(cmake_build::exec_name,source_dir_argv,CMAKE_ARGV);
                   qDebug()<<str;
                   cmake_config_file.write(str.toLatin1());
                   cmake_config_file.write("\n");
               }else
               {
                   str.clear();
                   qDebug()<<"KKKKK"<<project_config.sub_lib_type;
                   if(project_config.sub_lib_type == ESubLibType::SUB_LIB_STATIC)
                       str =  cmake_build::add_library(current_dir,source_dir_argv,CMAKE_ARGV,STATIC);
                   else if(project_config.sub_lib_type == ESubLibType::SUB_LIB_SHARED)
                       str =  cmake_build::add_library(current_dir,source_dir_argv,CMAKE_ARGV,SHARED);
                   qDebug()<<str;
                   cmake_config_file.write(str.toLatin1());
                   cmake_config_file.write("\n");
               }
            }




            if(project_config.project_type == ERootProjectType::LIB)
            {
                str.clear();
                if(project_config.root_lib_type == ERootLibType::ROOT_LIB_STATIC)
                    str =  cmake_build::add_library(current_dir,source_dir_argv,CMAKE_ARGV,STATIC);
                else
                    str =  cmake_build::add_library(current_dir,source_dir_argv,CMAKE_ARGV,SHARED);
                qDebug()<<str;
                cmake_config_file.write(str.toLatin1());
                cmake_config_file.write("\n");
            }


            ///******************************* 添加 第三方 库 *******************************
            ///
                if(sub_lists.length() <= 0)
                {

                    for(QStringList::iterator it = this->other_includes.begin();it != other_includes.end();it++)
                    {
                        str.clear();
                        str = cmake_build::include_directories(*it,CMAKE_STRING);
                        qDebug()<<str;
                        cmake_config_file.write(str.toLatin1());
                        cmake_config_file.write("\n");
                    }


                    for(QStringList::iterator it = this->other_libs.begin();it != other_libs.end();it++)
                    {
                        str.clear();
                        str = cmake_build::target_link_libraries(this->project_config.project_name,*it);
                        qDebug()<<str;
                        cmake_config_file.write(str.toLatin1());
                        cmake_config_file.write("\n");
                    }

                }

           //******************************** 添加 第三方 库 **************************/


            str.clear();
            if(sub_lists.length() > 0)
            for(int i =0;i<sub_lists.size();i++)
            {

                str = cmake_build::target_link_libraries(this->project_config.project_name,sub_lists.at(i),CMAKE_STRING);
                qDebug()<<str;
                cmake_config_file.write(str.toLatin1());
                cmake_config_file.write("\n");
            }


            // /*************************** 添加第三方链接库 **************************
              // //添加第三方库 使用find_ 不要使用link_directories() 使用此方法的时候 会出现找不到指定路径的库
        //*************************** 添加第三方链接库 ****************************/








    //add_sub
            if(sub_lists.length() > 0)
            {
                qDebug()<<"*****************************"<<sub_lists.length();
                for(int i = 0;i<sub_lists.size();i++)
                {
                    str.clear();

                    //QString RelativePath =  GetRelativePath(sub_lists.at(i));
                    str = cmake_build::add_subdirectory(sub_lists.at(i),CMAKE_STRING);
                    qDebug()<<str;
                    cmake_config_file.write(str.toLatin1());
                    cmake_config_file.write("\n");
                }
            }
    }
    cmake_config_file.close();
}
Example #12
0
void DocumentEditor::toggleComment(bool lineCommentPrefered_) {
	QsciLexer* l = lexer();
	if(l == 0)
		return;
	QString comment = l->commentLine();
	QStringList commentBlock = l->commentBlock();

	if(comment.isEmpty() && commentBlock.isEmpty()){
		qDebug() << "Toggle comment is not supported for " << l->language();
		return;
	}

	if (!hasSelectedText()) {
		//if line is empty, skip it
		int line = getCurrentLine();
		if (isLineEmpty(line))
			return;

		QString selText = text(line);
		selText.remove("\n");
		selText.remove("\r");
		QString selTextTrimmed = selText.trimmed();
		int pos_start = SendScintilla(SCI_POSITIONFROMLINE, line);
		int pos_end = SendScintilla(SCI_GETLINEENDPOSITION, line);

		// check for block comments on a line
		if(commentBlock.size() >= 2){
			QString blockStart = commentBlock.first();
			QString blockEnd = commentBlock.last();
			if (selTextTrimmed.startsWith(blockStart) && selTextTrimmed.endsWith(blockEnd)) {
				beginUndoAction();

				int idx1 = selText.indexOf(blockStart);
				selText.remove(idx1, blockEnd.size());
				int idx2 = selText.lastIndexOf(blockEnd);
				selText.remove(idx2, blockEnd.size());

				SendScintilla(SCI_SETTARGETSTART, pos_start);
				SendScintilla(SCI_SETTARGETEND, pos_end);
				SendScintilla(SCI_REPLACETARGET, -1, selText.toUtf8().data());

				endUndoAction();
				return;
			}
		}

		// check for single comments
		if (!comment.isEmpty()) {
			if (selTextTrimmed.startsWith(comment)) {
				// remove comment
				int idx = selText.indexOf(comment);
				selText = selText.remove(idx, comment.size());
			} else {
				// set comment
				selText = selText.prepend(comment);
			}

			SendScintilla(SCI_SETTARGETSTART, pos_start);
			SendScintilla(SCI_SETTARGETEND, pos_end);
			SendScintilla(SCI_REPLACETARGET, -1, selText.toUtf8().data());
			return;
		}

	}else{
		// comment out the selection
		QString selText = selectedText();
		QString selTextTrimmed = selText.trimmed();
		if (selTextTrimmed.isEmpty())
			return;

		int lineFrom, lineTo, indexFrom, indexTo;
		getSelection(&lineFrom, &indexFrom, &lineTo, &indexTo);

		int pos_start = positionFromLineIndex(lineFrom, indexFrom);
		int pos_end = positionFromLineIndex(lineTo, indexTo);

		// check if it is double commented block - to do before single check!
		if(commentBlock.size() >= 2){
			QString blockStart = commentBlock.first();
			QString blockEnd = commentBlock.last();
			// comment exists? remove?
			if (selTextTrimmed.startsWith(blockStart) && selTextTrimmed.endsWith(blockEnd)) {
				beginUndoAction();

				int idx1 = selText.indexOf(blockStart);
				selText.remove(idx1, blockStart.size());
				int idx2 = selText.lastIndexOf(blockEnd);
				selText.remove(idx2, blockEnd.size());

				SendScintilla(SCI_TARGETFROMSELECTION);
				SendScintilla(SCI_REPLACETARGET, -1, selText.toUtf8().data());
				SendScintilla(SCI_SETSEL, SendScintilla(SCI_GETTARGETSTART), SendScintilla(SCI_GETTARGETEND));

				endUndoAction();
				return;
			}
		}

		// check if this block can be single commented
		if (!comment.isEmpty() && lineCommentPrefered_) {
			bool empty_start = false, empty_end = false;

			if (indexFrom == 0)
				empty_start = true;
			else
				empty_start = getTextRange(positionFromLineIndex(lineFrom, 0), pos_start).trimmed().isEmpty();

			if (indexTo == 0)
				empty_end = true;
			else
				empty_end = getTextRange(pos_end, positionFromLineIndex(lineTo+1, 0)).trimmed().isEmpty();

			if (empty_start && empty_end) {
				beginUndoAction();

				// corrections
				if (indexTo == 0)
					lineTo--;
				if (isLineEmpty(lineFrom)) {
					lineFrom++; indexFrom = 0;
				}
				// a workaround: move cursor to the next line to replace EOL as well
				setSelection(lineFrom, 0, lineTo+1, 0);

				QStringList sl;
				for (int i = lineFrom; i <= lineTo; i++)
					sl += text(i);

				bool comm = false;
				for (int i = 0; i < sl.count(); i++)
					if (!sl.at(i).trimmed().startsWith(comment)) {
						comm = true;
						break;
					}

				for (int i = 0; i < sl.count(); i++) {
					if (comm)
						sl[i] = sl[i].prepend(comment);
					else {
						int idx = sl.at(i).indexOf(comment);
						sl[i] = sl[i].remove(idx, comment.size());
					}
				}

				SendScintilla(SCI_TARGETFROMSELECTION);
				SendScintilla(SCI_REPLACETARGET, -1, sl.join("").toUtf8().data());
				SendScintilla(SCI_SETSEL, SendScintilla(SCI_GETTARGETSTART), SendScintilla(SCI_GETTARGETEND));

				endUndoAction();
				return;
			}
		}

		// else, set double comment
		if(commentBlock.size() >= 2){
			QString blockStart = commentBlock.first();
			QString blockEnd = commentBlock.last();
			beginUndoAction();

			// last is first
			SendScintilla(SCI_INSERTTEXT, pos_end, blockEnd.toUtf8().data());
			SendScintilla(SCI_INSERTTEXT, pos_start, blockStart.toUtf8().data());

			// select everything
			if(lineFrom == lineTo)
				setSelection(lineFrom, indexFrom, lineTo, indexTo + blockStart.size() + blockEnd.size());
			else
				setSelection(lineFrom, indexFrom, lineTo, indexTo + blockEnd.size());

			endUndoAction();
			return;
		}
	}
}
// from amarok 2.3.0
// copyright            : (C) 2010 by Amarok developers
// web                  : amarok.kde.org
QString OutputDirectory::vfatPath( const QString& path )
{
    QString s = path;

    if( QDir::separator() == '/' ) // we are on *nix, \ is a valid character in file or directory names, NOT the dir separator
        s.replace( '\\', '_' );
    else
        s.replace( '/', '_' ); // on windows we have to replace / instead

    for( int i = 0; i < s.length(); i++ )
    {
        QChar c = s[ i ];
        if( c < QChar(0x20) || c == QChar(0x7F) // 0x7F = 127 = DEL control character
            || c=='*' || c=='?' || c=='<' || c=='>'
            || c=='|' || c=='"' || c==':' )
            c = '_';
        else if( c == '[' )
            c = '(';
        else if ( c == ']' )
            c = ')';
        s[ i ] = c;
    }

    /* beware of reserved device names */
    uint len = s.length();
    if( len == 3 || (len > 3 && s[3] == '.') )
    {
        QString l = s.left(3).toLower();
        if( l=="aux" || l=="con" || l=="nul" || l=="prn" )
            s = '_' + s;
    }
    else if( len == 4 || (len > 4 && s[4] == '.') )
    {
        QString l = s.left(3).toLower();
        QString d = s.mid(3,1);
        if( (l=="com" || l=="lpt") &&
                (d=="0" || d=="1" || d=="2" || d=="3" || d=="4" ||
                    d=="5" || d=="6" || d=="7" || d=="8" || d=="9") )
            s = '_' + s;
    }

    // "clock$" is only allowed WITH extension, according to:
    // http://en.wikipedia.org/w/index.php?title=Filename&oldid=303934888#Comparison_of_file_name_limitations
    if( QString::compare( s, "clock$", Qt::CaseInsensitive ) == 0 )
        s = '_' + s;

    /* max path length of Windows API */
    s = s.left(255);

    /* whitespace at the end of folder/file names or extensions are bad */
    len = s.length();
    if( s[len-1] == ' ' )
        s[len-1] = '_';

    int extensionIndex = s.lastIndexOf( '.' ); // correct trailing spaces in file name itself
    if( ( s.length() > 1 ) &&  ( extensionIndex > 0 ) )
        if( s.at( extensionIndex - 1 ) == ' ' )
            s[extensionIndex - 1] = '_';

    for( int i = 1; i < s.length(); i++ ) // correct trailing whitespace in folder names
    {
        if( ( s.at( i ) == QDir::separator() ) && ( s.at( i - 1 ) == ' ' ) )
            s[i - 1] = '_';
    }

    return s;
}
KUrl OutputDirectory::calcPath( FileListItem *fileListItem, Config *config, const QStringList& usedOutputNames )
{
    ConversionOptions *options = config->conversionOptionsManager()->getConversionOptions(fileListItem->conversionOptionsId);
    if( !options )
        return KUrl();

    QString path;
    KUrl url;

    QString extension;
    if( config->pluginLoader()->codecExtensions(options->codecName).count() > 0 )
        extension = config->pluginLoader()->codecExtensions(options->codecName).first();

    if( extension.isEmpty() )
        extension = options->codecName;

    QString fileName;
    if( fileListItem->track == -1 )
        fileName = fileListItem->url.fileName();
    else
        fileName =  QString().sprintf("%02i",fileListItem->tags->track) + " - " + fileListItem->tags->artist + " - " + fileListItem->tags->title + "." + extension;

    if( options->outputDirectoryMode == Specify )
    {
        path = options->outputDirectory+"/"+fileName;

        if( config->data.general.useVFATNames || options->outputFilesystem == "vfat" )
            path = vfatPath( path );

        if( options->outputFilesystem == "ntfs" )
            path = ntfsPath( path );

        url = changeExtension( KUrl(path), extension );

        if( config->data.general.conflictHandling == Config::Data::General::NewFileName )
            url = uniqueFileName( url, usedOutputNames );

        return url;
    }
    else if( options->outputDirectoryMode == MetaData )
    {
        path = options->outputDirectory;

        // TODO a little bit redundant, adding %f if file name wasn't set properly
        // TODO these restrictions could be a little bit over the top
        if( path.right(1) == "/" )
            path += "%f";
        else if( path.lastIndexOf(QRegExp("%[abcdfgnpty]")) < path.lastIndexOf("/") )
            path += "/%f";

        const int fileNameBegin = path.lastIndexOf("/");
        if( fileListItem->tags == 0 ||
            ( path.mid(fileNameBegin).contains("%n") && fileListItem->tags->track == 0 ) ||
            ( path.mid(fileNameBegin).contains("%t") && fileListItem->tags->title.isEmpty() )
          )
        {
            path = path.left( fileNameBegin ) + "/%f";
        }

        path.replace( "\\[", "$quared_bracket_open$" );
        path.replace( "\\]", "$quared_bracket_close$" );

        QRegExp reg( "\\[(.*)%([abcdfgnpty])(.*)\\]" );
        reg.setMinimal( true );
        while( path.indexOf(reg) != -1 )
        {
            if( fileListItem->tags &&
                (
                  ( reg.cap(2) == "a" && !fileListItem->tags->artist.isEmpty() ) ||
                  ( reg.cap(2) == "b" && !fileListItem->tags->album.isEmpty() ) ||
                  ( reg.cap(2) == "c" && !fileListItem->tags->comment.isEmpty() ) ||
                  ( reg.cap(2) == "d" && fileListItem->tags->disc != 0 ) ||
                  ( reg.cap(2) == "g" && !fileListItem->tags->genre.isEmpty() ) ||
                  ( reg.cap(2) == "n" && fileListItem->tags->track != 0 ) ||
                  ( reg.cap(2) == "p" && !fileListItem->tags->composer.isEmpty() ) ||
                  ( reg.cap(2) == "t" && !fileListItem->tags->title.isEmpty() ) ||
                  ( reg.cap(2) == "y" && fileListItem->tags->year != 0 )
                )
              )
            {
                path.replace( reg, "\\1%\\2\\3" );
            }
            else
            {
                path.replace( reg, "" );
            }
        }

        path.replace( "$quared_bracket_open$", "[" );
        path.replace( "$quared_bracket_close$", "]" );

        while( path.contains("//") )
            path.replace( "//", "/" );

        path.replace( "%a", "$replace_by_artist$" );
        path.replace( "%b", "$replace_by_album$" );
        path.replace( "%c", "$replace_by_comment$" );
        path.replace( "%d", "$replace_by_disc$" );
        path.replace( "%g", "$replace_by_genre$" );
        path.replace( "%n", "$replace_by_track$" );
        path.replace( "%p", "$replace_by_composer$" );
        path.replace( "%t", "$replace_by_title$" );
        path.replace( "%y", "$replace_by_year$" );
        path.replace( "%f", "$replace_by_filename$" );

        QString artist = ( fileListItem->tags == 0 || fileListItem->tags->artist.isEmpty() ) ? i18n("Unknown Artist") : fileListItem->tags->artist;
        artist.replace("/",",");
        path.replace( "$replace_by_artist$", artist );

        QString album = ( fileListItem->tags == 0 || fileListItem->tags->album.isEmpty() ) ? i18n("Unknown Album") : fileListItem->tags->album;
        album.replace("/",",");
        path.replace( "$replace_by_album$", album );

        QString comment = ( fileListItem->tags == 0 || fileListItem->tags->comment.isEmpty() ) ? i18n("No Comment") : fileListItem->tags->comment;
        comment.replace("/",",");
        path.replace( "$replace_by_comment$", comment );

        QString disc = ( fileListItem->tags == 0 ) ? "0" : QString().sprintf("%i",fileListItem->tags->disc);
        path.replace( "$replace_by_disc$", disc );

        QString genre = ( fileListItem->tags == 0 || fileListItem->tags->genre.isEmpty() ) ? i18n("Unknown Genre") : fileListItem->tags->genre;
        genre.replace("/",",");
        path.replace( "$replace_by_genre$", genre );

        QString track = ( fileListItem->tags == 0 ) ? "00" : QString().sprintf("%02i",fileListItem->tags->track);
        path.replace( "$replace_by_track$", track );

        QString composer = ( fileListItem->tags == 0 || fileListItem->tags->composer.isEmpty() ) ? i18n("Unknown Composer") : fileListItem->tags->composer;
        composer.replace("/",",");
        path.replace( "$replace_by_composer$", composer );

        QString title = ( fileListItem->tags == 0 || fileListItem->tags->title.isEmpty() ) ? i18n("Unknown Title") : fileListItem->tags->title;
        title.replace("/",",");
        path.replace( "$replace_by_title$", title );

        QString year = ( fileListItem->tags == 0 ) ? "0000" : QString().sprintf("%04i",fileListItem->tags->year);
        path.replace( "$replace_by_year$", year );

        QString filename = fileName.left( fileName.lastIndexOf(".") );
        filename.replace("/",",");
        path.replace( "$replace_by_filename$", filename );

        if( config->data.general.useVFATNames || options->outputFilesystem == "vfat" )
            path = vfatPath( path );

        if( options->outputFilesystem == "ntfs" )
            path = ntfsPath( path );

        url = KUrl( path + "." + extension );

        if( config->data.general.conflictHandling == Config::Data::General::NewFileName )
            url = uniqueFileName( url, usedOutputNames );

        return url;
    }
    else if( options->outputDirectoryMode == CopyStructure )
    {
        QString basePath = options->outputDirectory;
        QString originalPath = fileListItem->url.pathOrUrl();
        int cutpos = basePath.length();
        while( basePath.left(cutpos) != originalPath.left(cutpos) )
        {
            cutpos = basePath.lastIndexOf( '/', cutpos - 1 );
        }
        // At this point, basePath and originalPath overlap on the left for cutpos characters (which might be 0).
        path = basePath+originalPath.mid(cutpos);

        if( config->data.general.useVFATNames || options->outputFilesystem == "vfat" )
            path = vfatPath( path );

        if( options->outputFilesystem == "ntfs" )
            path = ntfsPath( path );

        url = changeExtension( KUrl(path), extension );

        if( config->data.general.conflictHandling == Config::Data::General::NewFileName )
            url = uniqueFileName( url, usedOutputNames );

        return url;
    }
    else // SourceDirectory
    {
        path = fileListItem->url.toLocalFile();

        url = changeExtension( KUrl(path), extension );

        if( config->data.general.conflictHandling == Config::Data::General::NewFileName )
            url = uniqueFileName( url, usedOutputNames );

        return url;
    }
}
Example #15
0
QString AssociatedFilesUI::userDefinedFilename() const {
    QString text = d->lineEditUserDefinedName->text();
    const int p = qMax(text.lastIndexOf(QLatin1Char('/')), text.lastIndexOf(QDir::separator()));
    if (p > 0) text = text.mid(p + 1);
    return text;
}
/**
 * Load vertices data from a OBJ file.
 */
bool OBJLoader::load(const char* filename, std::vector<std::vector<glm::vec3> >& points, std::vector<std::vector<glm::vec3> >& normals, std::vector<std::vector<glm::vec2> >& texCoords) {
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly)) {
        return false;
    }

    QTextStream in(&file);

    std::vector<glm::vec3> raw_vertices;
    std::vector<glm::vec3> raw_normals;
    std::vector<glm::vec2> raw_texCoords;
    std::vector<std::vector<unsigned int> > v_elements;
    std::vector<std::vector<unsigned int> > t_elements;
    std::vector<std::vector<unsigned int> > n_elements;

    while (!in.atEnd()) {
        QString line = in.readLine();
        if (line.startsWith("v ")) {
            int index1 = line.indexOf(QRegExp("[0-9\\.\\-]"), 2);
            int index2 = line.lastIndexOf(QRegExp("[0-9]"));
            QStringList values = line.mid(index1, index2 - index1 + 1).split(" ");
            raw_vertices.push_back(glm::vec3(values[0].toFloat(), values[1].toFloat(), values[2].toFloat()));
        } else if (line.startsWith("vn ")) {
            int index1 = line.indexOf(QRegExp("[0-9\\.\\-]"), 2);
            int index2 = line.lastIndexOf(QRegExp("[0-9]"));
            QStringList values = line.mid(index1, index2 - index1 + 1).split(" ");
            raw_normals.push_back(glm::vec3(values[0].toFloat(), values[1].toFloat(), values[2].toFloat()));
        } else if (line.startsWith("vt ")) {
            int index1 = line.indexOf(QRegExp("[0-9\\.\\-]"), 2);
            int index2 = line.lastIndexOf(QRegExp("[0-9]"));
            QStringList values = line.mid(index1, index2 - index1 + 1).split(" ");
            raw_texCoords.push_back(glm::vec2(values[0].toFloat(), values[1].toFloat()));
        } else if (line.startsWith("f ")) {
            int index1 = line.indexOf(QRegExp("[0-9]"), 2);
            int index2 = line.lastIndexOf(QRegExp("[0-9]"));
            QStringList values = line.mid(index1, index2 - index1 + 1).split(" ");

            std::vector<unsigned int> v_ele;
            std::vector<unsigned int> n_ele;
            std::vector<unsigned int> t_ele;
            for (int i = 0; i < values.size(); ++i) {
                v_ele.push_back(values[i].split("/")[0].toUInt() - 1);
                if (values[0].split("/").size() >= 2 && values[0].split("/")[1].size() > 0) {
                    t_ele.push_back(values[i].split("/")[1].toUInt() - 1);
                }
                if (values[0].split("/").size() >= 3 && values[0].split("/")[2].size() > 0) {
                    n_ele.push_back(values[i].split("/")[2].toUInt() - 1);
                }
            }

            v_elements.push_back(v_ele);
            if (t_ele.size() > 0) {
                t_elements.push_back(t_ele);
            }
            if (n_ele.size() > 0) {
                n_elements.push_back(n_ele);
            }
        } else if (line.size() == 0) {
            /* ignore empty line */
        } else if (line.startsWith("#")) {
            /* ignore comment line */
        } else {
            /* ignore this line */
        }
    }

    points.resize(v_elements.size());
    normals.resize(v_elements.size());
    if (t_elements.size() > 0) {
        texCoords.resize(v_elements.size());
    }
    for (int i = 0; i < v_elements.size(); ++i) {
        points[i].resize(v_elements[i].size());
        normals[i].resize(v_elements[i].size());
        if (t_elements.size() > 0) {
            texCoords[i].resize(v_elements[i].size());
        }

        for (int j = 0; j < v_elements[i].size(); ++j) {
            unsigned int idx = v_elements[i][j];
            points[i][j] = raw_vertices[idx];
        }

        if (n_elements.size() > 0 && n_elements[i].size() > 0) {
            for (int j = 0; j < n_elements[i].size(); ++j) {
                unsigned int idx = n_elements[i][j];
                normals[i][j] = raw_normals[idx];
            }
        } else {
            glm::vec3 normal = glm::cross(points[i][1] - points[i][0], points[i][2] - points[i][0]);
            normal = glm::normalize(normal);

            for (int j = 0; j < v_elements[i].size(); ++j) {
                normals[i][j] = normal;
            }
        }

        if (t_elements.size() > 0 && t_elements[i].size() > 0) {
            for (int j = 0; j < t_elements[i].size(); ++j) {
                unsigned int idx = t_elements[i][j];
                texCoords[i][j] = raw_texCoords[idx];
            }
        }
    }

    return true;
}
Example #17
0
bool downloadOSM(MainWindow* Main, const CoordBox& aBox , Document* theDocument)
{
    QString osmWebsite, osmUser, osmPwd;
    static bool DownloadRaw = false;

    QDialog * dlg = new QDialog(Main);

    osmWebsite = M_PREFS->getOsmApiUrl();
    osmUser = M_PREFS->getOsmUser();
    osmPwd = M_PREFS->getOsmPassword();

    Ui::DownloadMapDialog ui;
    ui.setupUi(dlg);
    SlippyMapWidget* SlippyMap = new SlippyMapWidget(ui.groupBox);
#ifndef _MOBILE
    SlippyMap->setMinimumHeight(256);
#endif
    CoordBox Clip(aBox);
    SlippyMap->setViewportArea(Clip);
    ui.verticalLayout->addWidget(SlippyMap);
    QObject::connect(SlippyMap, SIGNAL(redraw()), ui.FromMap, SLOT(toggle()));
    BookmarkListIterator i(*(M_PREFS->getBookmarks()));
    while (i.hasNext()) {
        i.next();
        if (i.value().deleted == false)
            ui.Bookmarks->addItem(i.key());
    }
    ui.edXapiUrl->setText(QString("*[bbox=%1,%2,%3,%4]").arg(aBox.bottomLeft().x(), 0, 'f').arg(aBox.bottomLeft().y(), 0, 'f').arg(aBox.topRight().x(), 0, 'f').arg(aBox.topRight().y(), 0, 'f'));
    ui.IncludeTracks->setChecked(DownloadRaw);
    ui.ResolveRelations->setChecked(M_PREFS->getResolveRelations());
    bool OK = true, retry = true, directAPI = false;
    QString directUrl;
    while (retry) {
        retry = false;
#ifdef _MOBILE
        dlg->setWindowState(Qt::WindowMaximized);
#endif
        if (dlg->exec() == QDialog::Accepted)
        {
            DownloadRaw = false;
            if (ui.FromBookmark->isChecked())
            {
                Clip = M_PREFS->getBookmarks()->value(ui.Bookmarks->currentText()).Coordinates;
            }
            else if (ui.FromView->isChecked())
            {
                Clip = aBox;
            }
            else if (ui.FromLink->isChecked()) {
                QString link = ui.Link->text();

                if (link.contains("/api/")) {
                    directAPI=true;
                    directUrl = link;
                } else if (link.contains("/browse/")) {
                    QString tag("/browse/");
                    int ix = link.lastIndexOf(tag) + tag.length();
                    directUrl = M_PREFS->getOsmApiUrl();
                    if (!directUrl.endsWith("/")) directUrl += "/";
                    directUrl += link.right(link.length() - ix);
                    if (!directUrl.endsWith("/")) directUrl += "/";
                    directUrl += "full";
                    directAPI=true;
                } else if (link.startsWith("way") || link.startsWith("node") || link.startsWith("relation")) {
                    directUrl = M_PREFS->getOsmApiUrl();
                    if (!directUrl.endsWith("/")) directUrl += "/";
                    directUrl += link;
                    directAPI=true;
                } else {
                    OsmLink ol(link);
                    Clip = ol.getCoordBox();
                    if (Clip.isNull() || Clip.isEmpty())
                        retry = true;
                }
            }
            else if (ui.FromXapi->isChecked())
            {
                directAPI = true;
                directUrl = M_PREFS->getXapiUrl();
                //if (!directUrl.endsWith("/")) directUrl += "/";
                directUrl += ui.edXapiUrl->text();
            }
            else if (ui.FromMap->isChecked())
            {
                QRectF R(SlippyMap->selectedArea());
                Clip = CoordBox(Coord(R.x(), R.y()), Coord(R.x()+R.width(), R.y()+R.height()));
            }
            if (retry) continue;
            Main->view()->setUpdatesEnabled(false);
            Layer* theLayer = new DrawingLayer(QApplication::translate("Downloader","%1 download").arg(QDateTime::currentDateTime().toString(Qt::ISODate)));
            theDocument->add(theLayer);
            M_PREFS->setResolveRelations(ui.ResolveRelations->isChecked());
            if (directAPI) {
                if (ui.FromXapi->isChecked())
                    theLayer->setUploadable(false);
                OK = downloadOSM(Main,QUrl(QUrl::fromEncoded(directUrl.toLatin1())),osmUser,osmPwd,theDocument,theLayer);
            }
            else
                OK = downloadOSM(Main,osmWebsite,osmUser,osmPwd,Clip,theDocument,theLayer);
            if (OK && ui.IncludeTracks->isChecked())
                OK = downloadTracksFromOSM(Main,osmWebsite,osmUser,osmPwd, Clip,theDocument);
            Main->view()->setUpdatesEnabled(true);
            if (OK)
            {
                theDocument->setLastDownloadLayer(theLayer);
                theDocument->addDownloadBox(theLayer, Clip);
#ifndef _MOBILE
                if (directAPI)
                    Main->on_viewZoomAllAction_triggered();
                else
#endif
                    Main->view()->setViewport(Clip,Main->view()->rect());
                Main->invalidateView();
            } else {
                retry = true;
                theDocument->remove(theLayer);
                SAFE_DELETE(theLayer);
            }
        }
    }
    delete dlg;
    return OK;
}
Example #18
0
void Builder::ImportDeclarations(void)
{
    QString inFileName = config.workspace + "/" + project->name + "/source/" + project->name + ".cpp"; //main.cpp

    if (QFileInfo(inFileName).exists() == false) {
        return;
    }

    QFile inFile(inFileName);
    inFile.open(QFile::ReadOnly | QFile::Text);
    QTextStream in(&inFile);
    QString code = in.readAll();

    // Remove all single-line comments from the text that will be processed
    QStringList lines = code.split("\n");

    int i=0;
    while (i < lines.count()) {
        int p = lines[i].indexOf("//");
        if (p >= 0) {
            lines[i] = lines[i].right(p);
        }
        i++;
    }
    code = lines.join("\n");

    // remove all multi-line comments from the text that will be processed
    int p1 = code.indexOf("/*");
    //int watchDogMonitor = code.length();
    while (p1 >= 0) {
        QString left = code.left(p1);
        code = code.right(code.length() - p1);
        int p2 = code.indexOf("*/");
        if (p2 >=0) {
            QString right = code.right(code.length() - p2 - 2);
            code = left + right;
        } else {
            return; // could not find the end of a comment: break to avoid infinite loop
        }
        p1 = code.indexOf("/*");

        /*if (code.length() == watchDogMonitor) {
        	return; // exit to avoid an infinite loop
        }
        watchDogMonitor = code.length();*/
    }

    lines = code.split("\n");
    QStringList list;

    i=1;
    while (i < lines.count()) {
        if (lines[i].trimmed().indexOf("{") == 0) {
            lines[i-1] = " " + lines[i];
            lines.erase(lines.begin()+i);
        } else {
            i++;
        }
    }

    for (int i=0; i < lines.count(); i++) {
        //QRegExp rx("(\\ |\\,|\\(|\\)|\\.|\\:|\\t)"); //RegEx for ' ' or ',' or '.' or ':' or '\t'
        QRegExp rx("\\s"); //RegEx for all white spaces, including tab'
        bool ok = rx.isValid();
        QString line = lines[i].trimmed();
        int j = 0;
        while (j < line.size()) { //insert spaces
            if ( ( (line.at(j) == '(') || (line.at(j) == ')') ) || ( (line.at(j) == '{') || (line.at(j) == '}') ) ) {
                line.insert(j, " ");
                j++;
            }
            if ( ( (line.at(j) == ':') || (line.at(j) == ',') ) || ( (line.at(j) == ';') || (line.at(j) == ';') ) ) {
                line.insert(j, " ");
                j++;
            }
            j++;
        }
        QStringList words = line.split(rx);
        int w = 0;
        while (w < words.count()) {
            words[w] = words[w].trimmed().toUpper();
            if (words[w] == "") {
                words.erase(words.begin() + w);
            } else {
                w++;
            }
        }

        if (words.count() < 4) { // at least "TYPE", "FUNCTION_NAME", "(", ")"
            continue;
        }

        bool ignore = false;
        ignore = ignore || (words.indexOf("IF") >= 0);
        ignore = ignore || (words.indexOf("ELSE") >= 0);
        ignore = ignore || (words.indexOf("WHILE") >= 0);
        ignore = ignore || (words.indexOf("DO") >= 0);
        ignore = ignore || (words.indexOf("SWITCH") >= 0);
        ignore = ignore || (lines[i].indexOf(";") >= 0);
        ignore = ignore || (lines[i].indexOf(".") >= 0);
        ignore = ignore || (lines[i].indexOf("->") >= 0);
        ignore = ignore || (lines[i].indexOf("=") >= 0);
        ignore = ignore || (lines[i].indexOf("==") >= 0);
        ignore = ignore || (lines[i].indexOf("\"") >= 0); // any argument with " may be considered a call, and not a definition
        ignore = ignore || (lines[i].indexOf("'") >= 0); // idem

        // check if any argument is a number. If yes, then it shall be considered a function call, and not a definiton
        for (int j=0; j < words.count(); j++) {
            double num = words.at(j).toDouble();
            if (QString::number(num) == words.at(j)) {
                ignore = true;
                break;
            }
        }

        // if the first word is not an recognized data type, ignore
        bool validDataType = false;
        validDataType = validDataType || (words.at(0) == "VOID");
        validDataType = validDataType || (words.at(0) == "INT");
        validDataType = validDataType || (words.at(0) == "CHAR");
        validDataType = validDataType || (words.at(0) == "SHORT");
        validDataType = validDataType || (words.at(0) == "UNSIGNED");
        validDataType = validDataType || (words.at(0) == "SIGNED");
        validDataType = validDataType || (words.at(0) == "LONG");
        validDataType = validDataType || (words.at(0) == "FLOAT");
        validDataType = validDataType || (words.at(0) == "DOUBLE");
        validDataType = validDataType || (words.at(0) == "BYTE");
        validDataType = validDataType || (words.at(0) == "INT16");
        validDataType = validDataType || (words.at(0) == "INT32");
        validDataType = validDataType || (words.at(0) == "INT64");
        validDataType = validDataType || (words.at(0) == "BOOL");
        ignore = ignore || (validDataType == false);

        if (lines[i].indexOf("//") >= 0) {
            lines[i] = lines[i].left(lines[i].indexOf("//"));
        }

        if (ignore) {
            continue;
        }

        int p1 = lines[i].indexOf("(");
        int p2 = lines[i].indexOf(")");
        if ((p1 > 0) && (p2 > p1)) {
            QString def = lines[i].trimmed();
            int p = def.lastIndexOf(")");
            if (p >= 0) {
                def = def.left(p+1) + ";";
                list.append(def);
            }
        }
    }

    QString outFileName = config.workspace + "/" + project->name + "/source/mariamole_auto_generated.h";

    if (QFileInfo(outFileName).exists() == false) {
        return;
    }

    QFile inFile2(outFileName);
    inFile2.open(QFile::ReadOnly | QFile::Text);
    QTextStream in2(&inFile2);
    code = in2.readAll();

    QStringList header = code.split("\n");
    //QStringList alreadyAdded;
    int index = -1;// = header.count() - 2;
    bool foundBegin = false;
    int k=0;
    while (k < header.count()) {
        QString line = header[k].trimmed();
        if (line == "/*--MARIMOLE-DEF_END--*/") {
            foundBegin = false;
        }
        if (foundBegin) {
            header.erase(header.begin() + k);
        } else {
            ++k;
        }
        if (line == "/*--MARIMOLE-DEF_BEGIN--*/") {
            foundBegin = true;
            index = k;
        }
    }

    if (index < 0) {
        return;
    }

    for (int i=0; i < list.count(); i++) {
        header.insert(index, list[i]);
    }

    QFile outFile(outFileName);
    outFile.open(QFile::WriteOnly);
    QTextStream out(&outFile);
    out << header.join("\n");
}
Example #19
0
QStringRef IoUtils::fileName(const QString &fileName)
{
    return fileName.midRef(fileName.lastIndexOf(QLatin1Char('/')) + 1);
}
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);
    if (argc >= 1 && qstrcmp(argv[1], "--system") == 0) {
        connection = &QDBus::systemBus();
        --argc;
        ++argv;
    } else
        connection = &QDBus::sessionBus();

    if (!connection->isConnected()) {
        fprintf(stderr, "Could not connect to D-Bus server: %s: %s\n",
                qPrintable(connection->lastError().name()),
                qPrintable(connection->lastError().message()));
        return 1;
    }
    QDBusBusService *bus = connection->busService();

    if (argc == 1) {
        QStringList names = bus->ListNames();
        foreach (QString name, names)
            printf("%s\n", qPrintable(name));
        exit(0);
    }
    
    QString service = QLatin1String(argv[1]);
    if (!QDBusUtil::isValidBusName(service)) {
        fprintf(stderr, "Service '%s' is not a valid name.\n", qPrintable(service));
        exit(1);
    }
    if (!bus->NameHasOwner(service)) {
        fprintf(stderr, "Service '%s' does not exist.\n", qPrintable(service));
        exit(1);
    }

    if (argc == 2) {
        printf("/\n");
        listObjects(service, QString());
        exit(0);
    }

    QString path = QLatin1String(argv[2]);
    if (!QDBusUtil::isValidObjectPath(path)) {
        fprintf(stderr, "Path '%s' is not a valid path name.\n", qPrintable(path));
        exit(1);
    }
    if (argc == 3) {
        listAllInterfaces(service, path);
        exit(0);
    }

    QString interface = QLatin1String(argv[3]);
    QString member;
    int pos = interface.lastIndexOf(QLatin1Char('.'));
    if (pos == -1) {
        member = interface;
        interface.clear();
    } else {
        member = interface.mid(pos + 1);
        interface.truncate(pos);
    }
    if (!interface.isEmpty() && !QDBusUtil::isValidInterfaceName(interface)) {
        fprintf(stderr, "Interface '%s' is not a valid interface name.\n", qPrintable(interface));
        exit(1);
    }
    if (!QDBusUtil::isValidMemberName(member)) {
        fprintf(stderr, "Method name '%s' is not a valid member name.\n", qPrintable(member));
        exit(1);
    }

    if (interface.isEmpty()) {
        if (member.toLower() == QLatin1String("get") && argc == 5) {
            getProperty(service, path, QLatin1String(argv[4]));
            return 0;
        } else if (member.toLower() == QLatin1String("set") && argc == 6) {
            setProperty(service, path, QLatin1String(argv[4]), QLatin1String(argv[5]));
            return 0;
        }
    }    
    placeCall(service, path, interface, member, argc - 4, argv + 4);
}
Example #21
0
QStringList CMakeProject::getCXXFlagsFor(const CMakeBuildTarget &buildTarget, QByteArray *cachedBuildNinja)
{
    QString makeCommand = QDir::fromNativeSeparators(buildTarget.makeCommand);
    int startIndex = makeCommand.indexOf(QLatin1Char('\"'));
    int endIndex = makeCommand.indexOf(QLatin1Char('\"'), startIndex + 1);
    if (startIndex != -1 && endIndex != -1) {
        startIndex += 1;
        QString makefile = makeCommand.mid(startIndex, endIndex - startIndex);
        int slashIndex = makefile.lastIndexOf(QLatin1Char('/'));
        makefile.truncate(slashIndex);
        makefile.append(QLatin1String("/CMakeFiles/") + buildTarget.title + QLatin1String(".dir/flags.make"));
        QFile file(makefile);
        if (file.exists()) {
            file.open(QIODevice::ReadOnly | QIODevice::Text);
            QTextStream stream(&file);
            while (!stream.atEnd()) {
                QString line = stream.readLine().trimmed();
                if (line.startsWith(QLatin1String("CXX_FLAGS ="))) {
                    // Skip past =
                    return line.mid(11).trimmed().split(QLatin1Char(' '), QString::SkipEmptyParts);
                }
            }
        }
    }

    // Attempt to find build.ninja file and obtain FLAGS (CXX_FLAGS) from there if no suitable flags.make were
    // found
    // Get "all" target's working directory
    if (!buildTargets().empty()) {
        if (cachedBuildNinja->isNull()) {
            QString buildNinjaFile = QDir::fromNativeSeparators(buildTargets().at(0).workingDirectory);
            buildNinjaFile += QLatin1String("/build.ninja");
            QFile buildNinja(buildNinjaFile);
            if (buildNinja.exists()) {
                buildNinja.open(QIODevice::ReadOnly | QIODevice::Text);
                *cachedBuildNinja = buildNinja.readAll();
                buildNinja.close();
            } else {
                *cachedBuildNinja = QByteArray();
            }
        }

        if (cachedBuildNinja->isEmpty())
            return QStringList();

        QTextStream stream(cachedBuildNinja);
        bool targetFound = false;
        bool cxxFound = false;
        QString targetSearchPattern = QString::fromLatin1("target %1").arg(buildTarget.title);

        while (!stream.atEnd()) {
            // 1. Look for a block that refers to the current target
            // 2. Look for a build rule which invokes CXX_COMPILER
            // 3. Return the FLAGS definition
            QString line = stream.readLine().trimmed();
            if (line.startsWith(QLatin1String("#"))) {
                if (!line.startsWith(QLatin1String("# Object build statements for"))) continue;
                targetFound = line.endsWith(targetSearchPattern);
            } else if (targetFound && line.startsWith(QLatin1String("build"))) {
                cxxFound = line.indexOf(QLatin1String("CXX_COMPILER")) != -1;
            } else if (cxxFound && line.startsWith(QLatin1String("FLAGS ="))) {
                // Skip past =
                return line.mid(7).trimmed().split(QLatin1Char(' '), QString::SkipEmptyParts);
            }
        }

    }
    return QStringList();
}
QString MainWindow::getFiletypeFromFilePath(QString path)
{
    int index = path.lastIndexOf('.');
    return path.right(path.length()-index);
}
Example #23
0
void CeguiInject::runGame() {
    if (RegVip() == FALSE) {
        return;
    }
    ks_exit();

    char dllname[MAX_PATH];
    GetModuleFileName(NULL, dllname, MAX_PATH);
    std::string strDll = dllname;
    //QString qstrDll = QString::fromStdString(strDll); // 此用法会造成中文乱码
    QString qstrDll = QString::fromLocal8Bit(strDll.c_str());
    QString strSplit = "\\";
    int index = qstrDll.lastIndexOf(strSplit);
    qstrDll = qstrDll.left(index);
    //strDll = qstrDll.toStdString(); // 此用法会造成程序崩溃
    strDll = std::string((const char*)qstrDll.toLocal8Bit());

    if (ui.radioButton_d3d9->isChecked()) {
        strDll += "\\D3D9_CEGUI.dll";
    } else if (ui.radioButton_d3d8->isChecked()) {
        strDll += "\\D3D8_CEGUI.dll";
    }

    if (!fileExists(strDll.c_str())) {
        ::MessageBox(NULL, "没有找到 DLL 文件 . . ", "Tatnium Error", MB_ICONERROR);
        return;
    }

    //if (IDCANCEL == ::MessageBox(0, "点击 \"确定\" 后开始等待游戏启动\n\n等待中按键盘 \"esc\" 键取消等待...", "Tatnium Injector", MB_OK)) {
    //    return;
    //}

    QString strOutput = QStringLiteral("点击 \"Yes\" 开始等待游戏启动(手动),\n等待中可按键盘 \"esc\" 键取消等待...");
    if (QMessageBox::No == QMessageBox::question(this, QStringLiteral("是否开启插件?"), strOutput, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes)) {
        return;
    }
    
    QString strGame = ui.lineEdit_path->text();
    if (strGame.isEmpty()) {
        QMessageBox::about(this, QStringLiteral("提示"), QStringLiteral("没有正确选择游戏路径!"));
        return;
    }

    strSplit = "/";
    index = strGame.lastIndexOf(strSplit);
    strGame = strGame.right(strGame.length() - index - 1);
    std::string szGame = std::string((const char*)strGame.toLocal8Bit());

    PROCESSENTRY32 pe32;
    while (!GetProcessOf(szGame.c_str(), &pe32)) {
        if (GetAsyncKeyState(VK_ESCAPE)) {
            return;
        }
        Sleep(10);
    }

    THREADENTRY32 te32;
    while (!GetThreadOf(pe32.th32ProcessID, &te32)) {
        Sleep(2);
    }

    PROCESS_INFORMATION PI;
    PI.dwProcessId = pe32.th32ProcessID;
    PI.dwThreadId = te32.th32ThreadID;
    PI.hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pe32.th32ProcessID);

    if (!ForceLibrary(strDll.c_str(), &PI)) {
        TerminateProcess(PI.hProcess, 0);
        ::MessageBox(NULL, "无法开启插件...", "Tatnium Error", MB_ICONERROR);
    }

    CloseHandle(PI.hProcess);

    //::CloseHandle((HANDLE)_beginthreadex(NULL, 0, ThreadFun_WaritGame, NULL, 0, NULL));
}
Example #24
0
void LegacyUpdate::extractLwjgl()
{
	// make sure the directories are there

	bool success = ensureFolderPathExists(lwjglNativesPath);

	if (!success)
	{
		emitFailed("Failed to extract the lwjgl libs - error when creating required folders.");
		return;
	}

	QuaZip zip("lwjgl.zip");
	if (!zip.open(QuaZip::mdUnzip))
	{
		emitFailed("Failed to extract the lwjgl libs - not a valid archive.");
		return;
	}

	// and now we are going to access files inside it
	QuaZipFile file(&zip);
	const QString jarNames[] = {"jinput.jar", "lwjgl_util.jar", "lwjgl.jar"};
	for (bool more = zip.goToFirstFile(); more; more = zip.goToNextFile())
	{
		if (!file.open(QIODevice::ReadOnly))
		{
			zip.close();
			emitFailed("Failed to extract the lwjgl libs - error while reading archive.");
			return;
		}
		QuaZipFileInfo info;
		QString name = file.getActualFileName();
		if (name.endsWith('/'))
		{
			file.close();
			continue;
		}
		QString destFileName;
		// Look for the jars
		for (int i = 0; i < 3; i++)
		{
			if (name.endsWith(jarNames[i]))
			{
				destFileName = PathCombine(lwjglTargetPath, jarNames[i]);
			}
		}
		// Not found? look for the natives
		if (destFileName.isEmpty())
		{
#ifdef Q_OS_WIN32
			QString nativesDir = "windows";
#else
#ifdef Q_OS_MAC
			QString nativesDir = "macosx";
#else
			QString nativesDir = "linux";
#endif
#endif
			if (name.contains(nativesDir))
			{
				int lastSlash = name.lastIndexOf('/');
				int lastBackSlash = name.lastIndexOf('\\');
				if (lastSlash != -1)
					name = name.mid(lastSlash + 1);
				else if (lastBackSlash != -1)
					name = name.mid(lastBackSlash + 1);
				destFileName = PathCombine(lwjglNativesPath, name);
			}
		}
		// Now if destFileName is still empty, go to the next file.
		if (!destFileName.isEmpty())
		{
			setStatus(tr("Installing new LWJGL - extracting ") + name + "...");
			QFile output(destFileName);
			output.open(QIODevice::WriteOnly);
			output.write(file.readAll()); // FIXME: wste of memory!?
			output.close();
		}
		file.close(); // do not forget to close!
	}
	zip.close();
	m_reply.reset();
	QFile doneFile(PathCombine(lwjglTargetPath, "done"));
	doneFile.open(QIODevice::WriteOnly);
	doneFile.write("done.");
	doneFile.close();
}
bool QtDesignerFormClassCodeGenerator::generateCpp(const FormClassWizardParameters &parameters,
                                                   QString *header, QString *source, int indentation)
{
    Internal::FormClassWizardGenerationParameters generationParameters;
    generationParameters.fromSettings(Core::ICore::settings());

    const QString indent = QString(indentation, QLatin1Char(' '));
    QString formBaseClass;
    QString uiClassName;

    if (!Internal::FormTemplateWizardPage::getUIXmlData(parameters.uiTemplate, &formBaseClass, &uiClassName)) {
        qWarning("Unable to determine the form base class from %s.", qPrintable(parameters.uiTemplate));
        return false;
    }

    // Build the ui class (Ui::Foo) name relative to the namespace (which is the same):
    const QString colonColon = QLatin1String("::");
    const int lastSeparator = uiClassName.lastIndexOf(colonColon);
    if (lastSeparator != -1)
        uiClassName.remove(0, lastSeparator + colonColon.size());
    uiClassName.insert(0, QLatin1String(uiNamespaceC) + colonColon);

    // Do we have namespaces?
    QStringList namespaceList = parameters.className.split(colonColon);
    if (namespaceList.empty()) // Paranoia!
        return false;

    const QString unqualifiedClassName = namespaceList.takeLast();

    const QString headerLicense =
            CppTools::AbstractEditorSupport::licenseTemplate(parameters.headerFile, parameters.className);
    const QString sourceLicense =
            CppTools::AbstractEditorSupport::licenseTemplate(parameters.sourceFile, parameters.className);
    // Include guards
    const QString guard = Utils::headerGuard(parameters.headerFile, namespaceList);

    QString uiInclude = QLatin1String("ui_");
    uiInclude += QFileInfo(parameters.uiFile).completeBaseName();
    uiInclude += QLatin1String(".h");

    // 1) Header file
    QTextStream headerStr(header);
    headerStr << headerLicense << "#ifndef " << guard
              << "\n#define " <<  guard << '\n' << '\n';

    // Include 'ui_'
    if (generationParameters.embedding != Internal::PointerAggregatedUiClass) {
        Utils::writeIncludeFileDirective(uiInclude, false, headerStr);
    } else {
        // Todo: Can we obtain the header from the code model for custom widgets?
        // Alternatively, from Designer.
        if (formBaseClass.startsWith(QLatin1Char('Q'))) {
            if (generationParameters.includeQtModule) {
                if (generationParameters.addQtVersionCheck) {
                    Utils::writeBeginQtVersionCheck(headerStr);
                    Utils::writeIncludeFileDirective(QLatin1String("QtWidgets/") + formBaseClass, true, headerStr);
                    headerStr << "#else\n";
                    Utils::writeIncludeFileDirective(QLatin1String("QtGui/") + formBaseClass, true, headerStr);
                    headerStr << "#endif\n";
                } else {
                    Utils::writeIncludeFileDirective(QLatin1String("QtGui/") + formBaseClass, true, headerStr);
                }
            } else {
                Utils::writeIncludeFileDirective(formBaseClass, true, headerStr);
            }
        }
    }

    const QString namespaceIndent = Utils::writeOpeningNameSpaces(namespaceList,
                                                                  generationParameters.indentNamespace ? indent : QString(),
                                                                  headerStr);

    // Forward-declare the UI class
    if (generationParameters.embedding == Internal::PointerAggregatedUiClass) {
          headerStr << '\n'
                  << namespaceIndent << "namespace " <<  uiNamespaceC << " {\n"
                  << namespaceIndent << indent << "class " << Internal::FormTemplateWizardPage::stripNamespaces(uiClassName) << ";\n"
                  << namespaceIndent << "}\n";
    }

    // Class declaration
    headerStr << '\n' << namespaceIndent << "class " << unqualifiedClassName
              << " : public " << formBaseClass;
    if (generationParameters.embedding == Internal::InheritedUiClass)
        headerStr << ", private " << uiClassName;
    headerStr << "\n{\n" << namespaceIndent << indent << "Q_OBJECT\n\n"
              << namespaceIndent << "public:\n"
              << namespaceIndent << indent << "explicit " << unqualifiedClassName << "(QWidget *parent = 0);\n";
    if (generationParameters.embedding == Internal::PointerAggregatedUiClass)
        headerStr << namespaceIndent << indent << "~" << unqualifiedClassName << "();\n";
    // retranslation
    if (generationParameters.retranslationSupport)
        headerStr << '\n' << namespaceIndent << "protected:\n"
                  << namespaceIndent << indent << "void changeEvent(QEvent *e);\n";
    // Member variable
    if (generationParameters.embedding != Internal::InheritedUiClass) {
        headerStr << '\n' << namespaceIndent << "private:\n"
                  << namespaceIndent << indent << uiClassName << ' ';
        if (generationParameters.embedding == Internal::PointerAggregatedUiClass)
            headerStr << '*';
        headerStr << uiMemberC << ";\n";
    }
    headerStr << namespaceIndent << "};\n\n";
    Utils::writeClosingNameSpaces(namespaceList, generationParameters.indentNamespace ? indent : QString(), headerStr);
    headerStr << "#endif // "<<  guard << '\n';

    // 2) Source file
    QTextStream sourceStr(source);
    sourceStr << sourceLicense;
    Utils::writeIncludeFileDirective(parameters.headerFile, false, sourceStr);
    if (generationParameters.embedding == Internal::PointerAggregatedUiClass)
        Utils::writeIncludeFileDirective(uiInclude, false, sourceStr);
    // NameSpaces(
    Utils::writeOpeningNameSpaces(namespaceList, generationParameters.indentNamespace ? indent : QString(), sourceStr);
    // Constructor with setupUi
    sourceStr << '\n' << namespaceIndent << unqualifiedClassName << "::" << unqualifiedClassName << "(QWidget *parent) :\n"
               << namespaceIndent << indent << formBaseClass << "(parent)";
    if (generationParameters.embedding == Internal::PointerAggregatedUiClass)
        sourceStr << ",\n"  << namespaceIndent << indent <<  uiMemberC << "(new " << uiClassName << ")";
    sourceStr <<  '\n' << namespaceIndent << "{\n" <<  namespaceIndent << indent;
    writeUiMemberAccess(generationParameters, sourceStr);
    sourceStr <<  "setupUi(this);\n" << namespaceIndent << "}\n";
    // Deleting destructor for ptr
    if (generationParameters.embedding == Internal::PointerAggregatedUiClass) {
        sourceStr << '\n' <<  namespaceIndent << unqualifiedClassName << "::~" << unqualifiedClassName
                  << "()\n" << namespaceIndent << "{\n"
                  << namespaceIndent << indent << "delete " << uiMemberC << ";\n"
                  << namespaceIndent << "}\n";
    }
    // retranslation
    if (generationParameters.retranslationSupport) {
        sourceStr  << '\n' << namespaceIndent << "void " << unqualifiedClassName << "::" << "changeEvent(QEvent *e)\n"
        << namespaceIndent << "{\n"
        << namespaceIndent << indent << formBaseClass << "::changeEvent(e);\n"
        << namespaceIndent << indent << "switch (e->type()) {\n" << namespaceIndent << indent << "case QEvent::LanguageChange:\n"
        << namespaceIndent << indent << indent;
        writeUiMemberAccess(generationParameters, sourceStr);
        sourceStr << "retranslateUi(this);\n"
                  << namespaceIndent << indent <<  indent << "break;\n"
                  << namespaceIndent << indent << "default:\n"
                  << namespaceIndent << indent << indent << "break;\n"
                  << namespaceIndent << indent << "}\n"
                  << namespaceIndent << "}\n";
    }
    Utils::writeClosingNameSpaces(namespaceList, generationParameters.indentNamespace ? indent : QString(), sourceStr);
    return true;
}
Example #26
0
QScriptValue QDeclarativeComponentPrivate::createObject(QObject *publicParent, const QScriptValue valuemap)
{
    Q_Q(QDeclarativeComponent);
    QDeclarativeContext* ctxt = q->creationContext();
    if(!ctxt && engine)
        ctxt = engine->rootContext();
    if (!ctxt)
        return QScriptValue(QScriptValue::NullValue);
    QObject* ret = q->beginCreate(ctxt);
    if (!ret) {
        q->completeCreate();
        return QScriptValue(QScriptValue::NullValue);
    }

    if (publicParent) {
        ret->setParent(publicParent);
        QList<QDeclarativePrivate::AutoParentFunction> functions = QDeclarativeMetaType::parentFunctions();

        bool needParent = false;

        for (int ii = 0; ii < functions.count(); ++ii) {
            QDeclarativePrivate::AutoParentResult res = functions.at(ii)(ret, publicParent);
            if (res == QDeclarativePrivate::Parented) {
                needParent = false;
                break;
            } else if (res == QDeclarativePrivate::IncompatibleParent) {
                needParent = true;
            }
        }

        if (needParent)
            qWarning("QDeclarativeComponent: Created graphical object was not placed in the graphics scene.");
    }

    QDeclarativeEnginePrivate *priv = QDeclarativeEnginePrivate::get(engine);
    QDeclarativeData::get(ret, true)->setImplicitDestructible();
    QScriptValue newObject = priv->objectClass->newQObject(ret, QMetaType::QObjectStar);

    if (valuemap.isObject() && !valuemap.isArray()) {
        //Iterate through and assign properties
        QScriptValueIterator it(valuemap);
        while (it.hasNext()) {
            it.next();
            QScriptValue prop = newObject;
            QString propName = it.name();
            int index = propName.indexOf(QLatin1Char('.'));
            if (index > 0) {
                QString subProp = propName;
                int lastIndex = 0;
                while (index > 0) {
                    subProp = propName.mid(lastIndex, index - lastIndex);
                    prop = prop.property(subProp);
                    lastIndex = index + 1;
                    index = propName.indexOf(QLatin1Char('.'), index + 1);
                }
                prop.setProperty(propName.mid(propName.lastIndexOf(QLatin1Char('.')) + 1), it.value());
            } else {
                newObject.setProperty(propName, it.value());
            }
        }
    }

    q->completeCreate();

    return newObject;
}
Example #27
0
void QmitkUploadToXNATAction::Run( const QList<mitk::DataNode::Pointer> &selectedNodes )
{
  if (selectedNodes.size() != 1)
  {
    QMessageBox infoBox;
    infoBox.setIcon(QMessageBox::Information);
    infoBox.setText("Please select only one data node for upload");
    infoBox.exec();
  }

  // Try to get the XNAT session
  us::ServiceReference<ctkXnatSession> modServiceRef = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext()->GetServiceReference<ctkXnatSession>();

  if (!modServiceRef)
  {
    ShowInfoMessage();
    return;
  }

  us::ModuleContext* xnatModuleContext = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatModuleContext();

  if (xnatModuleContext == nullptr)
  {
    ShowInfoMessage();
    return;
  }

  ctkXnatSession *session(nullptr);
  session = xnatModuleContext->GetService(modServiceRef);
  if (session == nullptr || !session->isOpen())
  {
    ShowInfoMessage();
    return;
  }

  mitk::DataNode* selectedNode = selectedNodes.at(0);

  if (selectedNode == nullptr)
    return;

  ctkServiceTracker<mitk::IDataStorageService*> dataStorageServiceTracker (mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext());
  dataStorageServiceTracker.open();
  mitk::IDataStorageService* dsService = dataStorageServiceTracker.getService();
  mitk::DataStorage::Pointer dataStorage = dsService->GetDataStorage()->GetDataStorage();

  mitk::NodePredicateProperty::Pointer pred = mitk::NodePredicateProperty::New("xnat.url");
  mitk::DataStorage::SetOfObjects::ConstPointer result = dataStorage->GetSources(selectedNode, pred);
  mitk::DataStorage::SetOfObjects::ConstIterator it = result->Begin();

  QList<ctkXnatObject*> resourceFolders;
  QStringList resourceNames;
  QString url;
  for (;it != result->End(); ++it)
  {
    mitk::DataNode::Pointer node = it->Value();

    std::string xnatUrl("");
    node->GetStringProperty("xnat.url", xnatUrl);
    url = QString::fromStdString(xnatUrl);

    int start = url.lastIndexOf("resources/") + 10; //length of "resources/"
    url = url.left(start);

    QUuid uid = session->httpGet(url);
    resourceFolders = session->httpResults(uid, ctkXnatDefaultSchemaTypes::XSI_RESOURCE);

    foreach (ctkXnatObject* obj, resourceFolders)
    {
      resourceNames << obj->name();
    }
  }

  // Dialog for selecting the upload destination
  QmitkSelectXnatUploadDestinationDialog dialog(session, resourceNames);
  dialog.setWindowTitle("Select XNAT upload destination");
  dialog.SetXnatResourceFolderUrl(url);
  int returnValue = dialog.exec();

  if (returnValue == QDialog::Accepted)
  {
    // Save node
    QString fileName (QString::fromStdString(ReplaceSpecialChars(selectedNode->GetName())));

    if (dynamic_cast<mitk::Image*>(selectedNode->GetData()))
    {
      fileName.append(".nrrd");
    }
    else if (dynamic_cast<mitk::Surface*>(selectedNode->GetData()))
    {
      fileName.append(".vtk");
    }
    else if (dynamic_cast<mitk::PointSet*>(selectedNode->GetData()))
    {
      fileName.append(".mps");
    }
    else
    {
      MITK_WARN << "Could not upload file! File-type not supported";
      QMessageBox msgbox;
      msgbox.setText("Could not upload file! File-type not supported");
      msgbox.setIcon(QMessageBox::Critical);
      msgbox.exec();
      return;
    }

    QString xnatFolder = "XNAT_UPLOADS";
    QDir dir(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext()->getDataFile("").absoluteFilePath());
    dir.mkdir(xnatFolder);

    fileName = dir.path().append("/" + fileName);
    mitk::IOUtil::Save (selectedNode->GetData(), fileName.toStdString());

    // Upload the file to XNAT
    ctkXnatObject* uploadDestination = dialog.GetUploadDestination();
    if (uploadDestination != nullptr)
    {
      ctkXnatFile* file = new ctkXnatFile(uploadDestination);
      file->setLocalFilePath(fileName);
      QFileInfo fileInfo (fileName);
      file->setName(fileInfo.fileName());
      file->save();
    }
  }
  dataStorageServiceTracker.close();
}
Example #28
0
void QNetworkReplyHandler::sendResponseIfNeeded()
{
    m_shouldSendResponse = (m_loadMode != LoadNormal);
    if (m_shouldSendResponse)
        return;

    if (m_reply->error() && !ignoreHttpError(m_reply, m_responseDataSent))
        return;

    if (m_responseSent || !m_resourceHandle)
        return;
    m_responseSent = true;

    ResourceHandleClient* client = m_resourceHandle->client();
    if (!client)
        return;

    WebCore::String contentType = m_reply->header(QNetworkRequest::ContentTypeHeader).toString();
    WebCore::String encoding = extractCharsetFromMediaType(contentType);
    WebCore::String mimeType = extractMIMETypeFromMediaType(contentType);

    if (mimeType.isEmpty()) {
        // let's try to guess from the extension
        QString extension = m_reply->url().path();
        int index = extension.lastIndexOf(QLatin1Char('.'));
        if (index > 0) {
            extension = extension.mid(index + 1);
            mimeType = MIMETypeRegistry::getMIMETypeForExtension(extension);
        }
    }

    KURL url(m_reply->url());
    ResourceResponse response(url, mimeType,
                              m_reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(),
                              encoding, String());

    if (url.isLocalFile()) {
        client->didReceiveResponse(m_resourceHandle, response);
        return;
    }

    // The status code is equal to 0 for protocols not in the HTTP family.
    int statusCode = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    if (url.protocolInHTTPFamily()) {
        String suggestedFilename = filenameFromHTTPContentDisposition(QString::fromAscii(m_reply->rawHeader("Content-Disposition")));

        if (!suggestedFilename.isEmpty())
            response.setSuggestedFilename(suggestedFilename);
        else
            response.setSuggestedFilename(url.lastPathComponent());

        response.setHTTPStatusCode(statusCode);
        response.setHTTPStatusText(m_reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toByteArray().constData());

        // Add remaining headers.
#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
        foreach (const QNetworkReply::RawHeaderPair& pair, m_reply->rawHeaderPairs()) {
            response.setHTTPHeaderField(QString::fromAscii(pair.first), QString::fromAscii(pair.second));
        }
#else
        foreach (const QByteArray& headerName, m_reply->rawHeaderList()) {
            response.setHTTPHeaderField(QString::fromAscii(headerName), QString::fromAscii(m_reply->rawHeader(headerName)));
        }
#endif
    }
Example #29
0
bool logData::setupFromXML() {

    // no log specified
    if (logFileXMLname.isEmpty()) {
        qDebug() << "XML filename not set";
        return false;
    }

    // open XML for reading
    QFile xmlfile( logFileXMLname );
    if( !xmlfile.open( QIODevice::ReadOnly ) ) {
        // could not open
        qDebug() << "Couldn't open XML file";
        return false;}


    // setup XML reader
    QXmlStreamReader * reader = new QXmlStreamReader;
    reader->setDevice( &xmlfile );

    // clear up
    columns.clear();
    eventIndices.clear();
    allLogged = false;
    min = Q_INFINITY;
    max = Q_INFINITY;

    // temp config data
    QString logFileName;

    // parse XML
    while (reader->readNextStartElement()) {

        if (reader->name() == "LogReport") {

            while (reader->readNextStartElement()) {

                if (reader->name() == "AnalogLog") {

                    dataClass = ANALOGDATA;

                    while (reader->readNextStartElement()) {

                        if (reader->name() == "LogFile") {

                            // store logfile name
                            logFileName = reader->readElementText();

                        } else if (reader->name() == "LogFileType") {

                            QString tempStr = reader->readElementText();
                            if (tempStr == "binary") {
                                dataFormat = BINARY;
                            } else if (tempStr == "csv") {
                                dataFormat = CSVFormat;
                            } else if (tempStr == "ssv") {
                                dataFormat = SSVFormat;
                            } else {
                                // invalid file format
                                qDebug() << "Invalid file format";
                                delete reader;
                                return false;
                            }

                        } else if (reader->name() == "LogEndTime") {

                            QString tempStr = reader->readElementText();
                            endTime = tempStr.toDouble();

                        } else if (reader->name() == "LogCol") {

                            column newCol;

                            if (reader->attributes().hasAttribute("index")) {
                                newCol.index = reader->attributes().value("index").toString().toInt();
                            } else {
                                // required attribute
                                qDebug() << "Index attr missing";
                                delete reader;
                                return false;
                            }

                            if (reader->attributes().hasAttribute("heading")) {
                                newCol.heading = reader->attributes().value("heading").toString();
                            } else {
                                // required attribute
                                qDebug() << "Heading attr missing";
                                delete reader;
                                return false;
                            }

                            if (reader->attributes().hasAttribute("dims")) {
                                newCol.dims = reader->attributes().value("dims").toString();
                            } else {
                                // required attribute
                                qDebug() << "Dims attr missing";
                                delete reader;
                                return false;
                            }

                            if (reader->attributes().hasAttribute("type")) {
                                QString tempStr = reader->attributes().value("type").toString();

                                if (tempStr == "double") {
                                    newCol.type = TYPE_DOUBLE;
                                } else if (tempStr == "float") {
                                    newCol.type = TYPE_FLOAT;
                                } else if (tempStr == "int") {
                                    newCol.type = TYPE_INT32;
                                } else if (tempStr == "longint") {
                                    newCol.type = TYPE_INT64;
                                } else if (tempStr == "string") {
                                    newCol.type = TYPE_STRING;
                                } else {
                                    // invalid data type
                                    qDebug() << "Wrong data type label";
                                    delete reader;
                                    return false;
                                }


                            } else {
                                // required attribute
                                qDebug() << "Type attr missing";
                                delete reader;
                                return false;
                            }

                            // as unclosed
                            reader->readNextStartElement();

                            // add column
                            columns.push_back(newCol);

                        } else if (reader->name() == "LogAll") {

                            allLogged = true;
                            column newCol;
                            int size;

                            if (reader->attributes().hasAttribute("size")) {
                                size = reader->attributes().value("size").toString().toInt();
                            } else {
                                // required attribute
                                qDebug() << "Size attr missing";
                                delete reader;
                                return false;
                            }

                            if (reader->attributes().hasAttribute("headings")) {
                                newCol.heading = reader->attributes().value("headings").toString();
                            } else {
                                // required attribute
                                qDebug() << "Headings attr missing";
                                delete reader;
                                return false;
                            }

                            if (reader->attributes().hasAttribute("dims")) {
                                newCol.dims = reader->attributes().value("dims").toString();
                            } else {
                                // required attribute
                                qDebug() << "Dims attr missing";
                                delete reader;
                                return false;
                            }

                            if (reader->attributes().hasAttribute("type")) {
                                QString tempStr = reader->attributes().value("type").toString();

                                if (tempStr == "double") {
                                    newCol.type = TYPE_DOUBLE;
                                } else if (tempStr == "float") {
                                    newCol.type = TYPE_FLOAT;
                                } else if (tempStr == "int") {
                                    newCol.type = TYPE_INT32;
                                } else if (tempStr == "longint") {
                                    newCol.type = TYPE_INT64;
                                } else if (tempStr == "string") {
                                    newCol.type = TYPE_STRING;
                                } else {
                                    // invalid data type
                                    qDebug() << "Wrong data type name";
                                    delete reader;
                                    return false;
                                }

                            } else {
                                // required attribute
                                qDebug() << "Type attr missing";
                                delete reader;
                                return false;
                            }

                            // as unclosed
                            reader->readNextStartElement();

                            // add columns
                            columns.resize(size, newCol);

                            // setup indices
                            for (uint i = 0; i < columns.size(); ++i)
                                columns[i].index = i;

                        } else if (reader->name() == "TimeStep") {

                            if (reader->attributes().hasAttribute("dt")) {
                                timeStep = reader->attributes().value("dt").toString().toDouble();
                            } else {
                                // required attribute
                                qDebug() << "Timestep attr missing";
                                delete reader;
                                return false;
                            }

                        } else {
                            // XML tag not recognised
                            qDebug() << "Unknown tag name " << reader->name();
                            delete reader;
                            return false;
                        }

                    }

                } else if (reader->name() == "EventLog") {

                    dataClass = EVENTDATA;

                    while (reader->readNextStartElement()) {

                        if (reader->name() == "LogFile") {

                            // store logfile name
                            logFileName = reader->readElementText();

                        } else if (reader->name() == "LogFileType") {

                            QString tempStr = reader->readElementText();
                            if (tempStr == "binary") {
                                dataFormat = BINARY;
                            } else if (tempStr == "csv") {
                                dataFormat = CSVFormat;
                            } else if (tempStr == "ssv") {
                                dataFormat = SSVFormat;
                            } else {
                                // invalid file format
                                qDebug() << "File format unkown";
                                delete reader;
                                return false;
                            }

                        } else if (reader->name() == "LogEndTime") {

                            QString tempStr = reader->readElementText();
                            endTime = tempStr.toDouble();

                        } else if (reader->name() == "LogCol") {

                            column newCol;

                            // event port logs don't use the index
                            newCol.index = -1;

                            if (reader->attributes().hasAttribute("heading")) {
                                newCol.heading = reader->attributes().value("heading").toString();
                            } else {
                                // required attribute
                                qDebug() << "Heading attr missing";
                                delete reader;
                                return false;
                            }

                            if (reader->attributes().hasAttribute("dims")) {
                                newCol.dims = reader->attributes().value("dims").toString();
                            } else {
                                // required attribute
                                qDebug() << "Dims attr missing";
                                delete reader;
                                return false;
                            }

                            if (reader->attributes().hasAttribute("type")) {
                                QString tempStr = reader->attributes().value("type").toString();

                                if (tempStr == "double") {
                                    newCol.type = TYPE_DOUBLE;
                                } else if (tempStr == "float") {
                                    newCol.type = TYPE_FLOAT;
                                } else if (tempStr == "int") {
                                    newCol.type = TYPE_INT32;
                                } else if (tempStr == "longint") {
                                    newCol.type = TYPE_INT64;
                                } else if (tempStr == "string") {
                                    newCol.type = TYPE_STRING;
                                } else {
                                    // invalid data type
                                    qDebug() << "Data type unknown";
                                    delete reader;
                                    return false;
                                }

                            } else {
                                // required attribute
                                qDebug() << "Type attr missing";
                                delete reader;
                                return false;
                            }

                            // as unclosed
                            reader->readNextStartElement();

                            // add column
                            columns.push_back(newCol);

                        } else if (reader->name() == "LogAll") {

                            allLogged = true;
                            int size;

                            if (reader->attributes().hasAttribute("size")) {
                                size = reader->attributes().value("size").toString().toInt();
                            } else {
                                // required attribute
                                qDebug() << "Size attr missing";
                                delete reader;
                                return false;
                            }

                            // add indices
                            for (int i = 0; i < size; ++i)
                                eventIndices.push_back(i);

                            // as unclosed
                            reader->readNextStartElement();

                        } else if (reader->name() == "LogIndex") {

                            eventIndices.push_back(reader->readElementText().toInt());


                        } else if (reader->name() == "LogPort") {

                            eventPortName = reader->readElementText();

                        } else if (reader->name() == "TimeStep") {

                            if (reader->attributes().hasAttribute("dt")) {
                                timeStep = reader->attributes().value("dt").toString().toDouble();
                            } else {
                                // required attribute
                                qDebug() << "Timestep attr missing";
                                delete reader;
                                return false;
                            }

                        } else {
                            // XML tag not recognised
                            qDebug() << "XML tag not recognised";
                            delete reader;
                            return false;
                        }

                    }

                } else {
                    // log type not recognised
                    qDebug() << "Log type unknown";
                    delete reader;
                    return false;
                }
            }

        } else {
            // not a LogReport
            qDebug() << "Not a logreport";
            delete reader;
            return false;
        }

    }

    // load the log file
    // get local dir
    QString dirPath = logFileXMLname;
    dirPath.resize(dirPath.lastIndexOf(QDir::separator()));
    QDir localDir(dirPath);

    if (!logFile.isOpen()) {
        logFile.setFileName(localDir.absoluteFilePath(logFileName));
        if( !logFile.open( QIODevice::ReadOnly ) ) {
            // could not open
            qDebug() << "Couldn't open log file " << localDir.absoluteFilePath(logFileName);
            delete reader;
            return false;}
    }

    // resize data carriers
    colData.resize(columns.size());

    // log name
    logName = logFileName;

    // all successful!
    delete reader;
    return true;
}
Example #30
0
/**
 * Syntax:
 * # Comment
 * Id=id
 * File=oldfile[,newfile]
 * AllGroups
 * Group=oldgroup[,newgroup]
 * RemoveGroup=oldgroup
 * Options=[copy,][overwrite,]
 * Key=oldkey[,newkey]
 * RemoveKey=ldkey
 * AllKeys
 * Keys= [Options](AllKeys|(Key|RemoveKey)*)
 * ScriptArguments=arguments
 * Script=scriptfile[,interpreter]
 *
 * Sequence:
 * (Id,(File(Group,Keys)*)*)*
 **/
bool KonfUpdate::updateFile(const QString &filename)
{
    m_currentFilename = filename;
    int i = m_currentFilename.lastIndexOf('/');
    if (i != -1) {
        m_currentFilename = m_currentFilename.mid(i + 1);
    }
    m_skip = true;
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly)) {
        return false;
    }

    log() << "Checking update-file '" << filename << "' for new updates" << endl;

    QTextStream ts(&file);
    ts.setCodec(QTextCodec::codecForName("ISO-8859-1"));
    m_lineCount = 0;
    resetOptions();
    while (!ts.atEnd()) {
        m_line = ts.readLine().trimmed();
        m_lineCount++;
        if (m_line.isEmpty() || (m_line[0] == '#')) {
            continue;
        }
        if (m_line.startsWith(QLatin1String("Id="))) {
            gotId(m_line.mid(3));
        } else if (m_skip) {
            continue;
        } else if (m_line.startsWith(QLatin1String("Options="))) {
            gotOptions(m_line.mid(8));
        } else if (m_line.startsWith(QLatin1String("File="))) {
            gotFile(m_line.mid(5));
        } else if (m_skipFile) {
            continue;
        } else if (m_line.startsWith(QLatin1String("Group="))) {
            gotGroup(m_line.mid(6));
        } else if (m_line.startsWith(QLatin1String("RemoveGroup="))) {
            gotRemoveGroup(m_line.mid(12));
            resetOptions();
        } else if (m_line.startsWith(QLatin1String("Script="))) {
            gotScript(m_line.mid(7));
            resetOptions();
        } else if (m_line.startsWith(QLatin1String("ScriptArguments="))) {
            gotScriptArguments(m_line.mid(16));
        } else if (m_line.startsWith(QLatin1String("Key="))) {
            gotKey(m_line.mid(4));
            resetOptions();
        } else if (m_line.startsWith(QLatin1String("RemoveKey="))) {
            gotRemoveKey(m_line.mid(10));
            resetOptions();
        } else if (m_line == "AllKeys") {
            gotAllKeys();
            resetOptions();
        } else if (m_line == "AllGroups") {
            gotAllGroups();
            resetOptions();
        } else {
            logFileError() << "Parse error" << endl;
        }
    }
    // Flush.
    gotId(QString());

    KDE_struct_stat buff;
    KDE::stat(filename, &buff);
    KConfigGroup cg(m_config, m_currentFilename);
    cg.writeEntry("ctime", int(buff.st_ctime));
    cg.writeEntry("mtime", int(buff.st_mtime));
    cg.sync();
    return true;
}