qwt_date_scale_engine.cpp 34.7 KB
Newer Older
Bryant's avatar
Bryant committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 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 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 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 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 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 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
#include "qwt_date_scale_engine.h"
#include "qwt_math.h"
#include "qwt_transform.h"
#include <qdatetime.h>
#include <limits.h>

static inline double qwtMsecsForType( QwtDate::IntervalType type )
{
    static const double msecs[] =
    {
        1.0,
        1000.0,
        60.0 * 1000.0,
        3600.0 * 1000.0,
        24.0 * 3600.0 * 1000.0,
        7.0 * 24.0 * 3600.0 * 1000.0,
        30.0 * 24.0 * 3600.0 * 1000.0,
        365.0 * 24.0 * 3600.0 * 1000.0,
    };

    if ( type < 0 || type >= static_cast<int>( sizeof( msecs ) / sizeof( msecs[0] ) ) )
        return 1.0;

    return msecs[ type ];
}

static inline int qwtAlignValue(
    double value, double stepSize, bool up )
{
    double d = value / stepSize;
    d = up ? ::ceil( d ) : ::floor( d );

    return static_cast<int>( d * stepSize );
}

static double qwtIntervalWidth( const QDateTime &minDate,
    const QDateTime &maxDate, QwtDate::IntervalType intervalType ) 
{
    switch( intervalType )
    {
        case QwtDate::Millisecond:
        {
            const double secsTo = minDate.secsTo( maxDate );
            const double msecs = maxDate.time().msec() -
                minDate.time().msec();

            return secsTo * 1000 + msecs;
        }
        case QwtDate::Second:
        {
            return minDate.secsTo( maxDate );
        }
        case QwtDate::Minute:
        {
            const double secsTo = minDate.secsTo( maxDate );
            return ::floor( secsTo / 60 );
        }
        case QwtDate::Hour:
        {
            const double secsTo = minDate.secsTo( maxDate );
            return ::floor( secsTo / 3600 );
        }
        case QwtDate::Day:
        {
            return minDate.daysTo( maxDate );
        }
        case QwtDate::Week:
        {
            return ::floor( minDate.daysTo( maxDate ) / 7.0 );
        }
        case QwtDate::Month:
        {
            const double years = 
                double( maxDate.date().year() ) - minDate.date().year();

            int months = maxDate.date().month() - minDate.date().month();
            if ( maxDate.date().day() < minDate.date().day() )
                months--;

            return years * 12 + months;
        }
        case QwtDate::Year:
        {
            double years = 
                double( maxDate.date().year() ) - minDate.date().year();

            if ( maxDate.date().month() < minDate.date().month() )
                years -= 1.0;

            return years;
        }
    }

    return 0.0;
}

static double qwtRoundedIntervalWidth( 
    const QDateTime &minDate, const QDateTime &maxDate, 
    QwtDate::IntervalType intervalType ) 
{
    const QDateTime minD = QwtDate::floor( minDate, intervalType );
    const QDateTime maxD = QwtDate::ceil( maxDate, intervalType );

    return qwtIntervalWidth( minD, maxD, intervalType );
}

static inline int qwtStepCount( int intervalSize, int maxSteps,
    const int limits[], size_t numLimits )
{
    for ( uint i = 0; i < numLimits; i++ )
    {
        const int numSteps = intervalSize / limits[ i ];

        if ( numSteps > 1 && numSteps <= maxSteps &&
            numSteps * limits[ i ] == intervalSize )
        {
            return numSteps;
        }
    }

    return 0;
}

static int qwtStepSize( int intervalSize, int maxSteps, uint base ) 
{
    if ( maxSteps <= 0 )
        return 0;

    if ( maxSteps > 2 )
    {
        for ( int numSteps = maxSteps; numSteps > 1; numSteps-- )
        {
            const double stepSize = double( intervalSize ) / numSteps;

            const double p = ::floor( ::log( stepSize ) / ::log( double( base ) ) );
            const double fraction = qPow( base, p );

            for ( uint n = base; n >= 1; n /= 2 )
            {
                if ( qFuzzyCompare( stepSize, n * fraction ) )
                    return qRound( stepSize );

                if ( n == 3 && ( base % 2 ) == 0 )
                {
                    if ( qFuzzyCompare( stepSize, 2 * fraction ) )
                        return qRound( stepSize );
                }
            }
        }
    }

    return 0;
}

static int qwtDivideInterval( double intervalSize, int numSteps, 
    const int limits[], size_t numLimits )
{
    const int v = qCeil( intervalSize / double( numSteps ) );

    for ( uint i = 0; i < numLimits - 1; i++ )
    {
        if ( v <= limits[i] )
            return limits[i];
    }

    return limits[ numLimits - 1 ];
}

