summaryrefslogtreecommitdiffstats
path: root/kig/misc/coordinate_system.cpp
blob: 859ed81dd600a131f952197c941bda07a1d45f7d (plain)
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
/**
 This file is part of Kig, a KDE program for Interactive Geometry...
 Copyright (C) 2002  Dominique Devriese <devriese@kde.org>

 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.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301
 USA
**/

#include "coordinate_system.h"

#include "../kig/kig_document.h"
#include "../kig/kig_view.h"

#include "common.h"
#include "coordinate.h"
#include "goniometry.h"
#include "kigpainter.h"

#include <tqpainter.h>
#include <tqregexp.h>

#include <kdebug.h>
#include <kglobal.h>
#include <klocale.h>
#include <knumvalidator.h>

#include <string>
#include <math.h>

class CoordinateValidator
  : public QValidator
{
  bool mpolar;
#ifdef KIG_USE_KDOUBLEVALIDATOR
  KDoubleValidator mdv;
#else
  KFloatValidator mdv;
#endif
  mutable TQRegExp mre;
public:
  CoordinateValidator( bool polar );
  ~CoordinateValidator();
  State validate ( TQString & input,  int & pos ) const;
  void fixup ( TQString & input ) const;
};


CoordinateValidator::CoordinateValidator( bool polar )
  : TQValidator( 0, 0 ), mpolar( polar ), mdv( 0, 0 ),
    mre( polar ? "\\(? ?([0-9.,+-]+); ?([0-9.,+-]+) ?°? ?\\)?"
         : "\\(? ?([0-9.,+-]+); ?([0-9.,+-]+) ?\\)?" )
{
}

CoordinateValidator::~CoordinateValidator()
{
}

TQValidator::State CoordinateValidator::validate( TQString & input, int & pos ) const
{
  TQString tinput = input;
  if ( tinput[tinput.length() - 1 ] == ')' ) tinput.truncate( tinput.length() - 1 );
  if ( mpolar )
  {
    if ( tinput[tinput.length() - 1 ] == ' ' ) tinput.truncate( tinput.length() - 1 );
    if ( tinput[tinput.length() - 1 ] == '°' ) tinput.truncate( tinput.length() - 1 );
  };
  if( tinput[tinput.length() - 1 ] == ' ' ) tinput.truncate( tinput.length() - 1 );
  if ( tinput[0] == '(' ) tinput = tinput.mid( 1 );
  if( tinput[0] == ' ' ) tinput = tinput.mid( 1 );
  int scp = tinput.find( ';' );
  if ( scp == -1 ) return mdv.validate( tinput, pos ) == Invalid ? Invalid : Valid;
  else
  {
    TQString p1 = tinput.left( scp );
    TQString p2 = tinput.mid( scp + 1 );

    State ret = Acceptable;

    int boguspos = 0;
    ret = kigMin( ret, mdv.validate( p1, boguspos ) );

    boguspos = 0;
    ret = kigMin( ret, mdv.validate( p2, boguspos ) );

    return ret;
  };
}

void CoordinateValidator::fixup( TQString & input ) const
{
  int nsc = input.contains( ';' );
  if ( nsc > 1 )
  {
    // where is the second ';'
    int i = input.find( ';' );
    i = input.find( ';', i );
    input = input.left( i );
  };
  // now the string has at most one semicolon left..
  int sc = input.find( ';' );
  if ( sc == -1 )
  {
    sc = input.length();
    KLocale* l = KGlobal::locale();
    if ( mpolar )
      input.append( TQString::fromLatin1( ";" ) + l->positiveSign() +
                    TQString::fromLatin1( "0°" ) );
    else
      input.append( TQString::fromLatin1( ";" ) + l->positiveSign() +
                    TQString::fromLatin1( "0" ) + l->decimalSymbol() +
                    TQString::fromLatin1( "0" ) );
  };
  mre.exactMatch( input );
  TQString ds1 = mre.cap( 1 );
  mdv.fixup( ds1 );
  TQString ds2 = mre.cap( 2 );
  mdv.fixup( ds2 );
  input = ds1 + TQString::fromLatin1( "; " ) + ds2;
}

EuclideanCoords::EuclideanCoords()
{
}

