GradientWidget.cpp 16 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 *	(c) LSIIT, UMR CNRS/UdS
 *	Authors: F. Larue.
 *
 *	See licence.txt for additional information.
 */


#include "GradientWidget.h"
#include <cassert>




GradientWidget::GradientWidget( QWidget *parent ) : QWidget(parent)
{
17
    setMinimumSize( 100, 20 );
18 19 20 21 22 23 24 25 26 27 28

    m_BelowCursor  = -1;
    m_SelectedStop = -1;

    setMouseTracking( true );
    setFocusPolicy( Qt::ClickFocus );
}


GradientWidget::GradientWidget( const QColor& start, const QColor& end, QWidget *parent ) : GradientWidget(parent)
{
29 30
    addStop( start, 0.0f );
    addStop( end  , 1.0f );
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
}


GradientWidget::GradientWidget( const QList<QColor>& colors, const QList<float>& values, QWidget *parent ) : GradientWidget(parent)
{
    setStops( colors, values );
}


void GradientWidget::resizeEvent( QResizeEvent *evt )
{
    for( auto &s : m_Stops )
        s.updateX( width()-1 );
}


void GradientWidget::paintEvent( QPaintEvent *evt )
{
    if( !isValid() )
        return;

    const int w = width();
    const int h = height();

55
    QColor color = this->palette().dark().color();
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

    QPainter painter;
    painter.begin( this );

    // Display gradients between every stop pair.

    painter.setPen( Qt::NoPen );

    if( m_Stops.front().value() != 0.0f )
    {
        painter.setBrush( QBrush(m_Stops.front().color()) );
        painter.drawRect( 0, 3, m_Stops.front().x(), h-6 );
    }

    if( m_Stops.back().value() != 1.0f )
    {
        painter.setBrush( QBrush(m_Stops.back().color()) );
        painter.drawRect( m_Stops.back().x(), 3, w-m_Stops.back().x(), h-6 );
    }

    for( int i=0; i<m_Stops.size()-1; ++i )
    {
        Stop &start = m_Stops[i];
        Stop &end   = m_Stops[i+1];

        QLinearGradient g( start.x(), 0.0f, end.x(), 0.0f );
        g.setColorAt( 0.0f, start.color() );
        g.setColorAt( 1.0f, end  .color() );
        painter.setBrush( QBrush(g) );

        painter.drawRect( start.x(), 3, end.x()-start.x()+1, h-6 );
    }

    // Display stop cursors.

91
    if( isEnabled() )
92
    {
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
        for( int i=0; i<m_Stops.size(); ++i )
        {
            Stop &s = m_Stops[i];

            // Vertical bar.
            painter.setPen( QPen(QColor(255,255,255),1.0f) );
            painter.setOpacity( 0.25f );
            painter.drawLine( s.x()  , 3, s.x()  , h-4 );
            painter.setOpacity( 0.22f );
            painter.drawLine( s.x()-1, 3, s.x()-1, h-4 );
            painter.drawLine( s.x()+1, 3, s.x()+1, h-4 );

            painter.setOpacity( 1.0f );
            if( i == m_SelectedStop )
                painter.setPen( QPen(color,1.0f) );
            else
109
                painter.setPen( QPen(color,1.0f,Qt::DashLine) );
110
            painter.drawLine( s.x(), 3, s.x(), h-4 );
111 112
            painter.setPen( QPen(color,1.0f) );

113
            // Top arrow head.
114
            //if( i == m_SelectedStop )
115 116 117 118 119
                painter.drawLine( s.x()-3, 0, s.x()+3, 0 );
            painter.drawLine( s.x()-2, 1, s.x()+2, 1 );
            painter.drawLine( s.x()-1, 2, s.x()+1, 2 );

            // Bottom arrow head.
120
            //if( i == m_SelectedStop )
121 122 123 124 125 126 127 128 129 130
                painter.drawLine( s.x()-3, h-1, s.x()+3, h-1 );
            painter.drawLine( s.x()-2, h-2, s.x()+2, h-2 );
            painter.drawLine( s.x()-1, h-3, s.x()+1, h-3 );
        }

        if( m_SelectedStop >= 0 )
        {
            QString text = m_KeyboardInputValue.isEmpty()?  QString::number(m_Stops[m_SelectedStop].value()) : m_KeyboardInputValue;

            QFontMetrics fm( font() );
131
#if QT_VERSION < QT_VERSION_CHECK(5,11,0)
132
            int textW = fm.width( text );
133 134 135
#else
            int textW = fm.horizontalAdvance( text );
#endif
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153

            int textX = m_Stops[m_SelectedStop].x() + 4;
            int textY = ((h+fm.height()) >> 1) - fm.descent();

            if( textX+textW >= w )
                textX -= textW + 7;

            painter.setOpacity( 0.5f );
            painter.setPen( QPen(QColor(255,255,255),1.0f) );
            painter.drawText( textX  , textY+1, text );
            painter.drawText( textX+1, textY  , text );
            painter.setOpacity( 0.25f );
            painter.drawText( textX  , textY-1, text );
            painter.drawText( textX-1, textY  , text );
            painter.setOpacity( 1.0f );
            painter.setPen( QPen(color,1.0f) );
            painter.drawText( textX, textY, text );
        }
154 155 156 157 158 159 160 161 162 163 164 165 166 167
    }

    painter.end();
}