static double qwtDivideScale( double intervalSize, int numSteps,
    QwtDate::IntervalType intervalType )
{
    if ( intervalType != QwtDate::Day )
    {
        if ( ( intervalSize > numSteps ) && 
            ( intervalSize <= 2 * numSteps ) )
        {
            return 2.0;
        }
    }

    double stepSize;

    switch( intervalType )
    {
        case QwtDate::Second:
        case QwtDate::Minute:
        {
            static int limits[] = { 1, 2, 5, 10, 15, 20, 30, 60 };
    
            stepSize = qwtDivideInterval( intervalSize, numSteps,
                limits, sizeof( limits ) / sizeof( int ) );

            break;
        }
        case QwtDate::Hour:
        {
            static int limits[] = { 1, 2, 3, 4, 6, 12, 24 };
    
            stepSize = qwtDivideInterval( intervalSize, numSteps,
                limits, sizeof( limits ) / sizeof( int ) );

            break;
        }
        case QwtDate::Day:
        {
            const double v = intervalSize / double( numSteps );
            if ( v <= 5.0 )
                stepSize = qCeil( v );
            else
                stepSize = qCeil( v / 7 ) * 7;

            break;
        }
        case QwtDate::Week:
        {
            static int limits[] = { 1, 2, 4, 8, 12, 26, 52 };

            stepSize = qwtDivideInterval( intervalSize, numSteps,
                limits, sizeof( limits ) / sizeof( int ) );

            break;
        }
        case QwtDate::Month:
        {
            static int limits[] = { 1, 2, 3, 4, 6, 12 };

            stepSize = qwtDivideInterval( intervalSize, numSteps,
                limits, sizeof( limits ) / sizeof( int ) );

            break;
        }
        case QwtDate::Year:
        case QwtDate::Millisecond:
        default:
        {
            stepSize = QwtScaleArithmetic::divideInterval(
                intervalSize, numSteps, 10 );
        }
    }

    return stepSize;
}

static double qwtDivideMajorStep( double stepSize, int maxMinSteps,
    QwtDate::IntervalType intervalType )
{
    double minStepSize = 0.0;

    switch( intervalType )
    {
        case QwtDate::Second:
        {
            minStepSize = qwtStepSize( stepSize, maxMinSteps, 10 );
            if ( minStepSize == 0.0 )
                minStepSize = 0.5 * stepSize;

            break;
        }
        case QwtDate::Minute:
        {
            static int limits[] = { 1, 2, 5, 10, 15, 20, 30, 60 };

            int numSteps;

            if ( stepSize > maxMinSteps )
            {
                numSteps = qwtStepCount( stepSize, maxMinSteps, 
                    limits, sizeof( limits ) / sizeof( int ) );

            }
            else
            {
                numSteps = qwtStepCount( stepSize * 60, maxMinSteps, 
                    limits, sizeof( limits ) / sizeof( int ) );
            }

            if ( numSteps > 0 )
                minStepSize = double( stepSize ) / numSteps;

            break;
        }
        case QwtDate::Hour:
        {
            int numSteps = 0;

            if ( stepSize > maxMinSteps )
            {
                static int limits[] = { 1, 2, 3, 4, 6, 12, 24, 48, 72 };

                numSteps = qwtStepCount( stepSize, maxMinSteps,
                    limits, sizeof( limits ) / sizeof( int ) );
            }
            else
            {
                static int limits[] = { 1, 2, 5, 10, 15, 20, 30, 60 };

                numSteps = qwtStepCount( stepSize * 60, maxMinSteps,
                    limits, sizeof( limits ) / sizeof( int ) );
            }

            if ( numSteps > 0 )
                minStepSize = double( stepSize ) / numSteps;

            break;
        }
        case QwtDate::Day:
        {
            int numSteps = 0;

            if ( stepSize > maxMinSteps )
            {
                static int limits[] = { 1, 2, 3, 7, 14, 28 };

                numSteps = qwtStepCount( stepSize, maxMinSteps,
                    limits, sizeof( limits ) / sizeof( int ) );
            }
            else
            {
                static int limits[] = { 1, 2, 3, 4, 6, 12, 24, 48, 72 };

                numSteps = qwtStepCount( stepSize * 24, maxMinSteps,
                    limits, sizeof( limits ) / sizeof( int ) );
            }

            if ( numSteps > 0 )
                minStepSize = double( stepSize ) / numSteps;

            break;
        }
        case QwtDate::Week:
        {
            const int daysInStep = stepSize * 7;

            if ( maxMinSteps >= daysInStep )
            {
                // we want to have one tick per day
                minStepSize = 1.0 / 7.0;
            }
            else
            {
                // when the stepSize is more than a week we want to
                // have a tick for each week

                const int stepSizeInWeeks = stepSize;

                if ( stepSizeInWeeks <= maxMinSteps )
                {
                    minStepSize = 1;
                }
                else
                {
                    minStepSize = QwtScaleArithmetic::divideInterval( 
                        stepSizeInWeeks, maxMinSteps, 10 );
                }
            }
            break;
        }
        case QwtDate::Month:
        {
            // fractions of months doesn't make any sense

            if ( stepSize < maxMinSteps )
                maxMinSteps = static_cast<int>( stepSize );

            static int limits[] = { 1, 2, 3, 4, 6, 12 };

            int numSteps = qwtStepCount( stepSize, maxMinSteps,
                limits, sizeof( limits ) / sizeof( int ) );

            if ( numSteps > 0 )
                minStepSize = double( stepSize ) / numSteps;

            break;
        }
        case QwtDate::Year:
        {
            if ( stepSize >= maxMinSteps )
            {
                minStepSize = QwtScaleArithmetic::divideInterval(
                    stepSize, maxMinSteps, 10 );
            }
            else
            {
                // something in months

                static int limits[] = { 1, 2, 3, 4, 6, 12 };

                int numSteps = qwtStepCount( 12 * stepSize, maxMinSteps,
                    limits, sizeof( limits ) / sizeof( int ) );

                if ( numSteps > 0 )
                    minStepSize = double( stepSize ) / numSteps;
            }
                
            break;
        }
        default:
            break;
    }

    if ( intervalType != QwtDate::Month
        && minStepSize == 0.0 )
    {
        minStepSize = 0.5 * stepSize;
    }

    return minStepSize;
}