TQString EuclideanCoords::fromScreen( const Coordinate& p, const KigDocument& d ) const
{
  // i used to use the widget size here, but that's no good idea,
  // since an object isn't asked to recalc every time the widget size
  // changes..  might be a good idea to do that, but well, maybe some
  // other time :)
  Rect sr = d.suggestedRect();
  double m = kigMax( sr.width(), sr.height() );
  int l = kigMax( 0, (int) ( 3 - log10( m ) ) );
  TQString xs = KGlobal::locale()->formatNumber( p.x, l );
  TQString ys = KGlobal::locale()->formatNumber( p.y, l );
  return TQString::fromLatin1( "( %1; %2 )" ).arg( xs ).arg( ys );
}

Coordinate EuclideanCoords::toScreen(const TQString& s, bool& ok) const
{
  TQRegExp r( "\\(? ?([0-9.,+-]+); ?([0-9.,+-]+) ?\\)?" );
  ok = ( r.search(s) == 0 );
  if (ok)
  {
    TQString xs = r.cap(1);
    TQString ys = r.cap(2);
    KLocale* l = KGlobal::locale();
    double x = l->readNumber( xs, &ok );
    if ( ! ok ) x = xs.toDouble( &ok );
    if ( ! ok ) return Coordinate();
    double y = l->readNumber( ys, &ok );
    if ( ! ok ) y = ys.toDouble( &ok );
    if ( ! ok ) return Coordinate();
    return Coordinate( x, y );
  }
  return Coordinate();
}

/**
 * copied and adapted from a ( public domain ) function i found in the
 * first Graphics Gems book.  Credits to Paul S. Heckbert, who wrote
 * the "Nice number for graph labels" gem.
 * find a "nice" number approximately equal to x.  We look for
 * 1, 2 or 5, multiplied by a power of 10.
 */
static double nicenum( double x, bool round )
{
  int exp = (int) log10( x );
  double f = x/pow( 10., exp );
  double nf;
  if ( round )
  {
    if ( f < 1.5 ) nf = 1.;
    else if ( f < 3. ) nf = 2.;
    else if ( f < 7. ) nf = 5.;
    else nf = 10.;
  }
  else
  {
    if ( f <= 1. ) nf = 1.;
    else if ( f <= 2. ) nf = 2.;
    else if ( f <= 5. ) nf = 5.;
    else nf = 10.;
  };
  return nf * pow( 10., exp );
}

