// @file ScintillaEdit.cpp
// Extended version of ScintillaEditBase with a method for each API
// Copyright (c) 2011 Archaeopteryx Software, Inc. d/b/a Wingware

#include "ScintillaEdit.h"

using namespace Scintilla;

ScintillaEdit::ScintillaEdit(QWidget *parent) : ScintillaEditBase(parent) {
}

ScintillaEdit::~ScintillaEdit() {
}

QByteArray ScintillaEdit::TextReturner(int message, uptr_t wParam) const {
    // While Scintilla can return strings longer than maximum(int), QByteArray uses int size
    const int length = static_cast<int>(send(message, wParam, 0));
    QByteArray ba(length + 1, '\0');
    send(message, wParam, (sptr_t)ba.data());
    // Remove extra NULs
    if (ba.at(ba.size()-1) == 0)
        ba.chop(1);
    return ba;
}

QPair<int, int>ScintillaEdit::find_text(int flags, const char *text, int cpMin, int cpMax) {
    struct Sci_TextToFind ft = {{0, 0}, 0, {0, 0}};
    ft.chrg.cpMin = cpMin;
    ft.chrg.cpMax = cpMax;
    ft.chrgText.cpMin = cpMin;
    ft.chrgText.cpMax = cpMax;
    ft.lpstrText = text;

    int start = send(SCI_FINDTEXT, flags, (uptr_t) (&ft));

    return QPair<int,int>(start, ft.chrgText.cpMax);
}

QByteArray ScintillaEdit::get_text_range(int start, int end) {
    if (start > end)
        start = end;

    int length = end-start;
    QByteArray ba(length+1, '\0');
    struct Sci_TextRange tr = {{start, end}, ba.data()};

    send(SCI_GETTEXTRANGE, 0, (sptr_t)&tr);
    ba.chop(1); // Remove extra NUL

    return ba;
}

ScintillaDocument *ScintillaEdit::get_doc() {
    return new ScintillaDocument(0, (void *)send(SCI_GETDOCPOINTER, 0, 0));
}

void ScintillaEdit::set_doc(ScintillaDocument *pdoc_) {
    send(SCI_SETDOCPOINTER, 0, (sptr_t)(pdoc_->pointer()));
}

long ScintillaEdit::format_range(bool draw, QPaintDevice* target, QPaintDevice* measure,
                                 const QRect& print_rect, const QRect& page_rect,
                                 long range_start, long range_end)
{
    Sci_RangeToFormat to_format;

    to_format.hdc = target;
    to_format.hdcTarget = measure;

    to_format.rc.left = print_rect.left();
    to_format.rc.top = print_rect.top();
    to_format.rc.right = print_rect.right();
    to_format.rc.bottom = print_rect.bottom();

    to_format.rcPage.left = page_rect.left();
    to_format.rcPage.top = page_rect.top();
    to_format.rcPage.right = page_rect.right();
    to_format.rcPage.bottom = page_rect.bottom();

    to_format.chrg.cpMin = range_start;
    to_format.chrg.cpMax = range_end;

    return send(SCI_FORMATRANGE, draw, reinterpret_cast<sptr_t>(&to_format));
}

/* ++Autogenerated -- start of section automatically generated from Scintilla.iface */
/* --Autogenerated -- end of section automatically generated from Scintilla.iface */