static QList<double> qwtDstTicks( const QDateTime &dateTime,
    int secondsMajor, int secondsMinor )
{
    if ( secondsMinor <= 0 )
        QList<double>();

    QDateTime minDate = dateTime.addSecs( -secondsMajor );
    minDate = QwtDate::floor( minDate, QwtDate::Hour );

    const double utcOffset = QwtDate::utcOffset( dateTime );

    // find the hours where daylight saving time happens

    double dstMin = QwtDate::toDouble( minDate );
    while ( minDate < dateTime &&
        QwtDate::utcOffset( minDate ) != utcOffset )
    {
        minDate = minDate.addSecs( 3600 );
        dstMin += 3600 * 1000.0;
    }

    QList<double> ticks;
    for ( int i = 0; i < 3600; i += secondsMinor )
        ticks += dstMin + i * 1000.0;

    return ticks;
}

static QwtScaleDiv qwtDivideToSeconds( 
    const QDateTime &minDate, const QDateTime &maxDate,
    double stepSize, int maxMinSteps,
    QwtDate::IntervalType intervalType ) 
{
    // calculate the min step size
    double minStepSize = 0;

    if ( maxMinSteps > 1 ) 
    {
        minStepSize = qwtDivideMajorStep( stepSize, 
            maxMinSteps, intervalType );
    }

    bool daylightSaving = false;
    if ( minDate.timeSpec() == Qt::LocalTime )
    {
        daylightSaving = intervalType > QwtDate::Hour;
        if ( intervalType == QwtDate::Hour )
        {
            daylightSaving = stepSize > 1;
        }
    }

    const double s = qwtMsecsForType( intervalType ) / 1000;
    const int secondsMajor = static_cast<int>( stepSize * s );
    const double secondsMinor = minStepSize * s;
    
    // UTC excludes daylight savings. So from the difference
    // of a date and its UTC counterpart we can find out
    // the daylight saving hours

    const double utcOffset = QwtDate::utcOffset( minDate );
    double dstOff = 0;

    QList<double> majorTicks;
    QList<double> mediumTicks;
    QList<double> minorTicks;

    for ( QDateTime dt = minDate; dt <= maxDate; 
        dt = dt.addSecs( secondsMajor ) )
    {
        if ( !dt.isValid() )
            break;

        double majorValue = QwtDate::toDouble( dt );

        if ( daylightSaving )
        {
            const double offset = utcOffset - QwtDate::utcOffset( dt );
            majorValue += offset * 1000.0;

            if ( offset > dstOff )
            {
                // we add some minor ticks for the DST hour,
                // otherwise the ticks will be unaligned: 0, 2, 3, 5 ...
                minorTicks += qwtDstTicks( 
                    dt, secondsMajor, qRound( secondsMinor ) );
            }

            dstOff = offset;
        }

        if ( majorTicks.isEmpty() || majorTicks.last() != majorValue )
            majorTicks += majorValue;

        if ( secondsMinor > 0.0 )
        {
            const int numMinorSteps = qFloor( secondsMajor / secondsMinor );

            for ( int i = 1; i < numMinorSteps; i++ )
            {
                const QDateTime mt = dt.addMSecs( 
                    qRound64( i * secondsMinor * 1000 ) );

                double minorValue = QwtDate::toDouble( mt );
                if ( daylightSaving )
                {
                    const double offset = utcOffset - QwtDate::utcOffset( mt );
                    minorValue += offset * 1000.0;
                }

                if ( minorTicks.isEmpty() || minorTicks.last() != minorValue )
                {
                    const bool isMedium = ( numMinorSteps % 2 == 0 ) 
                        && ( i != 1 ) && ( i == numMinorSteps / 2 );

                    if ( isMedium )
                        mediumTicks += minorValue;
                    else
                        minorTicks += minorValue;
                }
            }
        }
    }

    QwtScaleDiv scaleDiv;

    scaleDiv.setInterval( QwtDate::toDouble( minDate ),
        QwtDate::toDouble( maxDate ) );

    scaleDiv.setTicks( QwtScaleDiv::MajorTick, majorTicks );
    scaleDiv.setTicks( QwtScaleDiv::MediumTick, mediumTicks );
    scaleDiv.setTicks( QwtScaleDiv::MinorTick, minorTicks );

    return scaleDiv;
}