void EuclideanCoords::drawGrid( KigPainter& p, bool showgrid, bool showaxes ) const
{
  p.setWholeWinOverlay();

  // this instruction in not necessary, but there is a little
  // optimization when there are no grid and no axes.
  if ( !( showgrid || showaxes ) )
    return;

  // this function is inspired upon ( public domain ) code from the
  // first Graphics Gems book.  Credits to Paul S. Heckbert, who wrote
  // the "Nice number for graph labels" gem.

  const double hmax = ceil( p.window().right() );
  const double hmin = floor( p.window().left() );
  const double vmax = ceil( p.window().top() );
  const double vmin = floor( p.window().bottom() );

  // the number of intervals we would like to have:
  // we try to have one of them per 40 pixels or so..
  const int ntick = static_cast<int>(
    kigMax( hmax - hmin, vmax - vmin ) / p.pixelWidth() / 40. ) + 1;

  double hrange = nicenum( hmax - hmin, false );
  double vrange = nicenum( vmax - vmin, false );
  const double newrange = kigMin( hrange, vrange );
  hrange = newrange;
  vrange = newrange;

  const double hd = nicenum( hrange / ( ntick - 1 ), true );
  const double vd = nicenum( vrange / ( ntick - 1 ), true );

  const double hgraphmin = ceil( hmin / hd) * hd;
  const double hgraphmax = floor( hmax / hd ) * hd;
  const double vgraphmin = ceil( vmin / vd ) * vd;
  const double vgraphmax = floor( vmax / vd ) * vd;

  const int hnfrac = kigMax( (int) - floor( log10( hd ) ), 0 );
  const int vnfrac = kigMax( (int) - floor( log10( vd ) ), 0 );

  /****** the grid lines ******/
  if ( showgrid )
  {
    p.setPen( TQPen( lightGray, 0, DotLine ) );
    // vertical lines...
    for ( double i = hgraphmin; i <= hgraphmax + hd/2; i += hd )
      p.drawSegment( Coordinate( i, vgraphmin ),
                     Coordinate( i, vgraphmax ) );
    // horizontal lines...
    for ( double i = vgraphmin; i <= vgraphmax + vd/2; i += vd )
      p.drawSegment( Coordinate( hgraphmin, i ),
                     Coordinate( hgraphmax, i ) );
  }

  /****** the axes ******/
  if ( showaxes )
  {
    p.setPen( TQPen( Qt::gray, 1, Qt::SolidLine ) );
    // x axis
    p.drawSegment( Coordinate( hmin, 0 ), Coordinate( hmax, 0 ) );
    // y axis
    p.drawSegment( Coordinate( 0, vmin ), Coordinate( 0, vmax ) );

    /****** the numbers ******/

    // x axis
    for( double i = hgraphmin; i <= hgraphmax + hd / 2; i += hd )
    {
      // we skip 0 since that would look stupid... (the axes going
      // through the 0 etc. )
      if( fabs( i ) < 1e-8 ) continue;

      p.drawText(
        Rect( Coordinate( i, 0 ), hd, -2*vd ).normalized(),
        KGlobal::locale()->formatNumber( i, hnfrac ),
        AlignLeft | AlignTop
        );
    };
    // y axis...
    for ( double i = vgraphmin; i <= vgraphmax + vd/2; i += vd )
    {
      if( fabs( i ) < 1e-8 ) continue;
      p.drawText ( Rect( Coordinate( 0, i ), 2*hd, vd ).normalized(),
                   KGlobal::locale()->formatNumber( i, vnfrac ),
                   AlignBottom | AlignLeft
        );
    };
    // arrows on the ends of the axes...
    p.setPen( TQPen( Qt::gray, 1, Qt::SolidLine ) );
    p.setBrush( TQBrush( Qt::gray ) );
    std::vector<Coordinate> a;

    // the arrow on the right end of the X axis...
    a.reserve( 3 );
    double u = p.pixelWidth();
    a.push_back( Coordinate( hmax - 6 * u, -3 * u) );
    a.push_back( Coordinate( hmax, 0 ) );
    a.push_back( Coordinate( hmax - 6 * u, 3 * u ) );
    p.drawArea( a );
//    p.drawPolygon( a, true );

    // the arrow on the top end of the Y axis...
    a.clear();
    a.reserve( 3 );
    a.push_back( Coordinate( 3 * u, vmax - 6 * u ) );
    a.push_back( Coordinate( 0, vmax ) );
    a.push_back( Coordinate( -3 * u, vmax - 6 * u ) );
    p.drawArea( a );
//    p.drawPolygon( a, true );
  }; // if( showaxes )
}

TQString EuclideanCoords::coordinateFormatNotice() const
{
  return i18n( "Enter coordinates in the following format: \"x;y\",\n"
               "where x is the x coordinate, and y is the y coordinate." );
}

TQString EuclideanCoords::coordinateFormatNoticeMarkup() const
{
  return i18n( "Enter coordinates in the following format: <b>\"x;y\"</b>, "
               "where x is the x coordinate, and y is the y coordinate." );
}

EuclideanCoords::~EuclideanCoords()
{
}

CoordinateSystem::~CoordinateSystem()
{
}

CoordinateSystem::CoordinateSystem()
{
}

PolarCoords::PolarCoords()
{
}

PolarCoords::~PolarCoords()
{
}

TQString PolarCoords::fromScreen( const Coordinate& pt, const KigDocument& d ) const
{
  Rect sr = d.suggestedRect();
  double m = kigMax( sr.width(), sr.height() );
  int l = kigMax( 0, (int) ( 3 - log10( m ) ) );

  double r = pt.length();
  double theta = Goniometry::convert( atan2( pt.y, pt.x ), Goniometry::Rad, Goniometry::Deg );

  TQString rs = KGlobal::locale()->formatNumber( r, l );
  TQString ts = KGlobal::locale()->formatNumber( theta, 0 );

  return TQString::fromLatin1("( %1; %2° )").arg( rs ).arg( ts );
}

TQString PolarCoords::coordinateFormatNotice() const
{
  // \xCE\xB8 is utf8 for the greek theta sign..
  return i18n( "Enter coordinates in the following format: \"r; \xCE\xB8°\",\n"
               "where r and \xCE\xB8 are the polar coordinates." );
}