int GradientWidget::getInterval( float value ) const
{
    int beg = 0, end = m_Stops.size();

    while( end != beg )
    {
        int p = beg + (end-beg)/2;

168
        if( value < m_Stops[p].value() )
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
            end = p;
        else
            beg = p+1;
    }

    return end;
}


QColor GradientWidget::getColor( int interval, float value ) const
{
    assert( isValid() );

    if( interval == 0 )
        return m_Stops.front().color();
    else if( interval == m_Stops.size() )
        return m_Stops.back().color();
    else
    {
        const Stop &s0 = m_Stops[interval-1];
        const Stop &s1 = m_Stops[interval  ];

        float alpha = (value - s0.value()) / (s1.value() - s0.value());

        const QColor &c0 = s0.color();
        const QColor &c1 = s1.color();

        float r = c0.redF  () + alpha*(c1.redF  () - c0.redF  ());
        float g = c0.greenF() + alpha*(c1.greenF() - c0.greenF());
        float b = c0.blueF () + alpha*(c1.blueF () - c0.blueF ());

        return QColor::fromRgbF( r, g, b );
    }
}


float GradientWidget::clampValueToStopInterval( int n, float value ) const
{
    value = std::max( 0.0f, std::min(value,1.0f) );

    if( n > 0  &&  value < m_Stops[n-1].value() )
        value = m_Stops[n-1].value();
    else if( n < m_Stops.size()-1  &&  value > m_Stops[n+1].value() )
        value = m_Stops[n+1].value();

    return value;
}


void GradientWidget::addStop( const QColor& color, float value )
{
    Stop stop( color, value );
    stop.updateX( width()-1 );

    m_Stops.insert( getInterval(value), stop );

225
    emit gradientModified();
226 227 228 229 230 231 232 233 234
    update();
}


void GradientWidget::setStops( const QList<QColor>& colors, const QList<float>& values )
{
    assert( colors.size() == values.size() );
    assert( !colors.empty() );

235
    bool changed = false;
236 237
    QVector<Stop> stopsBackup = m_Stops;
    m_Stops.clear();
238 239 240 241

    auto c = colors.begin();
    auto v = values.begin();

242
    int i = 0;
243 244
    while( c != colors.end() )
    {
245 246
        if( i < stopsBackup.size() )
            changed |= (stopsBackup[i].color() != *c  ||  stopsBackup[i].value() != *v);
247
        else
248
            changed = true;
249 250 251 252 253
        ++ i;

        Stop stop( *c, *v );
        stop.updateX( width()-1 );

254
        m_Stops.insert( getInterval(*v), stop );
255

256 257 258
        ++ c;
        ++ v;
    }
259 260 261 262 263 264

    if( changed )
    {
        emit gradientModified();
        update();
    }
265 266 267
}


268
QString GradientWidget::getShaderFunctionBodyGLSL( const QVector< QPair<int,int> >& uniqueStops, int beg, int end, const QString& indent ) const
269 270 271 272 273
{
    QString res;
    if( end != beg )
    {
        int p = beg + (end-beg)/2;
274

275
        res += indent + "if( value <= " + QString::number( (double) m_Stops[ uniqueStops[p].first ].value() ) + " )\n";
276
        res += getShaderFunctionBodyGLSL( uniqueStops, beg, p, indent+"  " );
277
        res += indent + "else\n";
278
        res += getShaderFunctionBodyGLSL( uniqueStops, p+1, end, indent+"  " );
279 280 281 282 283 284 285 286
    }
    else
    {
        if( beg == 0 )
        {
            QColor c = m_Stops.front().color();
            res = indent + "return vec3(" + QString::number(c.redF()) + "," + QString::number(c.greenF()) + "," + QString::number(c.blueF()) + ");\n";
        }
287
        else if( beg == uniqueStops.size() )
288 289 290 291 292 293
        {
            QColor c = m_Stops.back().color();
            res = indent + "return vec3(" + QString::number(c.redF()) + "," + QString::number(c.greenF()) + "," + QString::number(c.blueF()) + ");\n";
        }
        else
        {
294 295
            const Stop &s0 = m_Stops[ uniqueStops[beg-1].second ];
            const Stop &s1 = m_Stops[ uniqueStops[beg  ].first  ];
296 297 298 299 300 301 302

            const QColor &c0 = s0.color();
            const QColor &c1 = s1.color();

            res += indent + "return mix( ";
            res += "vec3(" + QString::number(c0.redF()) + "," + QString::number(c0.greenF()) + "," + QString::number(c0.blueF()) + "), ";
            res += "vec3(" + QString::number(c1.redF()) + "," + QString::number(c1.greenF()) + "," + QString::number(c1.blueF()) + "), ";
303
            res += "(value-" + QString::number((double) s0.value()) + ")*" + QString::number(1.0 / (s1.value() - s0.value()));
304 305 306 307 308 309 310 311
            res += " );\n";
        }
    }

    return res;
}