static QwtScaleDiv qwtDivideToMonths( 
    QDateTime &minDate, const QDateTime &maxDate,
    double stepSize, int maxMinSteps ) 
{
    // months are intervals with non 
    // equidistant ( in ms ) steps: we have to build the 
    // scale division manually

    int minStepDays = 0;
    int minStepSize = 0.0; 

    if ( maxMinSteps > 1 )
    {
        if ( stepSize == 1 )
        {
            if ( maxMinSteps >= 30 )
                minStepDays = 1;
            else if ( maxMinSteps >= 6 )
                minStepDays = 5;
            else if ( maxMinSteps >= 3 )
                minStepDays = 10;

            minStepDays = 15;
        }
        else
        {
            minStepSize = qwtDivideMajorStep( 
                stepSize, maxMinSteps, QwtDate::Month );
        }
    }

    QList<double> majorTicks;
    QList<double> mediumTicks;
    QList<double> minorTicks;

    for ( QDateTime dt = minDate; 
        dt <= maxDate; dt = dt.addMonths( stepSize ) )
    {
        if ( !dt.isValid() )
            break;

        majorTicks += QwtDate::toDouble( dt );

        if ( minStepDays > 0 )
        {
            for ( int days = minStepDays; 
                days < 30; days += minStepDays )
            {
                const double tick = QwtDate::toDouble( dt.addDays( days ) );

                if ( days == 15 && minStepDays != 15 )
                    mediumTicks += tick;
                else
                    minorTicks += tick;
            }
        }
        else if ( minStepSize > 0.0 )
        {
            const int numMinorSteps = qRound( stepSize / (double) minStepSize );

            for ( int i = 1; i < numMinorSteps; i++ )
            {
                const double minorValue =
                    QwtDate::toDouble( dt.addMonths( i * minStepSize ) );

                if ( ( numMinorSteps % 2 == 0 ) && ( i == numMinorSteps / 2 ) )
                    mediumTicks += minorValue;
                else
                    minorTicks += minorValue;
            }
        }
    }

    QwtScaleDiv scaleDiv;
    scaleDiv.setInterval( QwtDate::toDouble( minDate ),
        QwtDate::toDouble( maxDate ) );

    scaleDiv.setTicks( QwtScaleDiv::MajorTick, majorTicks );
    scaleDiv.setTicks( QwtScaleDiv::MediumTick, mediumTicks );
    scaleDiv.setTicks( QwtScaleDiv::MinorTick, minorTicks );

    return scaleDiv;
}