TQString PolarCoords::coordinateFormatNoticeMarkup() const
{
  // \xCE\xB8 is utf8 for the greek theta sign..
  return i18n( "Enter coordinates in the following format: <b>\"r; \xCE\xB8°\"</b>, "
               "where r and \xCE\xB8 are the polar coordinates." );
}

Coordinate PolarCoords::toScreen(const TQString& s, bool& ok) const
{
  TQRegExp regexp("\\(? ?([0-9.,+-]+); ?([0-9.,+-]+) ?°? ?\\)?" );
  ok = ( regexp.search( s ) == 0 );
  if (ok)
  {
    TQString rs = regexp.cap( 1 );
    double r = KGlobal::locale()->readNumber( rs, &ok );
    if ( ! ok ) r = rs.toDouble( &ok );
    if ( ! ok ) return Coordinate();
    TQString ts = regexp.cap( 2 );
    double theta = KGlobal::locale()->readNumber( ts, &ok );
    if ( ! ok ) theta = ts.toDouble( &ok );
    if ( ! ok ) return Coordinate();
    theta *= M_PI;
    theta /= 180;
    return Coordinate( cos( theta ) * r, sin( theta ) * r );
  }
  else return Coordinate();
}

void PolarCoords::drawGrid( KigPainter& p, bool showgrid, bool showaxes ) const
{
  p.setWholeWinOverlay();

  // this instruction in not necessary, but there is a little
  // optimization when there are no grid and no axes.
  if ( !( showgrid || showaxes ) )
    return;

  // we multiply by sqrt( 2 ) cause we don't want to miss circles in
  // the corners, that intersect with the axes outside of the
  // screen..

  const double hmax = M_SQRT2*p.window().right();
  const double hmin = M_SQRT2*p.window().left();
  const double vmax = M_SQRT2*p.window().top();
  const double vmin = M_SQRT2*p.window().bottom();

  // the intervals:
  // we try to have one of them per 40 pixels or so..
  const int ntick = static_cast<int>(
    kigMax( hmax - hmin, vmax - vmin ) / p.pixelWidth() / 40 ) + 1;

  const double hrange = nicenum( hmax - hmin, false );
  const double vrange = nicenum( vmax - vmin, false );

  const double hd = nicenum( hrange / ( ntick - 1 ), true );
  const double vd = nicenum( vrange / ( ntick - 1 ), true );

  const double hgraphmin = floor( hmin / hd) * hd;
  const double hgraphmax = ceil( hmax / hd ) * hd;
  const double vgraphmin = floor( vmin / vd ) * vd;
  const double vgraphmax = ceil( vmax / vd ) * vd;

  const int hnfrac = kigMax( (int) - floor( log10( hd ) ), 0 );
  const int vnfrac = kigMax( (int) - floor( log10( vd ) ), 0 );
  const int nfrac = kigMax( hnfrac, vnfrac );

  /****** the grid lines ******/
  if ( showgrid )
  {
    double d = kigMin( hd, vd );
    double begin = kigMin( kigAbs( hgraphmin ), kigAbs( vgraphmin ) );
    if ( kigSgn( hgraphmin ) != kigSgn( hgraphmax ) && kigSgn( vgraphmin ) != kigSgn( vgraphmax ) )
      begin = d;
    double end = kigMax( hgraphmax, vgraphmax );

    // we also want the circles that don't fit entirely in the
    // screen..
    Coordinate c( 0, 0 );
    p.setPen( TQPen( lightGray, 0, DotLine ) );
    for ( double i = begin; i <= end + d / 2; i += d )
      drawGridLine( p, c, fabs( i ) );
  }

  /****** the axes ******/
  if ( showaxes )
  {
    p.setPen( TQPen( Qt::gray, 1, Qt::SolidLine ) );
    // x axis
    p.drawSegment( Coordinate( hmin, 0 ), Coordinate( hmax, 0 ) );
    // y axis
    p.drawSegment( Coordinate( 0, vmin ), Coordinate( 0, vmax ) );

    /****** the numbers ******/

    // x axis
    for( double i = hgraphmin; i <= hgraphmax + hd / 2; i += hd )
    {
      // we skip 0 since that would look stupid... (the axes going
      // through the 0 etc. )
      if( fabs( i ) < 1e-8 ) continue;

      TQString is = KGlobal::locale()->formatNumber( fabs( i ), nfrac );
      p.drawText(
        Rect( Coordinate( i, 0 ), hd, -2*vd ).normalized(),
        is, AlignLeft | AlignTop );
    };
    // y axis...
    for ( double i = vgraphmin; i <= vgraphmax + vd / 2; i += vd )
    {
      if( fabs( i ) < 1e-8 ) continue;

      TQString is = KGlobal::locale()->formatNumber( fabs( i ), nfrac );

      p.drawText ( Rect( Coordinate( 0, i ), hd, vd ).normalized(),
                   is, AlignBottom | AlignLeft
        );
    };
    // arrows on the ends of the axes...
    p.setPen( TQPen( Qt::gray, 1, Qt::SolidLine ) );
    p.setBrush( TQBrush( Qt::gray ) );
    std::vector<Coordinate> a;

    // the arrow on the right end of the X axis...
    a.reserve( 3 );
    double u = p.pixelWidth();
    a.push_back( Coordinate( hmax - 6 * u, -3 * u) );
    a.push_back( Coordinate( hmax, 0 ) );
    a.push_back( Coordinate( hmax - 6 * u, 3 * u ) );
//    p.drawPolygon( a, true );
    p.drawArea( a );

    // the arrow on the top end of the Y axis...
    a.clear();
    a.reserve( 3 );
    a.push_back( Coordinate( 3 * u, vmax - 6 * u ) );
    a.push_back( Coordinate( 0, vmax ) );
    a.push_back( Coordinate( -3 * u, vmax - 6 * u ) );
//    p.drawPolygon( a, true );
    p.drawArea( a );
  }; // if( showaxes )
}

