Example #1
0
bool XMLHandler::processingInstruction(const QString &target, const QString &data)
{
    if(currentNode()->nodeType() == Node::TEXT_NODE)
        exitText();
    // ### handle exceptions
    ProcessingInstructionImpl *pi = m_doc->createProcessingInstruction(target, new DOMStringImpl(data.unicode(), data.length()));
    currentNode()->addChild(pi);
    pi->checkStyleSheet();
    return true;
}
Example #2
0
	String String::fromUtf32(const std::u32string& utf32)
	{
		QString s = QString::fromUcs4((const uint*) utf32.data());
		std::u16string p{(const char16_t*) s.unicode(), size_t(s.size())};
		return String(p);
	}
Example #3
0
CFStringRef QCFString::toCFStringRef(const QString &string)
{
    return CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar *>(string.unicode()),
                                        string.length());
}
Example #4
0
int KStringHandler::naturalCompare(const QString &_a, const QString &_b, Qt::CaseSensitivity caseSensitivity)
{
    // This method chops the input a and b into pieces of
    // digits and non-digits (a1.05 becomes a | 1 | . | 05)
    // and compares these pieces of a and b to each other
    // (first with first, second with second, ...).
    //
    // This is based on the natural sort order code code by Martin Pool
    // http://sourcefrog.net/projects/natsort/
    // Martin Pool agreed to license this under LGPL or GPL.

    // FIXME: Using toLower() to implement case insensitive comparison is
    // sub-optimal, but is needed because we compare strings with
    // localeAwareCompare(), which does not know about case sensitivity.
    // A task has been filled for this in Qt Task Tracker with ID 205990.
    // http://trolltech.com/developer/task-tracker/index_html?method=entry&id=205990
    QString a;
    QString b;
    if (caseSensitivity == Qt::CaseSensitive) {
        a = _a;
        b = _b;
    } else {
        a = _a.toLower();
        b = _b.toLower();
    }

    const QChar* currA = a.unicode(); // iterator over a
    const QChar* currB = b.unicode(); // iterator over b

    if (currA == currB) {
        return 0;
    }

    while (!currA->isNull() && !currB->isNull()) {
        const QChar* begSeqA = currA; // beginning of a new character sequence of a
        const QChar* begSeqB = currB;
        if (currA->unicode() == QChar::ObjectReplacementCharacter) {
            return 1;
        }

        if (currB->unicode() == QChar::ObjectReplacementCharacter) {
            return -1;
        }

        if (currA->unicode() == QChar::ReplacementCharacter) {
            return 1;
        }

        if (currB->unicode() == QChar::ReplacementCharacter) {
            return -1;
        }

        // find sequence of characters ending at the first non-character
        while (!currA->isNull() && !currA->isDigit() && !currA->isPunct() && !currA->isSpace()) {
            ++currA;
        }

        while (!currB->isNull() && !currB->isDigit() && !currB->isPunct() && !currB->isSpace()) {
            ++currB;
        }

        // compare these sequences
        const QStringRef& subA(a.midRef(begSeqA - a.unicode(), currA - begSeqA));
        const QStringRef& subB(b.midRef(begSeqB - b.unicode(), currB - begSeqB));
        const int cmp = QStringRef::localeAwareCompare(subA, subB);
        if (cmp != 0) {
            return cmp < 0 ? -1 : +1;
        }

        if (currA->isNull() || currB->isNull()) {
            break;
        }

        // find sequence of characters ending at the first non-character
        while ((currA->isPunct() || currA->isSpace()) && (currB->isPunct() || currB->isSpace())) {
            if (*currA != *currB) {
                return (*currA < *currB) ? -1 : +1;
            }
            ++currA;
            ++currB;
            if (currA->isNull() || currB->isNull()) {
                break;
            }
        }

        // now some digits follow...
        if ((*currA == QLatin1Char('0')) || (*currB == QLatin1Char('0'))) {
            // one digit-sequence starts with 0 -> assume we are in a fraction part
            // do left aligned comparison (numbers are considered left aligned)
            while (1) {
                if (!currA->isDigit() && !currB->isDigit()) {
                    break;
                } else if (!currA->isDigit()) {
                    return +1;
                } else if (!currB->isDigit()) {
                    return -1;
                } else if (*currA < *currB) {
                    return -1;
                } else if (*currA > *currB) {
                    return + 1;
                }
                ++currA;
                ++currB;
            }
        } else {
            // No digit-sequence starts with 0 -> assume we are looking at some integer
            // do right aligned comparison.
            //
            // The longest run of digits wins. That aside, the greatest
            // value wins, but we can't know that it will until we've scanned
            // both numbers to know that they have the same magnitude.

            bool isFirstRun = true;
            int weight = 0;
            while (1) {
                if (!currA->isDigit() && !currB->isDigit()) {
                    if (weight != 0) {
                        return weight;
                    }
                    break;
                } else if (!currA->isDigit()) {
                    if (isFirstRun) {
                        return *currA < *currB ? -1 : +1;
                    } else {
                        return -1;
                    }
                } else if (!currB->isDigit()) {
                    if (isFirstRun) {
                        return *currA < *currB ? -1 : +1;
                    } else {
                        return +1;
                    }
                } else if ((*currA < *currB) && (weight == 0)) {
                    weight = -1;
                } else if ((*currA > *currB) && (weight == 0)) {
                    weight = + 1;
                }
                ++currA;
                ++currB;
                isFirstRun = false;
            }
        }
    }

    if (currA->isNull() && currB->isNull()) {
        return 0;
    }

    return currA->isNull() ? -1 : + 1;
}
Example #5
0
	String String::fromUtf8(const std::string& utf8)
	{
		QString s = QString::fromStdString(utf8);
		std::u16string p{(const char16_t*) s.unicode(), size_t(s.size())};
		return String(p);
	}
Example #6
0
// nsClipboard::GetNativeClipboardData ie. Paste
//
NS_IMETHODIMP
nsClipboard::GetNativeClipboardData(nsITransferable *aTransferable,
                                    QClipboard::Mode clipboardMode)
{
    if (nullptr == aTransferable)
    {
        NS_WARNING("GetNativeClipboardData: Transferable is null!");
        return NS_ERROR_FAILURE;
    }

    // get flavor list that includes all acceptable flavors (including
    // ones obtained through conversion)
    nsCOMPtr<nsISupportsArray> flavorList;
    nsresult errCode = aTransferable->FlavorsTransferableCanImport(
                           getter_AddRefs(flavorList));

    if (NS_FAILED(errCode))
    {
        NS_WARNING("nsClipboard::GetNativeClipboardData(): no FlavorsTransferable!");
        return NS_ERROR_FAILURE;
    }

    QClipboard *cb = QApplication::clipboard();
    const QMimeData *mimeData = cb->mimeData(clipboardMode);

    // Walk through flavors and see which flavor matches the one being pasted
    uint32_t flavorCount;
    flavorList->Count(&flavorCount);
    nsAutoCString foundFlavor;

    for (uint32_t i = 0; i < flavorCount; ++i)
    {
        nsCOMPtr<nsISupports> genericFlavor;
        flavorList->GetElementAt(i,getter_AddRefs(genericFlavor));
        nsCOMPtr<nsISupportsCString> currentFlavor(do_QueryInterface( genericFlavor) );

        if (currentFlavor)
        {
            nsXPIDLCString flavorStr;
            currentFlavor->ToString(getter_Copies(flavorStr));

            // Ok, so which flavor the data being pasted could be?
            // Text?
            if (!strcmp(flavorStr.get(), kUnicodeMime) && mimeData->hasText())
            {
                // Clipboard has text and flavor accepts text, so lets
                // handle the data as text
                foundFlavor = nsAutoCString(flavorStr);

                // Get the text data from clipboard
                QString text = mimeData->text();
                const QChar *unicode = text.unicode();
                // Is there a more correct way to get the size in UTF16?
                uint32_t len = (uint32_t) 2*text.size();

                // And then to genericDataWrapper
                nsCOMPtr<nsISupports> genericDataWrapper;
                nsPrimitiveHelpers::CreatePrimitiveForData(
                    foundFlavor.get(),
                    (void*)unicode,
                    len,
                    getter_AddRefs(genericDataWrapper));
                // Data is good, set it to the transferable
                aTransferable->SetTransferData(foundFlavor.get(),
                                               genericDataWrapper,len);
                // And thats all
                break;
            }

            // html?
            if (!strcmp(flavorStr.get(), kHTMLMime) && mimeData->hasHtml())
            {
                // Clipboard has text/html and flavor accepts text/html, so lets
                // handle the data as text/html
                foundFlavor = nsAutoCString(flavorStr);

                // Get the text data from clipboard
                QString html = mimeData->html();
                const QChar *unicode = html.unicode();
                // Is there a more correct way to get the size in UTF16?
                uint32_t len = (uint32_t) 2*html.size();

                // And then to genericDataWrapper
                nsCOMPtr<nsISupports> genericDataWrapper;
                nsPrimitiveHelpers::CreatePrimitiveForData(
                    foundFlavor.get(),
                    (void*)unicode,
                    len,
                    getter_AddRefs(genericDataWrapper));
                // Data is good, set it to the transferable
                aTransferable->SetTransferData(foundFlavor.get(),
                                               genericDataWrapper,len);
                // And thats all
                break;
            }

            // Image?
            if ((  !strcmp(flavorStr.get(), kJPEGImageMime)
                    || !strcmp(flavorStr.get(), kJPGImageMime)
                    || !strcmp(flavorStr.get(), kPNGImageMime)
                    || !strcmp(flavorStr.get(), kGIFImageMime))
                    && mimeData->hasImage())
            {
                // Try to retrieve an image from clipboard
                QImage image = cb->image();
                if(image.isNull())
                    continue;

                // Lets set the image format
                QByteArray imageFormat;
                if (!strcmp(flavorStr.get(), kJPEGImageMime) || !strcmp(flavorStr.get(), kJPGImageMime))
                    imageFormat = "jpeg";
                else if (!strcmp(flavorStr.get(), kPNGImageMime))
                    imageFormat = "png";
                else if (!strcmp(flavorStr.get(), kGIFImageMime))
                    imageFormat = "gif";
                else
                    continue;

                // Write image from clippboard to a QByteArrayBuffer
                QByteArray imageData;
                QBuffer imageBuffer(&imageData);
                QImageWriter imageWriter(&imageBuffer, imageFormat);
                if(!imageWriter.write(image))
                    continue;

                // Add the data to inputstream
                nsCOMPtr<nsIInputStream> byteStream;
                NS_NewByteInputStream(getter_AddRefs(byteStream), imageData.constData(),
                                      imageData.size(), NS_ASSIGNMENT_COPY);
                // Data is good, set it to the transferable
                aTransferable->SetTransferData(flavorStr, byteStream, sizeof(nsIInputStream*));

                imageBuffer.close();

                // And thats all
                break;
            }

            // Other mimetype?
            // Trying to forward the data "as is"
            if(mimeData->hasFormat(flavorStr.get()))
            {
                // get the data from the clipboard
                QByteArray clipboardData = mimeData->data(flavorStr.get());
                // And add it to genericDataWrapper
                nsCOMPtr<nsISupports> genericDataWrapper;
                nsPrimitiveHelpers::CreatePrimitiveForData(
                    foundFlavor.get(),
                    (void*) clipboardData.data(),
                    clipboardData.size(),
                    getter_AddRefs(genericDataWrapper));

                // Data is good, set it to the transferable
                aTransferable->SetTransferData(foundFlavor.get(),
                                               genericDataWrapper,clipboardData.size());
                // And thats all
                break;
            }
        }
    }

    return NS_OK;
}
Example #7
0
/*!
    Constructs a string matcher that will search for \a pattern, with
    case sensitivity \a cs.

    Call indexIn() to perform a search.
*/
QStringMatcher::QStringMatcher(const QString &pattern, Qt::CaseSensitivity cs)
    : d_ptr(0), q_pattern(pattern), q_cs(cs)
{
    bm_init_skiptable((const ushort *)pattern.unicode(), pattern.size(), q_skiptable, cs);
}
/**
 * Retrieves the data stored in this object and store the result in
 * pMedium.
 *
 * @return  IPRT status code.
 * @return  HRESULT
 * @param   pFormatEtc
 * @param   pMedium
 */