static QwtScaleDiv qwtDivideToYears( 
    const QDateTime &minDate, const QDateTime &maxDate,
    double stepSize, int maxMinSteps ) 
{
    QList<double> majorTicks;
    QList<double> mediumTicks;
    QList<double> minorTicks;

    double minStepSize = 0.0;

    if ( maxMinSteps > 1 )
    {
        minStepSize = qwtDivideMajorStep( 
            stepSize, maxMinSteps, QwtDate::Year );
    }

    int numMinorSteps = 0;
    if ( minStepSize > 0.0 )
        numMinorSteps = qFloor( stepSize / minStepSize );

    bool dateBC = minDate.date().year() < -1;

    for ( QDateTime dt = minDate; dt <= maxDate;
        dt = dt.addYears( stepSize ) )
    {
        if ( dateBC && dt.date().year() > 1 )
        {
            // there is no year 0 in the Julian calendar
            dt = dt.addYears( -1 );
            dateBC = false;
        }

        if ( !dt.isValid() )
            break;

        majorTicks += QwtDate::toDouble( dt );

        for ( int i = 1; i < numMinorSteps; i++ )
        {
            QDateTime tickDate;

            const double years = qRound( i * minStepSize );
            if ( years >= INT_MAX / 12 )
            {
                tickDate = dt.addYears( years );
            }
            else
            {
                tickDate = dt.addMonths( qRound( years * 12 ) );
            }

            const bool isMedium = ( numMinorSteps > 2 ) &&
                ( numMinorSteps % 2 == 0 ) && ( i == numMinorSteps / 2 );

            const double minorValue = QwtDate::toDouble( tickDate );
            if ( isMedium )
                mediumTicks += minorValue;
            else
                minorTicks += minorValue;
        }

        if ( QwtDate::maxDate().addYears( -stepSize ) < dt.date() )
        {
            break;
        }
    }   

    QwtScaleDiv scaleDiv;
    scaleDiv.setInterval( QwtDate::toDouble( minDate ),
        QwtDate::toDouble( maxDate ) );

    scaleDiv.setTicks( QwtScaleDiv::MajorTick, majorTicks );
    scaleDiv.setTicks( QwtScaleDiv::MediumTick, mediumTicks );
    scaleDiv.setTicks( QwtScaleDiv::MinorTick, minorTicks );

    return scaleDiv;
}

class QwtDateScaleEngine::PrivateData
{
public:
    PrivateData( Qt::TimeSpec spec ):
        timeSpec( spec ),
        utcOffset( 0 ),
        week0Type( QwtDate::FirstThursday ),
        maxWeeks( 4 )
    {
    }

    Qt::TimeSpec timeSpec;
    int utcOffset;
    QwtDate::Week0Type week0Type;
    int maxWeeks;
};      


/*!
  \brief Constructor

  The engine is initialized to build scales for the 
  given time specification. It classifies intervals > 4 weeks
  as >= Qt::Month. The first week of a year is defined like
  for QwtDate::FirstThursday.

  \param timeSpec Time specification

  \sa setTimeSpec(), setMaxWeeks(), setWeek0Type()
 */
QwtDateScaleEngine::QwtDateScaleEngine( Qt::TimeSpec timeSpec ):
    QwtLinearScaleEngine( 10 )
{
    d_data = new PrivateData( timeSpec );
}

//! Destructor
QwtDateScaleEngine::~QwtDateScaleEngine()
{
    delete d_data;
}

/*!
  Set the time specification used by the engine

  \param timeSpec Time specification
  \sa timeSpec(), setUtcOffset(), toDateTime()
 */
void QwtDateScaleEngine::setTimeSpec( Qt::TimeSpec timeSpec )
{
    d_data->timeSpec = timeSpec;
}

/*!
  \return Time specification used by the engine
  \sa setTimeSpec(), utcOffset(), toDateTime()
 */
Qt::TimeSpec QwtDateScaleEngine::timeSpec() const
{
    return d_data->timeSpec;
}

/*!
  Set the offset in seconds from Coordinated Universal Time

  \param seconds Offset in seconds

  \note The offset has no effect beside for the time specification
        Qt::OffsetFromUTC.

  \sa QDate::utcOffset(), setTimeSpec(), toDateTime()
 */
void QwtDateScaleEngine::setUtcOffset( int seconds )
{
    d_data->utcOffset = seconds;
}

/*!
  \return Offset in seconds from Coordinated Universal Time
  \note The offset has no effect beside for the time specification
        Qt::OffsetFromUTC.

  \sa QDate::setUtcOffset(), setTimeSpec(), toDateTime()
 */
int QwtDateScaleEngine::utcOffset() const
{
    return d_data->utcOffset;
}

/*!
  Sets how to identify the first week of a year.

  \param week0Type Mode how to identify the first week of a year

  \sa week0Type(), setMaxWeeks()
  \note week0Type has no effect beside for intervals classified as
        QwtDate::Week. 
 */
void QwtDateScaleEngine::setWeek0Type( QwtDate::Week0Type week0Type )
{
    d_data->week0Type = week0Type;
}

/*!
  \return Setting how to identify the first week of a year. 
  \sa setWeek0Type(), maxWeeks()
 */