TQValidator* EuclideanCoords::coordinateValidator() const
{
  return new CoordinateValidator( false );
}

TQValidator* PolarCoords::coordinateValidator() const
{
  return new CoordinateValidator( true );
}

TQStringList CoordinateSystemFactory::names()
{
  TQStringList ret;
  ret << i18n( "&Euclidean" )
      << i18n( "&Polar" );
  return ret;
}

CoordinateSystem* CoordinateSystemFactory::build( int which )
{
  if ( which == Euclidean )
    return new EuclideanCoords;
  else if ( which == Polar )
    return new PolarCoords;
  else return 0;
}

static const char euclideanTypeString[] = "Euclidean";
static const char polarTypeString[] = "Polar";

CoordinateSystem* CoordinateSystemFactory::build( const char* type )
{
  if ( std::string( euclideanTypeString ) == type )
    return new EuclideanCoords;
  if ( std::string( polarTypeString ) == type )
    return new PolarCoords;
  else return 0;
}

const char* EuclideanCoords::type() const
{
  return euclideanTypeString;
}

const char* PolarCoords::type() const
{
  return polarTypeString;
}

int EuclideanCoords::id() const
{
  return CoordinateSystemFactory::Euclidean;
}

int PolarCoords::id() const
{
  return CoordinateSystemFactory::Polar;
}

TQString CoordinateSystemFactory::setCoordinateSystemStatement( int id )
{
  switch( id )
  {
  case Euclidean:
    return i18n( "Set Euclidean Coordinate System" );
  case Polar:
    return i18n( "Set Polar Coordinate System" );
  default:
    assert( false );
    return TQString::null;
  }
}

Coordinate EuclideanCoords::snapToGrid( const Coordinate& c,
                                        const KigWidget& w ) const
{
  Rect rect = w.showingRect();
  // we recalc the interval stuff since there is no way to cache it..

  // this function is again inspired upon ( public domain ) code from
  // the first Graphics Gems book.  Credits to Paul S. Heckbert, who
  // wrote the "Nice number for graph labels" gem.

  const double hmax = rect.right();
  const double hmin = rect.left();
  const double vmax = rect.top();
  const double vmin = rect.bottom();

  // the number of intervals we would like to have:
  // we try to have one of them per 40 pixels or so..
  const int ntick = static_cast<int>(
    kigMax( hmax - hmin, vmax - vmin ) / w.pixelWidth() / 40. ) + 1;

  const double hrange = nicenum( hmax - hmin, false );
  const double vrange = nicenum( vmax - vmin, false );

  const double hd = nicenum( hrange / ( ntick - 1 ), true );
  const double vd = nicenum( vrange / ( ntick - 1 ), true );

  const double hgraphmin = ceil( hmin / hd) * hd;
  const double vgraphmin = ceil( vmin / vd ) * vd;

  const double nx = qRound( ( c.x - hgraphmin ) / hd ) * hd + hgraphmin;
  const double ny = qRound( ( c.y - vgraphmin ) / vd ) * vd + vgraphmin;
  return Coordinate( nx, ny );
}