312
QString GradientWidget::getShaderFunctionGLSL( const QString& funcName ) const
313
{
314 315 316 317 318 319 320 321 322 323 324 325
    QVector< QPair<int,int> > uniqueStops;
    for( int left=0; left<m_Stops.size(); ++left )
    {
        int right = left;
        while( right<m_Stops.size()-1  &&  m_Stops[right+1].value() == m_Stops[left].value() )
            ++ right;

        uniqueStops.push_back( QPair<int,int>(left,right) );

        left = right;
    }

326 327 328
    QString func =
        "vec3 " + funcName + "( float value )\n"
        "{\n"
329
        + getShaderFunctionBodyGLSL( uniqueStops, 0, uniqueStops.size(), "    " ) +
330 331 332 333 334 335 336 337 338 339 340 341
        "}\n";

    return func;
}


void GradientWidget::mouseDoubleClickEvent( QMouseEvent *evt )
{
    if( m_SelectedStop >= 0 )
    {
        Stop &stop = m_Stops[m_SelectedStop];
        QColor color = QColorDialog::getColor( stop.color(), this, "Select gradient stop color" );
342
        if( color.isValid()  &&  color != stop.color() )
343 344
        {
            stop.setColor( color );
345
            emit gradientModified();
346 347 348 349 350 351 352 353 354 355 356 357
            update();
        }
    }
    else
    {
        float value = float(evt->x()) / (width()-1);
        int interval = getInterval( value );

        Stop stop( getColor(interval,value), value );
        stop.updateX( width()-1 );
        m_Stops.insert( interval, stop );

358
        emit gradientModified();
359 360 361 362 363 364 365 366
        update();
    }
}


void GradientWidget::mousePressEvent( QMouseEvent *evt )
{
    m_SelectedStop = m_BelowCursor;
367
    m_SelectedStopRight = m_BelowCursorRight;
368
    m_PreviousMouseX = evt->x();
369 370 371 372 373 374 375 376
    update();
}


void GradientWidget::mouseMoveEvent( QMouseEvent *evt )
{
    if( (evt->buttons() & Qt::LeftButton)  &&  m_SelectedStop >= 0 )
    {
377
        if( m_SelectedStopRight != m_SelectedStop )
378 379
        {
            if( evt->x()-m_PreviousMouseX > 0 )
380
                m_SelectedStop = m_SelectedStopRight;
381
            else
382
                m_SelectedStopRight = m_SelectedStop;
383 384
        }

385
        float value = clampValueToStopInterval( m_SelectedStop, float(evt->x()) / (width()-1) );
386 387 388 389 390 391 392
        if( value != m_Stops[m_SelectedStop].value() )
        {
            m_Stops[m_SelectedStop].setValue( value );
            m_Stops[m_SelectedStop].updateX( width()-1 );
            emit gradientModified();
            update();
        }
393 394 395 396 397 398 399 400 401 402 403 404 405 406
    }
    else
    {
        int belowCursor = -1;
        for( int i=0; i<m_Stops.size(); ++i )
            if( evt->x() >= m_Stops[i].x()-2  &&  evt->x() <= m_Stops[i].x()+2 )
            {
                belowCursor = i;
                break;
            }

        if( belowCursor != m_BelowCursor )
        {
            m_BelowCursor = belowCursor;
407 408 409 410 411 412 413 414

            if( belowCursor >= 0 )
            {
                m_BelowCursorRight = belowCursor;
                while( m_BelowCursorRight<m_Stops.size()-1  &&  m_Stops[m_BelowCursorRight+1].value() == m_Stops[belowCursor].value() )
                    ++ m_BelowCursorRight;
            }

415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
            setCursor( belowCursor<0? Qt::ArrowCursor : Qt::PointingHandCursor );
        }
    }
}