QwtDate::Week0Type QwtDateScaleEngine::week0Type() const
{
    return d_data->week0Type;
}

/*!
  Set a upper limit for the number of weeks, when an interval
  can be classified as Qt::Week.

  The default setting is 4 weeks.

  \param weeks Upper limit for the number of weeks

  \note In business charts a year is often devided
        into weeks [1-52]
  \sa maxWeeks(), setWeek0Type() 
 */
void QwtDateScaleEngine::setMaxWeeks( int weeks )
{
    d_data->maxWeeks = qMax( weeks, 0 );
}

/*!
  \return Upper limit for the number of weeks, when an interval
          can be classified as Qt::Week.
  \sa setMaxWeeks(), week0Type()
 */
int QwtDateScaleEngine::maxWeeks() const
{
    return d_data->maxWeeks;
}

/*!
  Classification of a date/time interval division

  \param minDate Minimum ( = earlier ) of the interval
  \param maxDate Maximum ( = later ) of the interval
  \param maxSteps Maximum for the number of steps

  \return Interval classification
 */
QwtDate::IntervalType QwtDateScaleEngine::intervalType( 
    const QDateTime &minDate, const QDateTime &maxDate, 
    int maxSteps ) const
{
    const double jdMin = minDate.date().toJulianDay();
    const double jdMax = maxDate.date().toJulianDay();

    if ( ( jdMax - jdMin ) / 365 > maxSteps )
        return QwtDate::Year;

    const int months = qwtRoundedIntervalWidth( minDate, maxDate, QwtDate::Month );
    if ( months > maxSteps * 6 )
        return QwtDate::Year;

    const int days = qwtRoundedIntervalWidth( minDate, maxDate, QwtDate::Day );
    const int weeks = qwtRoundedIntervalWidth( minDate, maxDate, QwtDate::Week );

    if ( weeks > d_data->maxWeeks )
    {
        if ( days > 4 * maxSteps * 7 )
            return QwtDate::Month;
    }

    if ( days > maxSteps * 7 )
        return QwtDate::Week;

    const int hours = qwtRoundedIntervalWidth( minDate, maxDate, QwtDate::Hour );
    if ( hours > maxSteps * 24 )
        return QwtDate::Day;

    const int seconds = qwtRoundedIntervalWidth( minDate, maxDate, QwtDate::Second );

    if ( seconds >= maxSteps * 3600 )
        return QwtDate::Hour;

    if ( seconds >= maxSteps * 60 )
        return QwtDate::Minute;

    if ( seconds >= maxSteps )
        return QwtDate::Second;

    return QwtDate::Millisecond;
}

/*!
  Align and divide an interval

  The algorithm aligns and divides the interval into steps. 

  Datetime interval divisions are usually not equidistant and the
  calculated stepSize can only be used as an approximation
  for the steps calculated by divideScale(). 

  \param maxNumSteps Max. number of steps
  \param x1 First limit of the interval (In/Out)
  \param x2 Second limit of the interval (In/Out)
  \param stepSize Step size (Out)

  \sa QwtScaleEngine::setAttribute()
*/
void QwtDateScaleEngine::autoScale( int maxNumSteps,
    double &x1, double &x2, double &stepSize ) const
{
    stepSize = 0.0;

    QwtInterval interval( x1, x2 );
    interval = interval.normalized();

    interval.setMinValue( interval.minValue() - lowerMargin() );
    interval.setMaxValue( interval.maxValue() + upperMargin() );

    if ( testAttribute( QwtScaleEngine::Symmetric ) )
        interval = interval.symmetrize( reference() );

    if ( testAttribute( QwtScaleEngine::IncludeReference ) )
        interval = interval.extend( reference() );

    if ( interval.width() == 0.0 )
        interval = buildInterval( interval.minValue() );

    const QDateTime from = toDateTime( interval.minValue() );
    const QDateTime to = toDateTime( interval.maxValue() );

    if ( from.isValid() && to.isValid() )
    {
        if ( maxNumSteps < 1 )
            maxNumSteps = 1;

        const QwtDate::IntervalType intvType = 
            intervalType( from, to, maxNumSteps );

        const double width = qwtIntervalWidth( from, to, intvType );

        const double stepWidth = qwtDivideScale( width, maxNumSteps, intvType );
        if ( stepWidth != 0.0 && !testAttribute( QwtScaleEngine::Floating ) )
        {
            const QDateTime d1 = alignDate( from, stepWidth, intvType, false );
            const QDateTime d2 = alignDate( to, stepWidth, intvType, true );

            interval.setMinValue( QwtDate::toDouble( d1 ) );
            interval.setMaxValue( QwtDate::toDouble( d2 ) );
        }

        stepSize = stepWidth * qwtMsecsForType( intvType );
    }

    x1 = interval.minValue();
    x2 = interval.maxValue();

    if ( testAttribute( QwtScaleEngine::Inverted ) )
    {
        qSwap( x1, x2 );
        stepSize = -stepSize;
    }
}

