kjs_ocg.cpp 2.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/***************************************************************************
 *   Copyright (C) 2019 by João Netto <joaonetto901@gmail.com>             *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/

#include "kjs_ocg_p.h"

#include <kjs/kjsobject.h>
#include <kjs/kjsprototype.h>
#include <kjs/kjsinterpreter.h>

#include <QString>
#include <QAbstractItemModel>
#include <QDebug>
#include <QPair>

#include <memory>

using namespace Okular;

25
static KJSPrototype *g_OCGProto;
26 27 28 29 30 31 32 33 34 35

typedef QHash< QPair< int, int > *, QAbstractItemModel* > OCGCache;
Q_GLOBAL_STATIC( OCGCache, g_OCGCache )

// OCG.state (getter)
static KJSObject OCGGetState( KJSContext *, void *object )
{
    QPair< int, int > *pair = reinterpret_cast< QPair< int, int >* > ( object );
    QAbstractItemModel *model = g_OCGCache->value( pair );

36
   	const QModelIndex index = model->index( pair->first, pair->second );
37

38
   	const bool state = model->data( index, Qt::CheckStateRole ).toBool();
39 40 41 42 43 44 45 46 47 48 49

    return KJSBoolean( state );
}

// OCG.state (setter)
static void OCGSetState( KJSContext* ctx, void* object,
                           KJSObject value )
{
   	QPair< int, int > *pair = reinterpret_cast< QPair< int, int >* > ( object );
   	QAbstractItemModel *model = g_OCGCache->value( pair );

50
   	const QModelIndex index = model->index( pair->first, pair->second );
51

52
   	const bool state = value.toBoolean( ctx );
53 54 55 56 57 58

   	model->setData( index, QVariant( state ? Qt::Checked : Qt::Unchecked ), Qt::CheckStateRole );
}


void JSOCG::initType( KJSContext *ctx )
59 60 61
{      
    static bool initialized = false;
    if ( initialized )
62
        return;
63
    initialized = true;
64

65
    g_OCGProto = new KJSPrototype();
66 67 68 69 70 71 72 73 74
    
    g_OCGProto->defineProperty( ctx, QStringLiteral("state"), OCGGetState, OCGSetState );
}

KJSObject JSOCG::object( KJSContext *ctx )
{
    return g_OCGProto->constructObject( ctx, nullptr );
}

75
KJSObject JSOCG::wrapOCGObject( KJSContext *ctx, QAbstractItemModel *model, const int &i, const int &j )
76 77 78 79 80 81 82 83 84 85 86 87 88
{
    QPair< int, int > *pair = new QPair< int ,int >( i, j );
    g_OCGCache->insert( pair, model );
    return g_OCGProto->constructObject( ctx, pair );
}

void JSOCG::clearCachedFields()
{
    if ( g_OCGCache.exists() )
    {
        g_OCGCache->clear();
    }
}