STDMETHODIMP UIDnDDataObject::GetData(LPFORMATETC pFormatEtc, LPSTGMEDIUM pMedium)
{
    AssertPtrReturn(pFormatEtc, DV_E_FORMATETC);
    AssertPtrReturn(pMedium, DV_E_FORMATETC);

    HRESULT hr = DV_E_FORMATETC;

    LPFORMATETC pThisFormat = NULL;
    LPSTGMEDIUM pThisMedium = NULL;

    LogFlowThisFunc(("\n"));

    /* Format supported? */
    ULONG lIndex;
    if (   LookupFormatEtc(pFormatEtc, &lIndex)
        && lIndex < m_cFormats) /* Paranoia. */
    {
        pThisMedium = &m_pStgMedium[lIndex];
        AssertPtr(pThisMedium);
        pThisFormat = &m_pFormatEtc[lIndex];
        AssertPtr(pThisFormat);

        LogFlowThisFunc(("pThisMedium=%p, pThisFormat=%p\n", pThisMedium, pThisFormat));
        LogFlowThisFunc(("mStatus=%RU32\n", m_enmStatus));
        switch (m_enmStatus)
        {
            case DnDDataObjectStatus_Dropping:
            {
#if 0
                LogRel3(("DnD: Dropping\n"));
                LogFlowFunc(("Waiting for event ...\n"));
                int rc2 = RTSemEventWait(m_SemEvent, RT_INDEFINITE_WAIT);
                LogFlowFunc(("rc=%Rrc, mStatus=%RU32\n", rc2, m_enmStatus));
#endif
                break;
            }

            case DnDDataObjectStatus_Dropped:
            {
                LogRel3(("DnD: Dropped\n"));
                LogRel3(("DnD: cfFormat=%RI16, sFormat=%s, tyMed=%RU32, dwAspect=%RU32\n",
                         pThisFormat->cfFormat, UIDnDDataObject::ClipboardFormatToString(pFormatEtc->cfFormat),
                         pThisFormat->tymed, pThisFormat->dwAspect));
                LogRel3(("DnD: Got strFormat=%s, pvData=%p, cbData=%RU32\n",
                         m_strFormat.toAscii().constData(), m_pvData, m_cbData));

                QVariant::Type vaType;
                QString strMIMEType;
                if (    (pFormatEtc->tymed & TYMED_HGLOBAL)
                     && (pFormatEtc->dwAspect == DVASPECT_CONTENT)
                     && (   pFormatEtc->cfFormat == CF_TEXT
                         || pFormatEtc->cfFormat == CF_UNICODETEXT)
                   )
                {
                    strMIMEType = "text/plain"; /** @todo Indicate UTF8 encoding? */
                    vaType = QVariant::String;
                }
                else if (   (pFormatEtc->tymed & TYMED_HGLOBAL)
                         && (pFormatEtc->dwAspect == DVASPECT_CONTENT)
                         && (pFormatEtc->cfFormat == CF_HDROP))
                {
                    strMIMEType = "text/uri-list";
                    vaType = QVariant::StringList;
                }
#if 0 /* More formats; not needed right now. */
                else if (   (pFormatEtc->tymed & TYMED_ISTREAM)
                        && (pFormatEtc->dwAspect == DVASPECT_CONTENT)
                        && (pFormatEtc->cfFormat == CF_FILECONTENTS))
                {

                }
                else if  (   (pFormatEtc->tymed & TYMED_HGLOBAL)
                          && (pFormatEtc->dwAspect == DVASPECT_CONTENT)
                          && (pFormatEtc->cfFormat == CF_FILEDESCRIPTOR))
                {

                }
                else if (   (pFormatEtc->tymed & TYMED_HGLOBAL)
                         && (pFormatEtc->cfFormat == CF_PREFERREDDROPEFFECT))
                {
                    HGLOBAL hData = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT, sizeof(DWORD));
                    DWORD *pdwEffect = (DWORD *)GlobalLock(hData);
                    AssertPtr(pdwEffect);
                    *pdwEffect = DROPEFFECT_COPY;
                    GlobalUnlock(hData);

                    pMedium->hGlobal = hData;
                    pMedium->tymed = TYMED_HGLOBAL;
                }
#endif
                LogRel3(("DnD: strMIMEType=%s, vaType=%ld\n", strMIMEType.toAscii().constData(), vaType));

                int rc;

                if (!m_fDataRetrieved)
                {
                    if (m_pDnDHandler)
                    {
                        rc = m_pDnDHandler->retrieveData(Qt::CopyAction,
                                                         strMIMEType, vaType, m_vaData);
                    }
                    else
                        rc = VERR_NOT_FOUND;

                    m_fDataRetrieved = true;
                    LogFlowFunc(("Retrieving data ended with %Rrc\n", rc));
                }
                else /* Data already been retrieved. */
                    rc = VINF_SUCCESS;

                if (   RT_SUCCESS(rc)
                    && m_vaData.isValid())
                {
                    if (   strMIMEType.startsWith("text/uri-list")
                               /* One item. */
                        && (   m_vaData.canConvert(QVariant::String)
                               /* Multiple items. */
                            || m_vaData.canConvert(QVariant::StringList))
                       )
                    {
                        QStringList lstFilesURI = m_vaData.toStringList();
                        QStringList lstFiles;
                        for (size_t i = 0; i < lstFilesURI.size(); i++)
                        {
                            char *pszFilePath = RTUriFilePath(lstFilesURI.at(i).toAscii().constData());
                            if (pszFilePath)
                            {
                                lstFiles.append(pszFilePath);
                                RTStrFree(pszFilePath);
                            }
                            else /* Unable to parse -- refuse entire request. */
                            {
                                lstFiles.clear();
                                rc = VERR_INVALID_PARAMETER;
                                break;
                            }
                        }

                        size_t cFiles = lstFiles.size();
                        LogFlowThisFunc(("Files (%zu)\n", cFiles));
                        if (   RT_SUCCESS(rc)
                            && cFiles)
                        {
                            size_t cchFiles = 0; /* Number of characters. */
                            for (size_t i = 0; i < cFiles; i++)
                            {
                                const char *pszFile = lstFiles.at(i).toAscii().constData();
                                cchFiles += strlen(pszFile);
                                cchFiles += 1; /* Terminating '\0'. */
                                LogFlowThisFunc(("\tFile: %s (cchFiles=%zu)\n", pszFile, cchFiles));
                            }

                            /* List termination with '\0'. */
                            cchFiles++;

                            size_t cbBuf = sizeof(DROPFILES) + (cchFiles * sizeof(RTUTF16));
                            DROPFILES *pDropFiles = (DROPFILES *)RTMemAllocZ(cbBuf);
                            if (pDropFiles)
                            {
                                /* Put the files list right after our DROPFILES structure. */
                                pDropFiles->pFiles = sizeof(DROPFILES); /* Offset to file list. */
                                pDropFiles->fWide  = 1;                 /* We use Unicode. Always. */

                                uint8_t *pCurFile = (uint8_t *)pDropFiles + pDropFiles->pFiles;
                                AssertPtr(pCurFile);

                                LogFlowThisFunc(("Encoded:\n"));
                                for (size_t i = 0; i < cFiles; i++)
                                {
                                    const char *pszFile = lstFiles.at(i).toUtf8().constData();
                                    Assert(strlen(pszFile));

                                    size_t cchCurFile;
                                    PRTUTF16 pwszFile;
                                    rc = RTStrToUtf16(pszFile, &pwszFile);
                                    if (RT_SUCCESS(rc))
                                    {
                                        cchCurFile = RTUtf16Len(pwszFile);
                                        Assert(cchCurFile);
                                        memcpy(pCurFile, pwszFile, cchCurFile * sizeof(RTUTF16));
                                        RTUtf16Free(pwszFile);
                                    }
                                    else
                                        break;

                                    pCurFile += cchCurFile * sizeof(RTUTF16);

                                    /* Terminate current file name. */
                                    *pCurFile = L'\0';
                                    pCurFile += sizeof(RTUTF16);

                                    LogFlowThisFunc(("\t#%zu: cchCurFile=%zu\n", i, cchCurFile));
                                }

                                if (RT_SUCCESS(rc))
                                {
                                    *pCurFile = L'\0'; /* Final list terminator. */

                                    /*
                                     * Fill out the medium structure we're going to report back.
                                     */
                                    pMedium->tymed          = TYMED_HGLOBAL;
                                    pMedium->pUnkForRelease = NULL;
                                    pMedium->hGlobal        = GlobalAlloc(  GMEM_ZEROINIT
                                                                          | GMEM_MOVEABLE
                                                                          | GMEM_DDESHARE, cbBuf);
                                    if (pMedium->hGlobal)
                                    {
                                        LPVOID pvMem = GlobalLock(pMedium->hGlobal);
                                        if (pvMem)
                                        {
                                            memcpy(pvMem, pDropFiles, cbBuf);
                                            GlobalUnlock(pMedium->hGlobal);

                                            hr = S_OK;
                                        }
                                        else
                                            rc = VERR_ACCESS_DENIED;
                                    }
                                    else
                                        rc = VERR_NO_MEMORY;

                                    LogFlowThisFunc(("Copying to TYMED_HGLOBAL (%zu bytes): %Rrc\n", cbBuf, rc));
                                }

                                RTMemFree(pDropFiles);
                            }
                            else
                                rc = VERR_NO_MEMORY;

                            if (RT_FAILURE(rc))
                                LogFlowThisFunc(("Failed with %Rrc\n", rc));
                        }
                    }
                    else if (   strMIMEType.startsWith("text/plain")
                             && m_vaData.canConvert(QVariant::String))
                    {
                        const bool fUnicode = pFormatEtc->cfFormat == CF_UNICODETEXT;
                        const size_t cbCh   = fUnicode
                                            ? sizeof(WCHAR) : sizeof(char);

                        QString strText = m_vaData.toString();
                        size_t cbSrc = strText.length() * cbCh;
                        Assert(cbSrc);
                        LPCVOID pvSrc = fUnicode
                                      ? (void *)strText.unicode()
                                      : (void *)strText.toAscii().constData();
                        AssertPtr(pvSrc);

                        LogFlowFunc(("pvSrc=0x%p, cbSrc=%zu, cbCh=%zu, fUnicode=%RTbool\n",
                                     pvSrc, cbSrc, cbCh, fUnicode));

                        pMedium->tymed          = TYMED_HGLOBAL;
                        pMedium->pUnkForRelease = NULL;
                        pMedium->hGlobal        = GlobalAlloc(GHND | GMEM_SHARE, cbSrc);
                        if (pMedium->hGlobal)
                        {
                            LPVOID pvDst = GlobalLock(pMedium->hGlobal);
                            if (pvDst)
                            {
                                memcpy(pvDst, pvSrc, cbSrc);
                                GlobalUnlock(pMedium->hGlobal);
                            }
                            else
                                rc = VERR_ACCESS_DENIED;

                            hr = S_OK;
                        }
                        else
                            hr  = VERR_NO_MEMORY;
                    }
                    else
                        LogRel2(("DnD: MIME type '%s' not supported\n", strMIMEType.toAscii().constData()));

                    LogFlowThisFunc(("Handling formats ended with rc=%Rrc\n", rc));
                }

                break;
            }

            default:
                break;
        }
    }

    /*
     * Fallback in error case.
     */
    if (FAILED(hr))
    {
        if (pThisMedium)
        {
            switch (pThisMedium->tymed)
            {

            case TYMED_HGLOBAL:
                pMedium->hGlobal = (HGLOBAL)OleDuplicateData(pThisMedium->hGlobal,
                                                             pThisFormat->cfFormat,
                                                             0 /* Flags */);
                break;

            default:
                break;
            }
        }

        if (pFormatEtc)
            pMedium->tymed = pFormatEtc->tymed;

        pMedium->pUnkForRelease = NULL;
    }

    LogFlowThisFunc(("Returning hr=%Rhrc\n", hr));
    return hr;
}
const kvi_wchar_t * KviIrcView::getTextLine(
		int iMsgType,
		const kvi_wchar_t * data_ptr,
		KviIrcViewLine *line_ptr,
		bool bEnableTimeStamp,
		const QDateTime& datetime_param
	)
{
	const kvi_wchar_t* pUnEscapeAt = 0;

	// Splits the text data in lines (separated by '\n')

	// NOTE: This function may be NOT reentrant
	//   ... no function in this file is supposed to be thread safe anyway

	int iTextIdx  = 0;       //we're at the beginning in the buffer
	int iCurChunk = 0;
	int blockLen;

	register const kvi_wchar_t *p = data_ptr;

	//Alloc the first attribute
	line_ptr->uChunkCount = 1;
	line_ptr->pChunks = (KviIrcViewLineChunk *)KviMemory::allocate(sizeof(KviIrcViewLineChunk));
	//And fill it up
	line_ptr->pChunks[0].type = KviControlCodes::Color;
	line_ptr->pChunks[0].iTextStart = 0;
	line_ptr->pChunks[0].colors.back = KVI_OPTION_MSGTYPE(iMsgType).back();
	line_ptr->pChunks[0].colors.fore = KVI_OPTION_MSGTYPE(iMsgType).fore();
	line_ptr->pChunks[0].customFore = QColor();

	// print a nice timestamp at the begin of the first line
	if(bEnableTimeStamp && KVI_OPTION_BOOL(KviOption_boolIrcViewTimestamp))
	{
		QString szTimestamp;
		QDateTime datetime = datetime_param;
		if (!datetime.isValid()) datetime = QDateTime::currentDateTime();
		datetime = datetime.toTimeSpec(KVI_OPTION_BOOL(KviOption_boolIrcViewTimestampUTC) ? Qt::UTC : Qt::LocalTime);
		szTimestamp=datetime.toString(KVI_OPTION_STRING(KviOption_stringIrcViewTimestampFormat));
		szTimestamp.append(' ');
		int iTimeStampLength=szTimestamp.length();

		if(KVI_OPTION_BOOL(KviOption_boolUseSpecialColorForTimestamp))
		{
			// we need three chunks: the first one uses the default colors
			// for the message type, the second one the special colors
			// of the timestamp and the third one goes back to the defaults
			line_ptr->pChunks[0].iTextLen = 0;

			line_ptr->uChunkCount=3;
			line_ptr->pChunks=(KviIrcViewLineChunk *)KviMemory::reallocate((void *)line_ptr->pChunks,3 * sizeof(KviIrcViewLineChunk));

			line_ptr->pChunks[1].type = KviControlCodes::Color;
			line_ptr->pChunks[1].iTextStart = 0;
			line_ptr->pChunks[1].iTextLen = iTimeStampLength-1;
			line_ptr->pChunks[1].colors.back = KVI_OPTION_UINT(KviOption_uintTimeStampBackground);
			line_ptr->pChunks[1].colors.fore = KVI_OPTION_UINT(KviOption_uintTimeStampForeground);

			line_ptr->pChunks[2].type = KviControlCodes::Color;
			line_ptr->pChunks[2].iTextStart = iTimeStampLength-1;
			line_ptr->pChunks[2].iTextLen = 1;
			line_ptr->pChunks[2].colors.back = KVI_OPTION_MSGTYPE(iMsgType).back();
			line_ptr->pChunks[2].colors.fore = KVI_OPTION_MSGTYPE(iMsgType).fore();
			line_ptr->pChunks[2].customFore=QColor();
			iCurChunk+=2;
		} else {
			// only one chunk
			line_ptr->pChunks[0].iTextLen = iTimeStampLength;
		}

		// We need the timestamp string to be added
		// alloc the necessary space
		line_ptr->szText.resize(iTimeStampLength);

		iTextIdx = iTimeStampLength;                     // the rest of the string will begin 11 chars later

		// throw away const: we WANT to set the chars :D
		register QChar * data_ptr_aux = (QChar *)line_ptr->szText.unicode();
		register QChar * stamp_ptr_aux = (QChar *)szTimestamp.unicode();

		//copy the timestamp into line_ptr->szText.unicode()
		for(int i=0;i<iTimeStampLength;i++)
			*data_ptr_aux++  = *stamp_ptr_aux++;
	} else {
		// Timestamp not needed... but we don't want null strings floating around
		line_ptr->szText = "";
		line_ptr->pChunks[0].iTextLen = 0;
	}

	//
	// Ok... a couple of macros that occur really frequently
	// in the following code...
	// these could work well as functions too...but the macros are a lot faster :)
	//

/*
 * Profane description: this adds a block of text of known length to a already created chunk inside this line.
 */
#define APPEND_LAST_TEXT_BLOCK(__data_ptr,__data_len) \
	blockLen = (__data_len); \
	line_ptr->pChunks[iCurChunk].iTextLen += blockLen; \
	kvi_appendWCharToQStringWithLength(&(line_ptr->szText),__data_ptr,__data_len); \
	iTextIdx+=blockLen;

/*
 * Profane description: this adds a block of text of known length to a already created chunk inside this line.
 * text is hidden (eg: we want to display an emoticon instead of the ":)" text, so we insert it hidden)
 */

#define APPEND_LAST_TEXT_BLOCK_HIDDEN_FROM_NOW(__data_ptr,__data_len) \
	blockLen = (__data_len); \
	kvi_appendWCharToQStringWithLength(&(line_ptr->szText),__data_ptr,__data_len); \
	iTextIdx+=blockLen;

/*
 * Profane description: this is dummy
 */

#define APPEND_ZERO_LENGTH_BLOCK(__data_ptr) /* does nothing */

/*
 * Profane description: this adds a new chunk to the current line of the specified type. A chunk is a block of text
 * with similar style properties (mainly with the same color)
 */

#define NEW_LINE_CHUNK(_chunk_type) \
	line_ptr->uChunkCount++; \
	line_ptr->pChunks=(KviIrcViewLineChunk *)KviMemory::reallocate((void *)line_ptr->pChunks, \
			line_ptr->uChunkCount * sizeof(KviIrcViewLineChunk)); \
	iCurChunk++; \
	line_ptr->pChunks[iCurChunk].type = _chunk_type; \
	line_ptr->pChunks[iCurChunk].iTextStart = iTextIdx; \
	line_ptr->pChunks[iCurChunk].iTextLen = 0; \
	line_ptr->pChunks[iCurChunk].customFore=iCurChunk ? line_ptr->pChunks[iCurChunk-1].customFore : QColor();

	// EOF Macros

	int partLen;

/*
 * Some additional description for the profanes: we want a fast way to check the presence of "active objects we have to process" in lines of text;
 * such objects can be: EOF, urls, mirc control characters, emoticons, and so on. We implemented a jump table to accomplish this task very fast.
 * This jump table is an array[256] containing label addresses (imagine them as functions). So something like "goto array[4];" is valid construct
 * in C, that equivals to a function call to a function that starts on that label's line of code.
 * Imagine to parse the input line one character at once and match it (as a switch can do) agains this big array. Every 1-byte character corresponds
 * to an ascii integer between 0 and 255. If the array value for that integer key is defined and !=0, we jump to the corrispective label address.
 * Example, if we find a "H" (72) we'll "goto char_to_check_jump_table[72]", aka "goto check_http_url".
 * There exists two different versions of this tricky code, we switch them depending on the compiler abilities to accept our bad code :)
 */

#ifdef COMPILE_USE_DYNAMIC_LABELS

	// Herezy :)

	// This is not only usage of the *Evil Goto(tm)*
	// This is also a *rather unclear* use of the *Really Evil Goto(tm)*
	// char_to_check_jump_table is a table of dynamic label addresses...
	// we use it to jump to the proper check
	// loop_begin is a dynamic label, and we use it to
	// return to the appropriate loop
	// This is again BAD PROGRAMMING(TM) :).... but it is faster than
	// the version with no dynamic gotos, and really faster
	// that any version without gotos that came into my mind...
	//
	// This code will prolly work only with GCC...(and even needs a "smart" one)

	// Again did two versions... the first was:
	//
	//  if(void * jmp_address = char_to_check_jump_table[*((unsigned char *)p)])goto *jmp_address;
	//    18a3:	8b 55 f0             	movl   0xfffffff0(%ebp),%edx
	//    18a6:	31 c0                	xorl   %eax,%eax
	//    18a8:	8a 02                	movb   (%edx),%al
	//    18aa:	8b 04 85 20 00 00 00 	movl   0x20(,%eax,4),%eax
	//    18b1:	85 c0                	testl  %eax,%eax
	//    18b3:	74 02                	je     18b7 <KviIrcView::getTextLine(int, char const *, KviIrcViewLine *)+0x1f3>
	//    18b5:	ff e0                	jmp    *%eax
	//
	// I even had a nicer version:
	//
	//  goto *(char_to_check_jump_table[*((unsigned char *)p)]);
	//    18a3:	8b 55 f0             	movl   0xfffffff0(%ebp),%edx
	//    18a6:	31 c0                	xorl   %eax,%eax
	//    18a8:	8a 02                	movb   (%edx),%al
	//    18aa:	ff 24 85 20 00 00 00 	jmp    *0x20(,%eax,4)
	//
	// but sth tells me that "jmp *0x20(,%eax,4)" takes a loooooot of clock ticks...
	// ...we have less instructions, but the code takes longer to execute (7-8% longer)
	// it might be also due to pipeline tricks, jump "next instruction precalculation" stuff...

	// So we end up using the first version here

	void * loop_begin;

	static void * char_to_check_jump_table[256]=
	{
		&&found_end_of_buffer  ,0                      ,&&found_mirc_escape    ,&&found_color_escape   ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,&&found_end_of_line    ,0                      ,
		0                      ,&&found_command_escape ,0                      ,&&found_mirc_escape    ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,&&found_mirc_escape    ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,&&found_icon_escape    ,0                      ,&&found_mirc_escape    , // 000-031
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      , // 032-047
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,&&check_emoticon_char  ,&&check_emoticon_char  ,
		0                      ,&&check_emoticon_char  ,0                      ,0                      , // 048-063 // 61='=' , 59=';' , 58=':'
		0                      ,0                      ,0                      ,0                      ,
		0                      ,&&check_e2k_url        ,&&check_file_or_ftp_url,0                      ,
		&&check_http_url       ,&&check_irc_url        ,0                      ,0                      ,
		0                      ,&&check_mailto_or_magnet_url     ,0            ,0                      , // 064-079  // 070==F 072==H 073==I  077==M
		0                      ,0                      ,0                      ,&&check_spotify_url    ,
		0                      ,0                      ,0                      ,&&check_www_url        ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      , // 080-095  // 083==S 087==W
		0                      ,0                      ,0                      ,0                      ,
		0                      ,&&check_e2k_url        ,&&check_file_or_ftp_url,0                      ,
		&&check_http_url       ,&&check_irc_url        ,0                      ,0                      ,
		0                      ,&&check_mailto_or_magnet_url     ,0            ,0                      , // 096-111  // 101=e 102=f 104=h 105=i 109==m
		0                      ,0                      ,0                      ,&&check_spotify_url    ,
		0                      ,0                      ,0                      ,&&check_www_url        ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      , // 112-127  // 115==s 119==w
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      , // 128-133
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      , // 134-159
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      , // 160-175
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      , // 176-191
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      , // 192-207
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      , // 208-223
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      , // 224-239
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                      ,
		0                      ,0                      ,0                      ,0                        // 240-255
	};

	if(KVI_OPTION_BOOL(KviOption_boolIrcViewUrlHighlighting) || KVI_OPTION_BOOL(KviOption_boolDrawEmoticons))
	{
		loop_begin = &&highlighting_check_loop;               // get the address of the return label
		// forever loop
highlighting_check_loop:
		// yet more optimized
		if(*((unsigned short *)p) < 0xff)
			if(void * jmp_address = char_to_check_jump_table[*((unsigned short *)p)])goto *jmp_address;
			// goto *(char_to_check_jump_table[*((unsigned char *)p)]); <--- replace 0 with &nothing_found
//nothing_found:
		p++;
		goto highlighting_check_loop;
		// never here
	} else {
Example #10
0
QString Q3FileDialog::macGetSaveFileName(const QString &start, const QString &filter,
                                         QString *, QWidget *parent, const char* /*name*/,
                                         const QString& caption, QString *selectedFilter)
{
    OSErr err;
    QString retstr;
    NavDialogCreationOptions options;
    NavGetDefaultDialogCreationOptions(&options);
    static const int w = 450, h = 350;
    options.optionFlags |= kNavDontConfirmReplacement;
    options.modality = kWindowModalityAppModal;
    options.location.h = options.location.v = -1;
    QString workingDir;
    QString initialSelection;
    if (!start.isEmpty()) {
        Q3UrlOperator u(encodeFileName(start));
        if (u.isLocalFile() && QFileInfo(u.path()).isDir()) {
            workingDir = start;
        } else {
            if (u.isLocalFile()) {
                QFileInfo fi(u.dirPath());
                if (fi.exists()) {
                    workingDir = u.dirPath();
                    initialSelection = u.fileName();
                }
            } else {
                workingDir = u.toString();
            }
        }
        if (!initialSelection.isEmpty())
            options.saveFileName = CFStringCreateWithCharacters(0,
                                                            (UniChar *)initialSelection.unicode(),
                                                            initialSelection.length());
    }
    if(!caption.isEmpty())
        options.windowTitle = CFStringCreateWithCharacters(NULL, (UniChar *)caption.unicode(),
                                                           caption.length());
    if(parent && parent->isVisible()) {
        Qt::WindowType wt = parent->window()->windowType();
        if (wt != Qt::Desktop && wt != Qt::Sheet && wt != Qt::Drawer) {
            options.modality = kWindowModalityWindowModal;
            options.parentWindow = qt_mac_window_for(parent);
        } else {
            parent = parent->window();
            QString s = parent->windowTitle();
            options.clientName = CFStringCreateWithCharacters(NULL, (UniChar *)s.unicode(), s.length());
            options.location.h = (parent->x() + (parent->width() / 2)) - (w / 2);
            options.location.v = (parent->y() + (parent->height() / 2)) - (h / 2);

            QRect r = QApplication::desktop()->screenGeometry(
                QApplication::desktop()->screenNumber(parent));
            if(options.location.h + w > r.right())
                options.location.h -= (options.location.h + w) - r.right() + 10;
            if(options.location.v + h > r.bottom())
                options.location.v -= (options.location.v + h) - r.bottom() + 10;
        }
    } else if(QWidget *p = qApp->mainWidget()) {
        static int last_screen = -1;
        int scr = QApplication::desktop()->screenNumber(p);
        if(last_screen != scr) {
            QRect r = QApplication::desktop()->screenGeometry(scr);
            options.location.h = (r.x() + (r.width() / 2)) - (w / 2);
            options.location.v = (r.y() + (r.height() / 2)) - (h / 2);
        }
    }

    QList<qt_mac_filter_name*> filts = makeFiltersList(filter);
    qt_mac_nav_filter_type t;
    t.index = 0;
    t.filts = &filts;
    if(filts.count() > 1) {
        int i = 0;
        CFStringRef *arr = (CFStringRef *)malloc(sizeof(CFStringRef) * filts.count());
        for (QList<qt_mac_filter_name*>::Iterator it = filts.begin(); it != filts.end(); ++it) {
            QString rg = (*it)->description;
            arr[i++] = CFStringCreateWithCharacters(NULL, (UniChar *)rg.unicode(), rg.length());
        }
        options.popupExtension = CFArrayCreate(NULL, (const void **)arr, filts.count(), NULL);
    }

    NavDialogRef dlg;
    if(NavCreatePutFileDialog(&options, 'cute', kNavGenericSignature, make_navProcUPP(),
                              (void *) (filts.isEmpty() ? NULL : &t), &dlg)) {
        qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
        return retstr;
    }
    if (!workingDir.isEmpty()) {
        FSRef fsref;
        if (qt_mac_create_fsref(workingDir, &fsref) == noErr) {
            AEDesc desc;
            if (AECreateDesc(typeFSRef, &fsref, sizeof(FSRef), &desc) == noErr)
                NavCustomControl(dlg, kNavCtlSetLocation, (void*)&desc);
        }
    }
    NavDialogRun(dlg);
    if (selectedFilter) {
        NavMenuItemSpec navSpec;
        bzero(&navSpec, sizeof(NavMenuItemSpec));
        qt_mac_filter_name *sel_filt_name = makeFiltersList(*selectedFilter).at(0);
        for (int i = 0; i < filts.count(); ++i) {
            const qt_mac_filter_name *filter = filts.at(i);
            if (sel_filt_name->description == filter->description
                    && sel_filt_name->regxp == filter->regxp
                    && sel_filt_name->filter == filter->filter) {
                navSpec.menuType = i;
                break;
            }
        }
        NavCustomControl(dlg, kNavCtlSelectCustomType, &navSpec);
    }
    if(options.modality == kWindowModalityWindowModal) { //simulate modality
        QWidget modal_widg(parent, __FILE__ "__modal_dlg",
                           Qt::WType_TopLevel | Qt::WStyle_Customize | Qt::WStyle_DialogBorder);
        modal_widg.createWinId();
        QApplicationPrivate::enterModal(&modal_widg);
        while(g_nav_blocking)
            qApp->processEvents(QEventLoop::WaitForMoreEvents);
        QApplicationPrivate::leaveModal(&modal_widg);
    }

    if(NavDialogGetUserAction(dlg) != kNavUserActionSaveAs) {
        NavDialogDispose(dlg);
        return retstr;
    }
    NavReplyRecord ret;
    NavDialogGetReply(dlg, &ret);
    NavDialogDispose(dlg);

    long count;
    err = AECountItems(&(ret.selection), &count);
    if(!ret.validRecord || err != noErr || !count) {
        NavDisposeReply(&ret);
        return retstr;
    }

    AEKeyword        keyword;
    DescType    type;
    Size        size;
    FSRef ref;
    err = AEGetNthPtr(&(ret.selection), 1, typeFSRef, &keyword,
                      &type, &ref, sizeof(ref), &size);
    if(err == noErr) {
        if(!str_buffer) {
            qAddPostRoutine(cleanup_str_buffer);
            str_buffer = (UInt8 *)malloc(1024);
        }
        FSRefMakePath(&ref, str_buffer, 1024);
        retstr = QString::fromUtf8((const char *)str_buffer);
        //now filename
        CFStringGetCString(ret.saveFileName, (char *)str_buffer, 1024, kCFStringEncodingUTF8);
        retstr += QLatin1Char('/') + QString::fromUtf8((const char *)str_buffer);
    }
    NavDisposeReply(&ret);
    if(selectedFilter)
        *selectedFilter = filts.at(t.index)->filter;
    while (!filts.isEmpty())
        delete filts.takeFirst();
    return retstr;
}
Example #11
0
void KreTextEdit::keyPressEvent( QKeyEvent *e )
{
	// Filter key-events if completion mode is not set to CompletionNone

	KeyBindingMap keys = getKeyBindings();
	KShortcut cut;
	bool noModifier = ( e->modifiers() == Qt::NoModifier || e->modifiers() == Qt::ShiftModifier );

	if ( noModifier ) {
		QString keycode = e->text();
		if ( !keycode.isEmpty() && keycode.unicode() ->isPrint() ) {
			KTextEdit::keyPressEvent ( e );
			tryCompletion();
			e->accept();
			return ;
		}
	}

	// Handles completion
	if ( keys[ TextCompletion ].isEmpty() )
		cut = KStandardShortcut::shortcut( KStandardShortcut::TextCompletion );
	else
		cut = keys[ TextCompletion ];

	//using just the standard Ctrl+E isn't user-friendly enough for Grandma...
	if ( completing && ( cut.contains( e->key() ) || e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return ) ) {
#if 0
		int paraFrom, indexFrom, paraTo, indexTo;
		getSelection ( &paraFrom, &indexFrom, &paraTo, &indexTo );

		removeSelection();
		setCursorPosition( paraTo, indexTo );

		completing = false;
		return ;
#endif
	}

	// handle rotation

	// Handles previous match
	if ( keys[ PrevCompletionMatch ].isEmpty() )
		cut = KStandardShortcut::shortcut( KStandardShortcut::PrevCompletion );
	else
		cut = keys[ PrevCompletionMatch ];

	if ( cut.contains( e->key() ) ) {
		rotateText( KCompletionBase::PrevCompletionMatch );
		return ;
	}

	// Handles next match
	if ( keys[ NextCompletionMatch ].isEmpty() )
		cut = KStandardShortcut::shortcut( KStandardShortcut::NextCompletion );
	else
		cut = keys[ NextCompletionMatch ];

	if ( cut.contains( e->key() ) ) {
		rotateText( KCompletionBase::NextCompletionMatch );
		return ;
	}

	//any other key events will end any text completion execpt for modifiers
	switch ( e->key() ) {
	case Qt::Key_Shift:
	case Qt::Key_Control:
	case Qt::Key_Alt:
	case Qt::Key_Meta:
		break;
	default:
		completing = false;
		break;
	}

	// Let KTextEdit handle any other keys events.
	KTextEdit::keyPressEvent ( e );
}
Example #12
0
QStringList Q3FileDialog::macGetOpenFileNames(const QString &filter, QString *pwd,
                                             QWidget *parent, const char* /*name*/,
                                             const QString& caption, QString *selectedFilter,
                                             bool multi, bool directory)
{
    OSErr err;
    QStringList retstrl;

    NavDialogCreationOptions options;
    NavGetDefaultDialogCreationOptions(&options);
    options.modality = kWindowModalityAppModal;
    options.optionFlags |= kNavDontConfirmReplacement | kNavSupportPackages;
    if (!multi)
        options.optionFlags &= ~kNavAllowMultipleFiles;
    if(!caption.isEmpty())
        options.windowTitle = CFStringCreateWithCharacters(NULL, (UniChar *)caption.unicode(),
                                                           caption.length());

    static const int w = 450, h = 350;
    options.location.h = options.location.v = -1;
    if(parent && parent->isVisible()) {
        Qt::WindowType wt = parent->window()->windowType();
        if (wt != Qt::Desktop && wt != Qt::Sheet && wt != Qt::Drawer) {
            options.modality = kWindowModalityWindowModal;
            options.parentWindow = qt_mac_window_for(parent);
        } else {
            parent = parent->window();
            QString s = parent->windowTitle();
            options.clientName = CFStringCreateWithCharacters(NULL, (UniChar *)s.unicode(), s.length());
            options.location.h = (parent->x() + (parent->width() / 2)) - (w / 2);
            options.location.v = (parent->y() + (parent->height() / 2)) - (h / 2);

            QRect r = QApplication::desktop()->screenGeometry(
                QApplication::desktop()->screenNumber(parent));
            if(options.location.h + w > r.right())
                options.location.h -= (options.location.h + w) - r.right() + 10;
            if(options.location.v + h > r.bottom())
                options.location.v -= (options.location.v + h) - r.bottom() + 10;
        }
    } else if(QWidget *p = qApp->mainWidget()) {
        static int last_screen = -1;
        int scr = QApplication::desktop()->screenNumber(p);
        if(last_screen != scr) {
            QRect r = QApplication::desktop()->screenGeometry(scr);
            options.location.h = (r.x() + (r.width() / 2)) - (w / 2);
            options.location.v = (r.y() + (r.height() / 2)) - (h / 2);
        }
    }

    QList<qt_mac_filter_name*> filts = makeFiltersList(filter);
    qt_mac_nav_filter_type t;
    t.index = 0;
    t.filts = &filts;
    if(filts.count() > 1) {
        int i = 0;
        CFStringRef *arr = (CFStringRef *)malloc(sizeof(CFStringRef) * filts.count());
        for (QList<qt_mac_filter_name*>::Iterator it = filts.begin(); it != filts.end(); ++it) {
            QString rg = (*it)->description;
            arr[i++] = CFStringCreateWithCharacters(NULL, (UniChar *)rg.unicode(), rg.length());
        }
        options.popupExtension = CFArrayCreate(NULL, (const void **)arr, filts.count(), NULL);
    }

    NavDialogRef dlg;
    if(directory) {
        if(NavCreateChooseFolderDialog(&options, make_navProcUPP(), NULL, NULL, &dlg)) {
            qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
            return retstrl;
        }
    } else {
        if(NavCreateGetFileDialog(&options, NULL, make_navProcUPP(), NULL,
                                  make_navFilterUPP(), (void *) (filts.isEmpty() ? NULL : &t),
                                  &dlg)) {
            qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
            return retstrl;
        }
    }
    if(pwd && !pwd->isEmpty()) {
        FSRef fsref;
        if(qt_mac_create_fsref(*pwd, &fsref) == noErr) {
            AEDesc desc;
            if(AECreateDesc(typeFSRef, &fsref, sizeof(FSRef), &desc) == noErr)
                NavCustomControl(dlg, kNavCtlSetLocation, (void*)&desc);
        }
    }

    NavDialogRun(dlg);
    if (selectedFilter) {
        NavMenuItemSpec navSpec;
        bzero(&navSpec, sizeof(NavMenuItemSpec));
        qt_mac_filter_name *sel_filt_name = makeFiltersList(*selectedFilter).at(0);
        for (int i = 0; i < filts.count(); ++i) {
            const qt_mac_filter_name *filter = filts.at(i);
            if (sel_filt_name->description == filter->description
                    && sel_filt_name->regxp == filter->regxp
                    && sel_filt_name->filter == filter->filter) {
                navSpec.menuType = i;
                break;
            }
        }
        NavCustomControl(dlg, kNavCtlSelectCustomType, &navSpec);
    }
    if(options.modality == kWindowModalityWindowModal) { //simulate modality
        QWidget modal_widg(parent, __FILE__ "__modal_dlg",
                           Qt::WType_TopLevel | Qt::WStyle_Customize | Qt::WStyle_DialogBorder);
        modal_widg.createWinId();
        QApplicationPrivate::enterModal(&modal_widg);
        while(g_nav_blocking)
            qApp->processEvents(QEventLoop::WaitForMoreEvents);
        QApplicationPrivate::leaveModal(&modal_widg);
    }

    if(!(NavDialogGetUserAction(dlg) &
          (kNavUserActionOpen | kNavUserActionChoose | kNavUserActionNewFolder))) {
        NavDialogDispose(dlg);
        return retstrl;
    }
    NavReplyRecord ret;
    NavDialogGetReply(dlg, &ret);
    NavDialogDispose(dlg);

    long count;
    err = AECountItems(&(ret.selection), &count);
    if(!ret.validRecord || err != noErr || !count) {
        NavDisposeReply(&ret);
        return retstrl;
    }

    for(long index = 1; index <= count; index++) {
        FSRef ref;
        err = AEGetNthPtr(&(ret.selection), index, typeFSRef, 0, 0, &ref, sizeof(ref), 0);
        if(err != noErr)
            break;

        if(!str_buffer) {
            qAddPostRoutine(cleanup_str_buffer);
            str_buffer = (UInt8 *)malloc(1024);
        }
        FSRefMakePath(&ref, str_buffer, 1024);
        retstrl.append(QString::fromUtf8((const char *)str_buffer));
    }
    NavDisposeReply(&ret);
    if(selectedFilter)
        *selectedFilter = filts.at(t.index)->filter;
    while (!filts.isEmpty())
        delete filts.takeFirst();
    return retstrl;
}
Example #13
0
bool KMacroExpanderBase::expandMacrosShellQuote( QString &str, uint &pos )
{
    int len;
    uint pos2;
    QChar ec( escapechar );
    State state = { noquote, false };
    QValueStack<State> sstack;
    QValueStack<Save> ostack;
    QStringList rst;
    QString rsts;

    while (pos < str.length()) {
        QChar cc( str.unicode()[pos] );
        if (ec != (char)0) {
            if (cc != ec)
                goto nohit;
            if (!(len = expandEscapedMacro( str, pos, rst )))
                goto nohit;
        } else {
            if (!(len = expandPlainMacro( str, pos, rst )))
                goto nohit;
        }
            if (len < 0) {
                pos -= len;
                continue;
            }
            if (state.dquote) {
                rsts = rst.join( " " );
                rsts.replace( QRegExp("([$`\"\\\\])"), "\\\\1" );
            } else if (state.current == dollarquote) {
                rsts = rst.join( " " );
                rsts.replace( QRegExp("(['\\\\])"), "\\\\1" );
            } else if (state.current == singlequote) {
                rsts = rst.join( " " );
                rsts.replace( '\'', "'\\''");
            } else {
                if (rst.isEmpty()) {
                    str.remove( pos, len );
                    continue;
                } else {
                    rsts = "'";
#if 0 // this could pay off if join() would be cleverer and the strings were long
                    for (QStringList::Iterator it = rst.begin(); it != rst.end(); ++it)
                        (*it).replace( '\'', "'\\''" );
                    rsts += rst.join( "' '" );
#else
                    for (QStringList::ConstIterator it = rst.begin(); it != rst.end(); ++it) {
                        if (it != rst.begin())
                            rsts += "' '";
                        QString trsts( *it );
                        trsts.replace( '\'', "'\\''" );
                        rsts += trsts;
                    }
#endif
                    rsts += "'";
                }
            }
            rst.clear();
            str.replace( pos, len, rsts );
            pos += rsts.length();
            continue;
      nohit:
        if (state.current == singlequote) {
            if (cc == '\'')
                state = sstack.pop();
        } else if (cc == '\\') {
            // always swallow the char -> prevent anomalies due to expansion
            pos += 2;
            continue;
        } else if (state.current == dollarquote) {
            if (cc == '\'')
                state = sstack.pop();
        } else if (cc == '$') {
            cc = str[++pos];
            if (cc == '(') {
                sstack.push( state );
                if (str[pos + 1] == '(') {
                    Save sav = { str, pos + 2 };
                    ostack.push( sav );
                    state.current = math;
                    pos += 2;
                    continue;
                } else {
                    state.current = paren;
                    state.dquote = false;
                }
            } else if (cc == '{') {
                sstack.push( state );
                state.current = subst;
            } else if (!state.dquote) {
                if (cc == '\'') {
                    sstack.push( state );
                    state.current = dollarquote;
                } else if (cc == '"') {
                    sstack.push( state );
                    state.current = doublequote;
                    state.dquote = true;
                }
            }
            // always swallow the char -> prevent anomalies due to expansion
        } else if (cc == '`') {
            str.replace( pos, 1, "$( " ); // add space -> avoid creating $((
            pos2 = pos += 3;
            for (;;) {
                if (pos2 >= str.length()) {
                    pos = pos2;
                    return false;
                }
                cc = str.unicode()[pos2];
                if (cc == '`')
                    break;
                if (cc == '\\') {
                    cc = str[++pos2];
                    if (cc == '$' || cc == '`' || cc == '\\' ||
                        (cc == '"' && state.dquote))
                    {
                        str.remove( pos2 - 1, 1 );
                        continue;
                    }
                }
                pos2++;
            }
            str[pos2] = ')';
            sstack.push( state );
            state.current = paren;
            state.dquote = false;
            continue;
        } else if (state.current == doublequote) {
            if (cc == '"')
                state = sstack.pop();
        } else if (cc == '\'') {
            if (!state.dquote) {
                sstack.push( state );
                state.current = singlequote;
            }
        } else if (cc == '"') {
            if (!state.dquote) {
                sstack.push( state );
                state.current = doublequote;
                state.dquote = true;
            }
        } else if (state.current == subst) {
            if (cc == '}')
                state = sstack.pop();
        } else if (cc == ')') {
            if (state.current == math) {
                if (str[pos + 1] == ')') {
                    state = sstack.pop();
                    pos += 2;
                } else {
                    // false hit: the $(( was a $( ( in fact
                    // ash does not care, but bash does
                    pos = ostack.top().pos;
                    str = ostack.top().str;
                    ostack.pop();
                    state.current = paren;
                    state.dquote = false;
                    sstack.push( state );
                }
                continue;
            } else if (state.current == paren)
                state = sstack.pop();
            else
                break;
        } else if (cc == '}') {
            if (state.current == KMacroExpander::group)
                state = sstack.pop();
            else
                break;
        } else if (cc == '(') {
            sstack.push( state );
            state.current = paren;
        } else if (cc == '{') {
            sstack.push( state );
            state.current = KMacroExpander::group;
        }
        pos++;
    }
    return sstack.empty();
}
Example #14
0
/**
 * Retrieves the data stored in this object and store the result in
 * pMedium.
 *
 * @return  IPRT status code.
 * @return  HRESULT
 * @param   pFormatEtc
 * @param   pMedium
 */
STDMETHODIMP UIDnDDataObject::GetData(FORMATETC *pFormatEtc, STGMEDIUM *pMedium)
{
    AssertPtrReturn(pFormatEtc, DV_E_FORMATETC);
    AssertPtrReturn(pMedium, DV_E_FORMATETC);

#ifdef VBOX_DND_DEBUG_FORMATS
    LogFlowFunc(("pFormatEtc=%p, pMedium=%p\n", pFormatEtc, pMedium));
#endif

    ULONG lIndex;
    if (!LookupFormatEtc(pFormatEtc, &lIndex)) /* Format supported? */
        return DV_E_FORMATETC;
    if (lIndex >= mcFormats) /* Paranoia. */
        return DV_E_FORMATETC;

    FORMATETC *pThisFormat = &mpFormatEtc[lIndex];
    AssertPtr(pThisFormat);

    STGMEDIUM *pThisMedium = &mpStgMedium[lIndex];
    AssertPtr(pThisMedium);

    HRESULT hr = DV_E_FORMATETC;

    LogFlowFunc(("mStatus=%ld\n", mStatus));
    if (mStatus == Dropping)
    {
        LogFlowFunc(("Waiting for event ...\n"));
        int rc2 = RTSemEventWait(mSemEvent, RT_INDEFINITE_WAIT);
        LogFlowFunc(("rc=%Rrc, mStatus=%ld\n", rc2, mStatus));
    }

    if (mStatus == Dropped)
    {
        LogFlowFunc(("cfFormat=%RI16, sFormat=%s, tyMed=%RU32, dwAspect=%RU32\n",
                     pThisFormat->cfFormat, UIDnDDataObject::ClipboardFormatToString(pFormatEtc->cfFormat),
                     pThisFormat->tymed, pThisFormat->dwAspect));
        LogFlowFunc(("Got strFormat=%s, pvData=%p, cbData=%RU32\n",
                     mstrFormat.toAscii().constData(), mpvData, mcbData));

        QVariant::Type vaType;
        QString strMIMEType;
        if (    (pFormatEtc->tymed & TYMED_HGLOBAL)
             && (pFormatEtc->dwAspect == DVASPECT_CONTENT)
             && (   pFormatEtc->cfFormat == CF_TEXT
                 || pFormatEtc->cfFormat == CF_UNICODETEXT)
           )
        {
            strMIMEType = "text/plain"; /** @todo Indicate UTF8 encoding? */
            vaType = QVariant::String;
        }
        else if (   (pFormatEtc->tymed & TYMED_HGLOBAL)
                 && (pFormatEtc->dwAspect == DVASPECT_CONTENT)
                 && (pFormatEtc->cfFormat == CF_HDROP))
        {
            strMIMEType = "text/uri-list";
            vaType = QVariant::StringList;
        }
#if 0 /* More formats; not needed right now. */
        else if (   (pFormatEtc->tymed & TYMED_ISTREAM)
                && (pFormatEtc->dwAspect == DVASPECT_CONTENT)
                && (pFormatEtc->cfFormat == CF_FILECONTENTS))
        {

        }
        else if  (   (pFormatEtc->tymed & TYMED_HGLOBAL)
                  && (pFormatEtc->dwAspect == DVASPECT_CONTENT)
                  && (pFormatEtc->cfFormat == CF_FILEDESCRIPTOR))
        {

        }
        else if (   (pFormatEtc->tymed & TYMED_HGLOBAL)
                 && (pFormatEtc->cfFormat == CF_PREFERREDDROPEFFECT))
        {
            HGLOBAL hData = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT, sizeof(DWORD));
            DWORD *pdwEffect = (DWORD *)GlobalLock(hData);
            AssertPtr(pdwEffect);
            *pdwEffect = DROPEFFECT_COPY;
            GlobalUnlock(hData);

            pMedium->hGlobal = hData;
            pMedium->tymed = TYMED_HGLOBAL;
        }
#endif
        LogFlowFunc(("strMIMEType=%s, vaType=%ld\n",
                     strMIMEType.toAscii().constData(), vaType));

        int rc;
        if (!mVaData.isValid())
        {
            rc = UIDnDDrag::RetrieveData(mSession,
                                         mDnDSource,
                                         /** @todo Support other actions. */
                                         Qt::CopyAction,
                                         strMIMEType, vaType, mVaData,
                                         mpParent);
        }
        else
            rc = VINF_SUCCESS; /* Data already retrieved. */

        if (RT_SUCCESS(rc))
        {
            if (   strMIMEType.startsWith("text/uri-list")
                       /* One item. */
                && (   mVaData.canConvert(QVariant::String)
                       /* Multiple items. */
                    || mVaData.canConvert(QVariant::StringList))
               )
            {
                QStringList lstFilesURI = mVaData.toStringList();
                QStringList lstFiles;
                for (size_t i = 0; i < lstFilesURI.size(); i++)
                {
                    /* Extract path from URI. */
                    char *pszPath = RTUriPath(lstFilesURI.at(i).toAscii().constData());
                    if (   pszPath
                        && strlen(pszPath) > 1)
                    {
                        pszPath++; /** @todo Skip first '/' (part of URI). Correct? */
                        pszPath = RTPathChangeToDosSlashes(pszPath, false /* fForce */);
                        lstFiles.append(pszPath);
                    }
                }

                size_t cFiles = lstFiles.size();
                Assert(cFiles);
#ifdef DEBUG
                LogFlowFunc(("Files (%zu)\n", cFiles));
                for (size_t i = 0; i < cFiles; i++)
                    LogFlowFunc(("\tFile: %s\n", lstFiles.at(i).toAscii().constData()));
#endif
                size_t cchFiles = 0; /* Number of ASCII characters. */
                for (size_t i = 0; i < cFiles; i++)
                {
                    cchFiles += strlen(lstFiles.at(i).toAscii().constData());
                    cchFiles += 1; /* Terminating '\0'. */
                }

                size_t cbBuf = sizeof(DROPFILES) + ((cchFiles + 1) * sizeof(RTUTF16));
                DROPFILES *pDropFiles = (DROPFILES *)RTMemAllocZ(cbBuf);
                if (pDropFiles)
                {
                    pDropFiles->pFiles = sizeof(DROPFILES);
                    pDropFiles->fWide = 1; /* We use unicode. Always. */

                    uint8_t *pCurFile = (uint8_t *)pDropFiles + pDropFiles->pFiles;
                    AssertPtr(pCurFile);

                    for (size_t i = 0; i < cFiles; i++)
                    {
                        size_t cchCurFile;
                        PRTUTF16 pwszFile;
                        rc = RTStrToUtf16(lstFiles.at(i).toAscii().constData(), &pwszFile);
                        if (RT_SUCCESS(rc))
                        {
                            cchCurFile = RTUtf16Len(pwszFile);
                            Assert(cchCurFile);
                            memcpy(pCurFile, pwszFile, cchCurFile * sizeof(RTUTF16));
                            RTUtf16Free(pwszFile);
                        }
                        else
                            break;

                        pCurFile += cchCurFile * sizeof(RTUTF16);

                        /* Terminate current file name. */
                        *pCurFile = L'\0';
                        pCurFile += sizeof(RTUTF16);
                    }

                    if (RT_SUCCESS(rc))
                    {
                        *pCurFile = L'\0'; /* Final list terminator. */

                        pMedium->tymed = TYMED_HGLOBAL;
                        pMedium->pUnkForRelease = NULL;
                        pMedium->hGlobal = GlobalAlloc(  GMEM_ZEROINIT
                                                       | GMEM_MOVEABLE
                                                       | GMEM_DDESHARE, cbBuf);
                        if (pMedium->hGlobal)
                        {
                            LPVOID pvMem = GlobalLock(pMedium->hGlobal);
                            if (pvMem)
                            {
                                memcpy(pvMem, pDropFiles, cbBuf);
                                GlobalUnlock(pMedium->hGlobal);

                                hr = S_OK;
                            }
                            else
                                rc = VERR_ACCESS_DENIED;
                        }
                        else
                            rc = VERR_NO_MEMORY;
                    }

                    RTMemFree(pDropFiles);
                }
            }
            else if (   strMIMEType.startsWith("text/plain")
                     && mVaData.canConvert(QVariant::String))
            {
                bool fUnicode = pFormatEtc->cfFormat == CF_UNICODETEXT;
                int cbCh = fUnicode
                         ? sizeof(WCHAR) : sizeof(char);

                QString strText = mVaData.toString();
                size_t cbSrc = strText.length() * cbCh;
                Assert(cbSrc);
                LPCVOID pvSrc = fUnicode
                              ? (void *)strText.unicode()
                              : (void *)strText.toAscii().constData();
                AssertPtr(pvSrc);

                LogFlowFunc(("pvSrc=0x%p, cbSrc=%zu, cbch=%d, fUnicode=%RTbool\n",
                             pvSrc, cbSrc, cbCh, fUnicode));

                pMedium->tymed = TYMED_HGLOBAL;
                pMedium->pUnkForRelease = NULL;
                pMedium->hGlobal = GlobalAlloc(  GMEM_ZEROINIT
                                               | GMEM_MOVEABLE
                                               | GMEM_DDESHARE,
                                               cbSrc);
                if (pMedium->hGlobal)
                {
                    LPVOID pvDst = GlobalLock(pMedium->hGlobal);
                    if (pvDst)
                    {
                        memcpy(pvDst, pvSrc, cbSrc);
                        GlobalUnlock(pMedium->hGlobal);
                    }
                    else
                        rc = VERR_ACCESS_DENIED;

                    hr = S_OK;
                }
                else
                    hr  = VERR_NO_MEMORY;
            }
            else
                LogFlowFunc(("MIME type=%s not supported\n",
                             strMIMEType.toAscii().constData()));

            LogFlowFunc(("Handling formats ended with rc=%Rrc\n", rc));
        }
    }

    /*
     * Fallback in error case.
     */
    if (FAILED(hr))
    {
        LogFlowFunc(("Error hr=%Rhrc while handling data, copying raw medium data ...\n", hr));

        switch (pThisMedium->tymed)
        {

        case TYMED_HGLOBAL:
            pMedium->hGlobal = (HGLOBAL)OleDuplicateData(pThisMedium->hGlobal,
                                                         pThisFormat->cfFormat,
                                                         0 /* Flags */);
            break;

        default:
            break;
        }

        pMedium->tymed          = pFormatEtc->tymed;
        pMedium->pUnkForRelease = NULL;
    }

    LogFlowFunc(("Returning hr=%Rhrc\n", hr));
    return hr;
}
Example #15
0
void SourceDisplay::setSource(SourceFile *sourceFile)
{
    if(sourceFile)
        sourceFile->ref();
    if(m_sourceFile)
        m_sourceFile->deref();
    m_sourceFile = sourceFile;
    if(m_sourceFile)
        m_sourceFile->ref();

    if(!m_sourceFile || !m_debugWin->isVisible())
    {
        return;
    }

    QString code = sourceFile->getCode();
    const QChar *chars = code.unicode();
    uint len = code.length();
    QChar newLine('\n');
    QChar cr('\r');
    QChar tab('\t');
    QString tabstr("        ");
    QString line;
    m_lines.clear();
    int width = 0;
    QFontMetrics metrics(m_font);

    for(uint pos = 0; pos < len; pos++)
    {
        QChar c = chars[pos];
        if(c == cr)
        {
            if(pos < len - 1 && chars[pos + 1] == newLine)
                continue;
            else
                c = newLine;
        }
        if(c == newLine)
        {
            m_lines.append(line);
            int lineWidth = metrics.width(line);
            if(lineWidth > width)
                width = lineWidth;
            line = "";
        }
        else if(c == tab)
        {
            line += tabstr;
        }
        else
        {
            line += c;
        }
    }
    if(line.length())
    {
        m_lines.append(line);
        int lineWidth = metrics.width(line);
        if(lineWidth > width)
            width = lineWidth;
    }

    int linenoDisplayWidth = metrics.width("888888");
    resizeContents(linenoDisplayWidth + 4 + width, metrics.height() * m_lines.count());
    update();
    sourceFile->deref();
}
Example #16
0
// nsClipboard::GetNativeClipboardData ie. Paste
//
NS_IMETHODIMP
nsClipboard::GetNativeClipboardData(nsITransferable *aTransferable,
                                    QClipboard::Mode clipboardMode)
{
    if (nsnull == aTransferable)
    {
        qDebug("  GetNativeClipboardData: Transferable is null!");
        return NS_ERROR_FAILURE;
    }

    // get flavor list that includes all acceptable flavors (including
    // ones obtained through conversion)
    nsCOMPtr<nsISupportsArray> flavorList;
    nsresult errCode = aTransferable->FlavorsTransferableCanImport(
        getter_AddRefs(flavorList));

    if (NS_FAILED(errCode))
    {
        qDebug("nsClipboard::GetNativeClipboardData(): no FlavorsTransferable %i !",
               errCode);
        return NS_ERROR_FAILURE;
    }

    QClipboard *cb = QApplication::clipboard();
    const QMimeData *mimeData = cb->mimeData(clipboardMode);

    // Walk through flavors and see which flavor matches the one being pasted
    PRUint32 flavorCount;
    flavorList->Count(&flavorCount);
    nsCAutoString foundFlavor;

    for (PRUint32 i = 0; i < flavorCount; ++i)
    {
        nsCOMPtr<nsISupports> genericFlavor;
        flavorList->GetElementAt(i,getter_AddRefs(genericFlavor));
        nsCOMPtr<nsISupportsCString> currentFlavor(do_QueryInterface( genericFlavor) );

        if (currentFlavor)
        {
            nsXPIDLCString flavorStr;
            currentFlavor->ToString(getter_Copies(flavorStr));

            // Ok, so which flavor the data being pasted could be?
            // Text?
            if (!strcmp(flavorStr.get(), kUnicodeMime)) 
            {
                if (mimeData->hasText())
                {
                    // Clipboard has text and flavor accepts text, so lets
                    // handle the data as text
                    foundFlavor = nsCAutoString(flavorStr);

                    // Get the text data from clipboard
                    QString text = mimeData->text();
                    const QChar *unicode = text.unicode();
                    // Is there a more correct way to get the size in UTF16?
                    PRUint32 len = (PRUint32) 2*text.size();

                    // And then to genericDataWrapper
                    nsCOMPtr<nsISupports> genericDataWrapper;
                    nsPrimitiveHelpers::CreatePrimitiveForData(
                        foundFlavor.get(),
                        (void*)unicode,
                        len,
                        getter_AddRefs(genericDataWrapper));

                    // Data is good, set it to the transferable
                    aTransferable->SetTransferData(foundFlavor.get(),
                                                   genericDataWrapper,len);
                    // And thats all
                    break;
                }
            }

            // Image?
            if (!strcmp(flavorStr.get(), kJPEGImageMime)
             || !strcmp(flavorStr.get(), kPNGImageMime)
             || !strcmp(flavorStr.get(), kGIFImageMime))
            {
                qDebug("nsClipboard::GetNativeClipboardData(): Pasting image data not implemented!");
                break;
            }
        }
    }

    return NS_OK;
}
Example #17
0
int QSLookup::find(const struct QSHashTable *table, const QString &s)
{
  return find(table, s.unicode(), s.length());
}
void QHelpSearchIndexWriter::run()
{
    mutex.lock();

    if (m_cancel) {
        mutex.unlock();
        return;
    }

    const bool reindex(this->m_reindex);
    const QLatin1String key("DefaultSearchNamespaces");
    const QString collectionFile(this->m_collectionFile);
    const QString indexPath = m_indexFilesFolder;
    
    mutex.unlock();

    QHelpEngineCore engine(collectionFile, 0);
    if (!engine.setupData())
        return;

    if (reindex)
        engine.setCustomValue(key, QLatin1String(""));

    const QStringList registeredDocs = engine.registeredDocumentations();
    const QStringList indexedNamespaces = engine.customValue(key).toString().
        split(QLatin1String("|"), QString::SkipEmptyParts);

    emit indexingStarted();

    QStringList namespaces;
    Writer writer(indexPath);
    foreach(const QString &namespaceName, registeredDocs) {
        mutex.lock();
        if (m_cancel) {
            mutex.unlock();
            return;
        }
        mutex.unlock();

        // if indexed, continue
        namespaces.append(namespaceName);
        if (indexedNamespaces.contains(namespaceName))
            continue;

        const QList<QStringList> attributeSets =
            engine.filterAttributeSets(namespaceName);

        foreach (const QStringList &attributes, attributeSets) {
            // cleanup maybe old or unfinished files
            writer.setIndexFile(namespaceName, attributes.join(QLatin1String("@")));
            writer.removeIndex();

            QSet<QString> documentsSet;
            const QList<QUrl> docFiles = engine.files(namespaceName, attributes);
            foreach(QUrl url, docFiles) {
                if (m_cancel)
                    return;

                // get rid of duplicated files
                if (url.hasFragment())
                    url.setFragment(QString());
                
                QString s = url.toString();
                if (s.endsWith(QLatin1String(".html"))
                    || s.endsWith(QLatin1String(".htm"))
                    || s.endsWith(QLatin1String(".txt")))
                    documentsSet.insert(s);
            }

            int docNum = 0;
            const QStringList documentsList(documentsSet.toList());
            foreach(const QString &url, documentsList) {
                if (m_cancel)
                    return;

                QByteArray data(engine.fileData(url));
                if (data.isEmpty())
                    continue;

                QTextStream s(data);
                QString en = QHelpGlobal::codecFromData(data);
                s.setCodec(QTextCodec::codecForName(en.toLatin1().constData()));

                QString text = s.readAll();
                if (text.isNull())
                    continue;

                QString title = QHelpGlobal::documentTitle(text);

                int j = 0;
                int i = 0;
                bool valid = true;
                const QChar *buf = text.unicode();
                QChar str[64];
                QChar c = buf[0];

                while ( j < text.length() ) {
                    if (m_cancel)
                        return;

                    if ( c == QLatin1Char('<') || c == QLatin1Char('&') ) {
                        valid = false;
                        if ( i > 1 )
                            writer.insertInIndex(QString(str,i), docNum);
                        i = 0;
                        c = buf[++j];
                        continue;
                    }
                    if ( ( c == QLatin1Char('>') || c == QLatin1Char(';') ) && !valid ) {
                        valid = true;
                        c = buf[++j];
                        continue;
                    }
                    if ( !valid ) {
                        c = buf[++j];
                        continue;
                    }
                    if ( ( c.isLetterOrNumber() || c == QLatin1Char('_') ) && i < 63 ) {
                        str[i] = c.toLower();
                        ++i;
                    } else {
                        if ( i > 1 )
                            writer.insertInIndex(QString(str,i), docNum);
                        i = 0;
                    }
                    c = buf[++j];
                }
                if ( i > 1 )
                    writer.insertInIndex(QString(str,i), docNum);

                docNum++;
                writer.insertInDocumentList(title, url);
            }

            if (writer.writeIndex()) {
                engine.setCustomValue(key, addNamespace(
                    engine.customValue(key).toString(), namespaceName));
            }

            writer.reset();
        }
Example #19
0
CFStringRef
lastfm::QStringToCFString( const QString &s )
{
    return CFStringCreateWithCharacters( 0, (UniChar*)s.unicode(), s.length() );
}
bool Compose::handle_qkey(const QKeyEvent *event)
{
    int qstate = event->modifiers();
    unsigned int xstate = 0;
    if (qstate & Qt::ShiftModifier)
        xstate |= ShiftMask;
    if (qstate & Qt::ControlModifier)
        xstate |= ControlMask;
    if (qstate & Qt::AltModifier)
        xstate |= Mod1Mask; // XXX
    if (qstate & Qt::MetaModifier)
        xstate |= Mod1Mask; // XXX

    int qkey = event->key();
    unsigned int xkeysym;
    if (qkey >= 0x20 && qkey <= 0xff) {
        if (isascii(qkey) && isprint(qkey)) {
            QString str = event->text();
            int ascii = str.length() ? str.unicode()->toLatin1() : 0;
            if (isalpha(ascii))
                    xkeysym = ascii;
            else
                if ((qstate & Qt::ControlModifier) &&
                    (ascii >= 0x01 && ascii <= 0x1a))
                    if (qstate & Qt::ShiftModifier)
                        xkeysym = ascii + 0x40;
                    else
                        xkeysym = ascii + 0x60;
                else
                        xkeysym = qkey;
        } else {
            xkeysym = qkey;
        }
    } else if (qkey >= Qt::Key_Dead_Grave && qkey <= Qt::Key_Dead_Horn) {
        xkeysym = qkey + 0xec00 - 0x01000000;
    } else {
        switch (qkey) {
        case Qt::Key_Escape: xkeysym = XK_Escape; break;
        case Qt::Key_Tab: xkeysym = XK_Tab; break;
        case Qt::Key_Backspace: xkeysym = XK_BackSpace; break;
        case Qt::Key_Return: xkeysym = XK_Return; break;
        case Qt::Key_Insert: xkeysym = XK_Insert; break;
        case Qt::Key_Delete: xkeysym = XK_Delete; break;
        case Qt::Key_Pause: xkeysym = XK_Pause; break;
        case Qt::Key_Print: xkeysym = XK_Print; break;
        case Qt::Key_SysReq: xkeysym = XK_Sys_Req; break;
        case Qt::Key_Clear: xkeysym = XK_Clear; break;
        case Qt::Key_Home: xkeysym = XK_Home; break;
        case Qt::Key_End: xkeysym = XK_End; break;
        case Qt::Key_Left: xkeysym = XK_Left; break;
        case Qt::Key_Up: xkeysym = XK_Up; break;
        case Qt::Key_Right: xkeysym = XK_Right; break;
        case Qt::Key_Down: xkeysym = XK_Down; break;
        case Qt::Key_PageUp: xkeysym = XK_Prior; break;
        case Qt::Key_PageDown: xkeysym = XK_Next; break;
        case Qt::Key_Shift: xkeysym = XK_Shift_L; break;
        case Qt::Key_Control: xkeysym = XK_Control_L; break;
        case Qt::Key_Meta: xkeysym = XK_Meta_L; break;
        case Qt::Key_Alt: xkeysym = XK_Alt_L; break;
        case Qt::Key_CapsLock: xkeysym = XK_Caps_Lock; break;
        case Qt::Key_NumLock: xkeysym = XK_Num_Lock; break;
        case Qt::Key_ScrollLock: xkeysym = XK_Scroll_Lock; break;
        case Qt::Key_F1: xkeysym = XK_F1; break;
        case Qt::Key_F2: xkeysym = XK_F2; break;
        case Qt::Key_F3: xkeysym = XK_F3; break;
        case Qt::Key_F4: xkeysym = XK_F4; break;
        case Qt::Key_F5: xkeysym = XK_F5; break;
        case Qt::Key_F6: xkeysym = XK_F6; break;
        case Qt::Key_F7: xkeysym = XK_F7; break;
        case Qt::Key_F8: xkeysym = XK_F8; break;
        case Qt::Key_F9: xkeysym = XK_F9; break;
        case Qt::Key_F10: xkeysym = XK_F10; break;
        case Qt::Key_F11: xkeysym = XK_F11; break;
        case Qt::Key_F12: xkeysym = XK_F12; break;
        case Qt::Key_F13: xkeysym = XK_F13; break;
        case Qt::Key_F14: xkeysym = XK_F14; break;
        case Qt::Key_F15: xkeysym = XK_F15; break;
        case Qt::Key_F16: xkeysym = XK_F16; break;
        case Qt::Key_F17: xkeysym = XK_F17; break;
        case Qt::Key_F18: xkeysym = XK_F18; break;
        case Qt::Key_F19: xkeysym = XK_F19; break;
        case Qt::Key_F20: xkeysym = XK_F20; break;
        case Qt::Key_F21: xkeysym = XK_F21; break;
        case Qt::Key_F22: xkeysym = XK_F22; break;
        case Qt::Key_F23: xkeysym = XK_F23; break;
        case Qt::Key_F24: xkeysym = XK_F24; break;
        case Qt::Key_F25: xkeysym = XK_F25; break;
        case Qt::Key_F26: xkeysym = XK_F26; break;
        case Qt::Key_F27: xkeysym = XK_F27; break;
        case Qt::Key_F28: xkeysym = XK_F28; break;
        case Qt::Key_F29: xkeysym = XK_F29; break;
        case Qt::Key_F30: xkeysym = XK_F30; break;
        case Qt::Key_F31: xkeysym = XK_F31; break;
        case Qt::Key_F32: xkeysym = XK_F32; break;
        case Qt::Key_F33: xkeysym = XK_F33; break;
        case Qt::Key_F34: xkeysym = XK_F34; break;
        case Qt::Key_F35: xkeysym = XK_F35; break;
        case Qt::Key_Super_L: xkeysym = XK_Super_L; break;
        case Qt::Key_Super_R: xkeysym = XK_Super_R; break;
        case Qt::Key_Menu: xkeysym = XK_Menu; break;
        case Qt::Key_Hyper_L: xkeysym = XK_Hyper_L; break;
        case Qt::Key_Hyper_R: xkeysym = XK_Hyper_R; break;
        case Qt::Key_Help: xkeysym = XK_Help; break;
        case Qt::Key_Multi_key: xkeysym = XK_Multi_key; break;
        case Qt::Key_Codeinput: xkeysym = XK_Codeinput; break;
        case Qt::Key_SingleCandidate: xkeysym = XK_SingleCandidate; break;
        case Qt::Key_PreviousCandidate: xkeysym = XK_PreviousCandidate; break;
        case Qt::Key_Mode_switch: xkeysym = XK_Mode_switch; break;
        case Qt::Key_Kanji: xkeysym = XK_Kanji; break;
        case Qt::Key_Muhenkan: xkeysym = XK_Muhenkan; break;
        case Qt::Key_Henkan: xkeysym = XK_Henkan_Mode; break;
        case Qt::Key_Romaji: xkeysym = XK_Romaji; break;
        case Qt::Key_Hiragana: xkeysym = XK_Hiragana; break;
        case Qt::Key_Katakana: xkeysym = XK_Katakana; break;
        case Qt::Key_Hiragana_Katakana: xkeysym = XK_Hiragana_Katakana; break;
        case Qt::Key_Zenkaku: xkeysym = XK_Zenkaku; break;
        case Qt::Key_Hankaku: xkeysym = XK_Hankaku; break;
        case Qt::Key_Zenkaku_Hankaku: xkeysym = XK_Zenkaku_Hankaku; break;
        case Qt::Key_Touroku: xkeysym = XK_Touroku; break;
        case Qt::Key_Massyo: xkeysym = XK_Massyo; break;
        case Qt::Key_Kana_Lock: xkeysym = XK_Kana_Lock; break;
        case Qt::Key_Kana_Shift: xkeysym = XK_Kana_Shift; break;
        case Qt::Key_Eisu_Shift: xkeysym = XK_Eisu_Shift; break;
        case Qt::Key_Eisu_toggle: xkeysym = XK_Eisu_toggle; break;

        case Qt::Key_Hangul: xkeysym = XK_Hangul; break;
        case Qt::Key_Hangul_Start: xkeysym = XK_Hangul_Start; break;
        case Qt::Key_Hangul_End: xkeysym = XK_Hangul_End; break;
        case Qt::Key_Hangul_Jamo: xkeysym = XK_Hangul_Jamo; break;
        case Qt::Key_Hangul_Romaja: xkeysym = XK_Hangul_Romaja; break;
        case Qt::Key_Hangul_Jeonja: xkeysym = XK_Hangul_Jeonja; break;
        case Qt::Key_Hangul_Banja: xkeysym = XK_Hangul_Banja; break;
        case Qt::Key_Hangul_PreHanja: xkeysym = XK_Hangul_PreHanja; break;
        case Qt::Key_Hangul_PostHanja: xkeysym = XK_Hangul_PostHanja; break;
        case Qt::Key_Hangul_Special: xkeysym = XK_Hangul_Special; break;
        default: xkeysym = qkey; break;
        }
    }

    int type = event->type();
    bool press = (type == QEvent::KeyPress);
    return handleKey(xkeysym, xstate, press);
}
Example #21
0
/*!
    Sets the string that this string matcher will search for to \a
    pattern.

    \sa pattern(), setCaseSensitivity(), indexIn()
*/
void QStringMatcher::setPattern(const QString &pattern)
{
    bm_init_skiptable((const ushort *)pattern.unicode(), pattern.size(), q_skiptable, q_cs);
    q_pattern = pattern;
}
Example #22
0
void MozQWidget::inputMethodEvent(QInputMethodEvent* aEvent)
{
    QString currentPreeditString = aEvent->preeditString();
    QString currentCommitString = aEvent->commitString();

    //first check for some controllkeys send as text...
    if (currentCommitString == " ") {
        sendPressReleaseKeyEvent(Qt::Key_Space, currentCommitString.unicode());
    } else if (currentCommitString == "\n") {
        sendPressReleaseKeyEvent(Qt::Key_Return, currentCommitString.unicode());
    } else if (currentCommitString.isEmpty()) {
        //if its no controllkey than check if current Commit is empty
        //if yes than we have some preedit text here
        if (currentPreeditString.length() == 1 && gLastPreeditString.isEmpty()) {
            //Preedit text can change its entire look'a'like
            //check if length of new compared to the old is 1,
            //means that its a new startup
            sendPressReleaseKeyEvent(0, currentPreeditString.unicode());
        } else if (currentPreeditString.startsWith(gLastPreeditString)) {
            //Length was not 1 or not a new startup
            //check if the current preedit starts with the last one,
            //if so: Add new letters (note: this can be more then one new letter)
            const QChar * text = currentPreeditString.unicode();
            for (int i = gLastPreeditString.length(); i < currentPreeditString.length(); i++) {
                sendPressReleaseKeyEvent(0, &text[i]);
            }
        } else {
            //last possible case, we had a PreeditString which was now completely changed.
            //first, check if just one letter was removed (normal Backspace case!)
            //if so: just send the backspace
            QString tempLastPre = gLastPreeditString;
            tempLastPre.truncate(gLastPreeditString.length()-1);
            if (currentPreeditString == tempLastPre) {
                sendPressReleaseKeyEvent(Qt::Key_Backspace);
            } else if (currentPreeditString != tempLastPre) {
                //more than one character changed, so just renew everything
                //delete all preedit
                for (int i = 0; i < gLastPreeditString.length(); i++) {
                    sendPressReleaseKeyEvent(Qt::Key_Backspace);
                }
                //send new Preedit
                const QChar * text = currentPreeditString.unicode();
                for (int i = 0; i < currentPreeditString.length(); i++) {
                    sendPressReleaseKeyEvent(0, &text[i]);
                }
            }
        }
    } else if (gLastPreeditString != currentCommitString) {
        //User commited something
        if (currentCommitString.length() == 1 && gLastPreeditString.isEmpty()) {
            //if commit string ist one and there is no Preedit String
            //case i.e. when no error correction is enabled in the system (default meego.com)
            sendPressReleaseKeyEvent(0, currentCommitString.unicode());
        } else {
            //There is a Preedit, first remove it
            for (int i = 0; i < gLastPreeditString.length(); i++) {
                sendPressReleaseKeyEvent(Qt::Key_Backspace);
            }
            //Now push commited String into
            const QChar * text = currentCommitString.unicode();
            for (int i = 0; i < currentCommitString.length(); i++) {
                sendPressReleaseKeyEvent(0, &text[i]);
            }
        }
    }

    //save preedit for next round.
    gLastPreeditString = currentPreeditString;

    //pre edit is continues string of new chars pressed by the user.
    //if pre edit is changing rapidly without commit string first then user choose some overed text
    //if commitstring comes directly after, forget about it
    QGraphicsWidget::inputMethodEvent(aEvent);
}