void GradientWidget::keyPressEvent( QKeyEvent *evt )
{
    if( m_SelectedStop < 0 )
    {
        m_KeyboardInputValue = QString();
        QWidget::keyPressEvent( evt );
        return;
    }

    switch( evt->key() )
    {
        case Qt::Key_0:
        case Qt::Key_1:
        case Qt::Key_2:
        case Qt::Key_3:
        case Qt::Key_4:
        case Qt::Key_5:
        case Qt::Key_6:
        case Qt::Key_7:
        case Qt::Key_8:
        case Qt::Key_9:
        case Qt::Key_Period:
        {
            bool ok;
            QString tmp = m_KeyboardInputValue + (char) evt->key();
            if( tmp == "." )
                tmp = "0.";
448
            float value = tmp.toFloat( &ok );
449 450
            if( ok )
            {
451 452 453 454 455 456 457 458 459 460
                if( value >= 2.0f )
                {
                    m_KeyboardInputValue = "0." + tmp;
                    update();
                }
                else if( value <= 1.0f )
                {
                    m_KeyboardInputValue = tmp;
                    update();
                }
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
            }
            break;
        }
        case Qt::Key_Backspace:
        {
            m_KeyboardInputValue = m_KeyboardInputValue.left( m_KeyboardInputValue.size()-1 );
            update();
            break;
        }
        case Qt::Key_Delete:
        {
            if( m_Stops.size() > 1 )
            {
                m_Stops.remove( m_SelectedStop );
                m_SelectedStop = -1;
                m_KeyboardInputValue = QString();
477
                emit gradientModified();
478 479 480 481 482 483 484 485 486 487
                update();
            }
            break;
        }
        case Qt::Key_Enter:
        case Qt::Key_Return:
        {
            if( m_KeyboardInputValue.isEmpty() )
                break;

488
            float value = m_KeyboardInputValue.toFloat();
489 490
            m_KeyboardInputValue = QString();

491 492 493 494 495 496 497 498 499 500
            if( m_SelectedStop != m_SelectedStopRight )
            {
                if( value > m_Stops[m_SelectedStop].value() )
                    m_SelectedStop = m_SelectedStopRight;
                else
                    m_SelectedStopRight = m_SelectedStop;
            }

            value = clampValueToStopInterval( m_SelectedStop, value );

501 502 503 504 505 506
            if( value != m_Stops[m_SelectedStop].value() )
            {
                m_Stops[m_SelectedStop].setValue( value );
                m_Stops[m_SelectedStop].updateX( width()-1 );
                emit gradientModified();
            }
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523

            update();
            break;
        }
        default: QWidget::keyPressEvent( evt );
    }
}


void GradientWidget::leaveEvent( QEvent *evt )
{
    if( m_SelectedStop >= 0 )
    {
        m_SelectedStop = -1;
        update();
    }
}
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542


void GradientWidget::getStops( QVector<float> &values, QVector<QColor> &colors ) const
{
    values.clear();
    colors.clear();

    if( m_Stops.isEmpty() )
        return;

    values.reserve( m_Stops.size() );
    colors.reserve( m_Stops.size() );

    for( auto &s : m_Stops )
    {
        values.push_back( s.value() );
        colors.push_back( s.color() );
    }
}
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605


QString GradientWidget::ValueString() const
{
    QString str;

    for( auto &s : m_Stops )
    {
        QTextStream stream( &str );

        if( &s != &m_Stops[0] )
            stream << ", ";

        stream << (double) s.value() << ": ";

        stream << "#";
        stream.setFieldWidth(2);
        stream.setPadChar('0');
        stream << QString::number( s.color().red()  , 16 ).toUpper();
        stream << QString::number( s.color().green(), 16 ).toUpper();
        stream << QString::number( s.color().blue() , 16 ).toUpper();
        stream << QString::number( s.color().alpha(), 16 ).toUpper();
    }

    return str;
}


bool GradientWidget::SetValueString( const QString &valueString )
{
    QStringList stopStrings = valueString.split( ',' );

    QList<float> values;
    QList<QColor> colors;

    QRegExp rgbaExp( "#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})" );
    for( auto &stop : stopStrings )
    {
        QStringList valueAndColor = stop.remove( ' ' ).split( ':' );
        if( valueAndColor.size() != 2 )
            return false;

        bool ok;
        float value = valueAndColor.front().toFloat( &ok );
        if( !ok )
            return false;

        if( rgbaExp.indexIn(valueAndColor.back()) < 0 )
            return false;

        int r = rgbaExp.cap(1).toInt( NULL, 16 );
        int g = rgbaExp.cap(2).toInt( NULL, 16 );
        int b = rgbaExp.cap(3).toInt( NULL, 16 );
        int a = rgbaExp.cap(4).toInt( NULL, 16 );

        values.push_back( value );
        colors.push_back( QColor(r,g,b,a) );
    }

    setStops( colors, values );

    return true;
}