/*!
   \brief Calculate a scale division for a date/time interval

   \param x1 First interval limit
   \param x2 Second interval limit
   \param maxMajorSteps Maximum for the number of major steps
   \param maxMinorSteps Maximum number of minor steps
   \param stepSize Step size. If stepSize == 0, the scaleEngine
                   calculates one.
   \return Calculated scale division
*/
QwtScaleDiv QwtDateScaleEngine::divideScale( double x1, double x2,
    int maxMajorSteps, int maxMinorSteps, double stepSize ) const
{
    if ( maxMajorSteps < 1 )
        maxMajorSteps = 1;

    const double min = qMin( x1, x2 );
    const double max = qMax( x1, x2 );

    const QDateTime from = toDateTime( min );
    const QDateTime to = toDateTime( max );

    if ( from == to )
        return QwtScaleDiv();

    stepSize = qAbs( stepSize );
    if ( stepSize > 0.0 )
    {
        // as interval types above hours are not equidistant
        // ( even days might have 23/25 hours because of daylight saving )
        // the stepSize is used as a hint only

        maxMajorSteps = qCeil( ( max - min ) / stepSize );
    }

    const QwtDate::IntervalType intvType = 
        intervalType( from, to, maxMajorSteps );

    QwtScaleDiv scaleDiv;

    if ( intvType == QwtDate::Millisecond )
    {
        // for milliseconds and below we can use the decimal system
        scaleDiv = QwtLinearScaleEngine::divideScale( min, max,
            maxMajorSteps, maxMinorSteps, stepSize );
    }
    else
    {
        const QDateTime minDate = QwtDate::floor( from, intvType );
        const QDateTime maxDate = QwtDate::ceil( to, intvType );

        scaleDiv = buildScaleDiv( minDate, maxDate, 
            maxMajorSteps, maxMinorSteps, intvType );

        // scaleDiv has been calculated from an extended interval
        // adjusted to the step size. We have to shrink it again.

        scaleDiv = scaleDiv.bounded( min, max );
    }

    if ( x1 > x2 )
        scaleDiv.invert();

    return scaleDiv;
}

QwtScaleDiv QwtDateScaleEngine::buildScaleDiv( 
    const QDateTime &minDate, const QDateTime &maxDate,
    int maxMajorSteps, int maxMinorSteps,
    QwtDate::IntervalType intervalType ) const
{
    // calculate the step size
    const double stepSize = qwtDivideScale( 
        qwtIntervalWidth( minDate, maxDate, intervalType ), 
        maxMajorSteps, intervalType );

    // align minDate to the step size
    QDateTime dt0 = alignDate( minDate, stepSize, intervalType, false );
    if ( !dt0.isValid() )
    {
        // the floored date is out of the range of a 
        // QDateTime - we ceil instead.
        dt0 = alignDate( minDate, stepSize, intervalType, true );
    }

    QwtScaleDiv scaleDiv;

    if ( intervalType <= QwtDate::Week )
    {
        scaleDiv = qwtDivideToSeconds( dt0, maxDate, 
            stepSize, maxMinorSteps, intervalType );
    }
    else
    {
        if( intervalType == QwtDate::Month )
        {
            scaleDiv = qwtDivideToMonths( dt0, maxDate,
                stepSize, maxMinorSteps );
        }
        else if ( intervalType == QwtDate::Year )
        {
            scaleDiv = qwtDivideToYears( dt0, maxDate,
                stepSize, maxMinorSteps );
        }
    }


    return scaleDiv;
}

/*!
  Align a date/time value for a step size

  For Qt::Day alignments there is no "natural day 0" -
  instead the first day of the year is used to avoid jumping 
  major ticks positions when panning a scale. For other alignments
  ( f.e according to the first day of the month ) alignDate()
  has to be overloaded.

  \param dateTime Date/time value
  \param stepSize Step size
  \param intervalType Interval type
  \param up When true dateTime is ceiled - otherwise it is floored

  \return Aligned date/time value
 */