Coordinate PolarCoords::snapToGrid( const Coordinate& c,
                                    const KigWidget& w ) const
{
  // we reuse the drawGrid code to find

  // we multiply by sqrt( 2 ) cause we don't want to miss circles in
  // the corners, that intersect with the axes outside of the
  // screen..

  Rect r = w.showingRect();

  const double hmax = M_SQRT2 * r.right();
  const double hmin = M_SQRT2 * r.left();
  const double vmax = M_SQRT2 * r.top();
  const double vmin = M_SQRT2 * r.bottom();

  // the intervals:
  // we try to have one of them per 40 pixels or so..
  const int ntick = static_cast<int>(
    kigMax( hmax - hmin, vmax - vmin ) / w.pixelWidth() / 40 ) + 1;

  const double hrange = nicenum( hmax - hmin, false );
  const double vrange = nicenum( vmax - vmin, false );

  const double hd = nicenum( hrange / ( ntick - 1 ), true );
  const double vd = nicenum( vrange / ( ntick - 1 ), true );

  double d = kigMin( hd, vd );

  double dist = c.length();
  double ndist = qRound( dist / d ) * d;
  return c.normalize( ndist );
}

void PolarCoords::drawGridLine( KigPainter& p, const Coordinate& c,
                                double r ) const
{
  Rect rect = p.window();

  struct iterdata_t
  {
    int xd;
    int yd;
    Coordinate ( Rect::*point )() const;
    Coordinate ( Rect::*oppositepoint )() const;
    double horizAngle;
    double vertAngle;
  };

  static const iterdata_t iterdata[] =
    {
      { +1, +1, &Rect::topRight, &Rect::bottomLeft, 0, M_PI/2 },
      { -1, +1, &Rect::topLeft, &Rect::bottomRight, M_PI, M_PI / 2 },
      { -1, -1, &Rect::bottomLeft, &Rect::topRight, M_PI, 3*M_PI/2 },
      { +1, -1, &Rect::bottomRight, &Rect::topLeft, 2*M_PI, 3*M_PI/2 }
    };
  for ( int i = 0; i < 4; ++i )
  {
    int xd = iterdata[i].xd;
    int yd = iterdata[i].yd;
    Coordinate point = ( rect.*iterdata[i].point )();
    Coordinate opppoint = ( rect.*iterdata[i].oppositepoint )();
    double horizangle = iterdata[i].horizAngle;
    double vertangle = iterdata[i].vertAngle;

    if ( ( c.x - point.x )*xd > 0 || ( c.y - point.y )*yd > 0 )
      continue;
    if ( ( c.x - opppoint.x )*-xd > r || ( c.y - opppoint.y )*-yd > r )
      continue;

    int posdir = xd*yd;
    double hd = ( point.x - c.x )*xd;
    assert( hd >= 0 );
    if ( hd < r )
    {
      double anglediff = acos( hd/r );
      horizangle += posdir * anglediff;
    }

    hd = ( c.x - opppoint.x )*-xd;
    if ( hd >= 0 )
    {
      double anglediff = asin( hd/r );
      vertangle -= posdir * anglediff;
    }

    double vd = ( point.y - c.y )*yd;
    assert( vd >= 0 );
    if ( vd < r )
    {
      double anglediff = acos( vd/r );
      vertangle -= posdir * anglediff;
    }

    vd = ( c.y - opppoint.y ) * -xd;
    if ( vd >= 0 )
    {
      double anglediff = asin( hd/r );
      horizangle += posdir * anglediff;
    }

    p.drawArc( c, r, kigMin( horizangle, vertangle ), kigMax( horizangle, vertangle ) );
  }
//  p.drawCircle( c, r );
}