QDateTime QwtDateScaleEngine::alignDate( 
    const QDateTime &dateTime, double stepSize, 
    QwtDate::IntervalType intervalType, bool up ) const
{
    // what about: (year == 1582 && month == 10 && day > 4 && day < 15) ??

    QDateTime dt = dateTime;

    if ( dateTime.timeSpec() == Qt::OffsetFromUTC )
    {
        dt.setUtcOffset( 0 );
    }

    switch( intervalType )
    {
        case QwtDate::Millisecond:
        {
            const int ms = qwtAlignValue( 
                dt.time().msec(), stepSize, up ) ;

            dt = QwtDate::floor( dateTime, QwtDate::Second );
            dt = dt.addMSecs( ms );

            break;
        }
        case QwtDate::Second:
        {
            int second = dt.time().second();
            if ( up )
            {
                if ( dt.time().msec() > 0 )
                    second++;
            }

            const int s = qwtAlignValue( second, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Minute );
            dt = dt.addSecs( s );

            break;
        }
        case QwtDate::Minute:
        {
            int minute = dt.time().minute();
            if ( up )
            {
                if ( dt.time().msec() > 0 || dt.time().second() > 0 )
                    minute++;
            }

            const int m = qwtAlignValue( minute, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Hour );
            dt = dt.addSecs( m * 60 );

            break;
        }
        case QwtDate::Hour:
        {
            int hour = dt.time().hour();
            if ( up )
            {
                if ( dt.time().msec() > 0 || dt.time().second() > 0
                    || dt.time().minute() > 0 )
                {
                    hour++;
                }
            }
            const int h = qwtAlignValue( hour, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Day );
            dt = dt.addSecs( h * 3600 );

            break;
        }
        case QwtDate::Day:
        {
            // What date do we expect f.e. from an alignment of 5 days ??
            // Aligning them to the beginning of the year avoids at least
            // jumping major ticks when panning

            int day = dt.date().dayOfYear();
            if ( up )
            {
                if ( dt.time() > QTime( 0, 0 ) )
                    day++;
            }

            const int d = qwtAlignValue( day, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Year );
            dt = dt.addDays( d - 1 );

            break;
        }
        case QwtDate::Week:
        {
            const QDate date = QwtDate::dateOfWeek0(
                dt.date().year(), d_data->week0Type );

            int numWeeks = date.daysTo( dt.date() ) / 7;
            if ( up )
            {
                if ( dt.time() > QTime( 0, 0 ) ||
                    date.daysTo( dt.date() ) % 7 )
                {
                    numWeeks++;
                }
            }

            const int d = qwtAlignValue( numWeeks, stepSize, up ) * 7;

            dt = QwtDate::floor( dt, QwtDate::Day );
            dt.setDate( date );
            dt = dt.addDays( d );

            break;
        }
        case QwtDate::Month:
        {
            int month = dt.date().month();
            if ( up )
            {
                if ( dt.date().day() > 1 ||
                    dt.time() > QTime( 0, 0 ) )
                {
                    month++;
                }
            }

            const int m = qwtAlignValue( month - 1, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Year );
            dt = dt.addMonths( m );

            break;
        }
        case QwtDate::Year:
        {
            int year = dateTime.date().year();
            if ( up )
            {
                if ( dateTime.date().dayOfYear() > 1 ||
                    dt.time() > QTime( 0, 0 ) )
                {
                    year++;
                }
            }

            const int y = qwtAlignValue( year, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Day );
            if ( y == 0 )
            {
                // there is no year 0 in the Julian calendar
                dt.setDate( QDate( stepSize, 1, 1 ).addYears( -stepSize ) );
            }
            else
            {
                dt.setDate( QDate( y, 1, 1 ) );
            }

            break;
        }
    }

    if ( dateTime.timeSpec() == Qt::OffsetFromUTC )
    {
        dt.setUtcOffset( dateTime.utcOffset() );
    }

    return dt;
}

/*!
  Translate a double value into a QDateTime object.

  For QDateTime result is bounded by QwtDate::minDate() and QwtDate::maxDate()

  \return QDateTime object initialized with timeSpec() and utcOffset().
  \sa timeSpec(), utcOffset(), QwtDate::toDateTime()
 */
QDateTime QwtDateScaleEngine::toDateTime( double value ) const
{
    QDateTime dt = QwtDate::toDateTime( value, d_data->timeSpec );
    if ( !dt.isValid() )
    {
        const QDate date = ( value <= 0.0 ) 
            ? QwtDate::minDate() : QwtDate::maxDate();

        dt = QDateTime( date, QTime( 0, 0 ), d_data->timeSpec );
    }

    if ( d_data->timeSpec == Qt::OffsetFromUTC )
    {
        dt = dt.addSecs( d_data->utcOffset );
        dt.setUtcOffset( d_data->utcOffset );
    }

    return dt;
}