summaryrefslogtreecommitdiffstats
path: root/kodo/kodometer.cpp
blob: 22a946d5676ad42f9d3804a9ae7c40dc6f074bfd (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
/*
 * Mouspedometa
 *      Based on the original Xodometer VMS/Motif sources.
 *
 * Written by Armen Nakashian
 *            Compaq Computer Corporation
 *            Houston TX
 *            22 May 1998
 *
 * If you make improvements or enhancements to Mouspedometa, please send
 * them back to the author at any of the following addresses:
 *
 *              armen@nakashian.com
 *
 * Thanks to Mark Granoff for writing the original Xodometer, and
 * the whole KDE team for making such a nice environment to write
 * programs in.
 *
 *
 * This software is provided as is with no warranty of any kind,
 * expressed or implied. Neither Digital Equipment Corporation nor
 * Armen Nakashian will be held accountable for your use of this
 * software.
 */

#include "kodometer.h"

const double speedInterval = 500.0;
const double distanceInterval = 10.0;
const int speedSamples = 10;

static	struct conversionEntry ConversionTable[MAX_UNIT] = {
	{inch, I18N_NOOP("inch"), I18N_NOOP("inches"), 12.0,  2.54,
	       I18N_NOOP("cm"),   I18N_NOOP("cm"),     100.0, 3},
	{foot, I18N_NOOP("foot"),  I18N_NOOP("feet"),   5280.0, 0.3048,
	       I18N_NOOP("meter"), I18N_NOOP("meters"), 1000.0, 4},
	{mile, I18N_NOOP("mile"), I18N_NOOP("miles"), -1.0, 1.609344,
	       I18N_NOOP("km"),   I18N_NOOP("km"),    -1.0, 5}};

/*
 * Set the program up, do lots of ugly initialization.
 * Note that we use installEventFilter on the two KImageNumber's
 * to make clicks on them bring up the context-menu.
 */
Kodometer::Kodometer(TQWidget* tqparent, const char* name)
	: TQFrame(tqparent, name),
	dontRefresh(false),
        speed(0.0),
	lastDistance(0.0),
	XCoord(0), YCoord(0),
	lastXCoord(0), lastYCoord(0),
        pointerScreen(-1),
	lastPointerScreen(-1),
	Enabled(true),
	cyclesSinceLastSave(0),
	pollInterval(10),
	saveFrequency(10)
{
	display = KApplication::kApplication()->getDisplay();
	FindAllScreens();

	root = RootWindow(display, DefaultScreen(display));

	readSettings();
	if(AutoReset) {
		dontRefresh = true;
		resetTrip();
		dontRefresh = false;
	}

	lastDistance = Distance;

	lastDUnit = distanceUnit;
	lastTUnit = tripDistanceUnit;

	totalLabel = new KImageNumber(locate("appdata", "numbers.png"), this);
	tripLabel  = new KImageNumber(locate("appdata", "numbers.png"), this);

	totalLabel->installEventFilter(this);
	tripLabel->installEventFilter(this);

	// setup help menu
	help = new KHelpMenu(this, KGlobal::instance()->aboutData(), false);
	KPopupMenu* helpMnu = help->menu();

	// Make the popup menu
	menu = new KPopupMenu();

	menu->insertTitle(kapp->miniIcon(), KGlobal::instance()->aboutData()->programName());

	enabledID = menu->insertItem(i18n("&Enable"), this, TQT_SLOT(toggleEnabled()));
	metricID = menu->insertItem(i18n("&Metric Display"), this,
		TQT_SLOT(toggleUnits()));
	autoResetID = menu->insertItem(i18n("Auto &Reset Trip"), this,
		TQT_SLOT(toggleAutoReset()));
	menu->insertItem(i18n("Reset &Trip"), this, TQT_SLOT(resetTrip()));
	menu->insertItem(i18n("Reset &Odometer"), this, TQT_SLOT(resetTotal()));
	menu->insertSeparator();

	menu->insertItem(SmallIconSet("help"), i18n("&Help"), helpMnu);

	menu->insertItem(SmallIconSet("exit"), i18n("&Quit"), this, TQT_SLOT(quit()));
	menu->setCheckable(true);

	menu->setItemChecked(enabledID, Enabled);
	menu->setItemChecked(metricID, UseMetric);
	menu->setItemChecked(autoResetID, AutoReset);

	//start the timers that will rifresh the counter
	distanceID = startTimer((int)distanceInterval);
	speedID = startTimer((int)speedInterval);

	tripLabel->move(0, totalLabel->height());
	setFixedSize(tripLabel->width(),
		totalLabel->height() + tripLabel->height());

	UseMetric =! UseMetric;
	toggleUnits();

	refresh();
}

/*
 * Now I'm not really sure what this does.  I assume its here to tqfind
 * all the displays on your system, and measure them.  During the mouse
 * tracking phase, we use the information stored here to determine how
 * far the mouse moved on a given screen.
 *
 * The point is, since you might have one 17" screen and on 21" screen,
 * lets measure them differently.  Surely this level of accurasy is
 * only provide to prove that the original author was a man's man.
 */
void Kodometer::FindAllScreens(void)
{
	int Dh, DhMM, Dw, DwMM;
	double vPixelsPerMM, hPixelsPerMM;

	screenCount = ScreenCount(display);
//	kdDebug() << "Display has " <<  screenCount <<
//		" screen" << (screenCount == 1 ? "" : "s") << endl;

	for(int i = 0; i < screenCount; i++) {
//		kdDebug() << "Screen " << i << endl;
		screenInfo[i].root = RootWindow(display, i);
		screenInfo[i].scr = XScreenOfDisplay(display, i);

		screenInfo[i].height = Dh = HeightOfScreen(screenInfo[i].scr);
		DhMM = HeightMMOfScreen(screenInfo[i].scr);
		screenInfo[i].width = Dw = WidthOfScreen(screenInfo[i].scr);
		DwMM = WidthMMOfScreen(screenInfo[i].scr);
//		kdDebug() << "    Height is " << Dh << " pixels (" << DhMM <<
//			"mm)" << endl;
//		kdDebug() << "    Width is " << Dw << " pixels (" << DwMM <<
//			"mm)" << endl;

		vPixelsPerMM = (double)Dh / (double)DhMM;
		hPixelsPerMM = (double)Dw / (double)DwMM;
		screenInfo[i].PixelsPerMM = (vPixelsPerMM + hPixelsPerMM) / 2.0;
//		kdDebug() << "   Qt::Vertical pixels/mm  are " << vPixelsPerMM <<
//			"mm" << endl;
//		kdDebug() << "   Qt::Horizontal pixels/mm are " << hPixelsPerMM <<
//			"mm" << endl;
//		kdDebug() << "    Average pixels/mm are " <<
//			screenInfo[i].PixelsPerMM << "mm" << endl;
	}
}

/*
 * Here's where we override events to the KImgNum's to display
 * the context menu
 */
bool Kodometer::eventFilter( TQObject *, TQEvent *e )
{
	if ( e->type() == TQEvent::MouseButtonPress ) {
		mousePressEvent((TQMouseEvent*)e);
		return true;
	}
	return false;
}

/*
 * Show the context menu
 */
void Kodometer::mousePressEvent(TQMouseEvent* e)
{
	//FIXME fix this!
	//dontRefresh = true;
	menu->popup(mapToGlobal(e->pos()));
}

/*
 * Called when the timer expires to query the pointer position,
 * compare it to the last known position, and then to calculate
 * the distance moved.
 */
void Kodometer::timerEvent(TQTimerEvent* e)
{
	if (Enabled) {
		if(e->timerId() == distanceID) {
			lastPointerScreen = pointerScreen;
			lastXCoord = XCoord;
			lastYCoord = YCoord;
			XQueryPointer (display, root, &RootIDRet, &ChildIDRet, &XCoord,
				&YCoord, &WinX, &WinY, &StateMask);
			if (CalcDistance()) {
//				kdDebug() << "Mouse moved" << endl;
				if (!dontRefresh) {
					refresh();
					cyclesSinceLastSave++;
				}
			}
		}
	}
}

// Guess!
void Kodometer::toggleEnabled()
{
	Enabled = !Enabled;
	menu->setItemChecked(enabledID,Enabled);
	refresh();
}

// Try again!
void Kodometer::toggleAutoReset()
{
	AutoReset = !AutoReset;
	menu->setItemChecked(autoResetID,AutoReset);
	refresh();
}


// You're getting warm!
void Kodometer::toggleUnits()
{
	UseMetric =! UseMetric;

	menu->setItemChecked(metricID, UseMetric);

	TQToolTip::remove(totalLabel);
	TQToolTip::remove(tripLabel);
	if(!UseMetric) {
		TQToolTip::add(totalLabel,
			i18n(ConversionTable[distanceUnit].fromUnitTagPlural));
		TQToolTip::add(tripLabel,
			i18n(ConversionTable[tripDistanceUnit].fromUnitTagPlural));
	} else {
		TQToolTip::add(totalLabel,
			i18n(ConversionTable[distanceUnit].toUnitTagPlural));
		TQToolTip::add(tripLabel,
			i18n(ConversionTable[tripDistanceUnit].toUnitTagPlural));
	}
	refresh();
}


// Were you dropped on your head as a child?
void Kodometer::resetTrip()
{
	TripDistance = 0.0;
	tripDistanceUnit = inch;
	if (!dontRefresh)
		refresh();
}

// I was!
void Kodometer::resetTotal()
{
	resetTrip();

	Distance = 0.0;
	distanceUnit = inch;

	TripDistance = 0.0;
	tripDistanceUnit = inch;
	refresh();
}

/*
 * Set the values in all the KImgNums, do metric conversions,
 * and make the screen look like reality.
 */
void Kodometer::refresh(void)
{
	if(distanceUnit != lastDUnit) {
		lastDUnit = distanceUnit;
		TQToolTip::remove(totalLabel);
		if(!UseMetric)
			TQToolTip::add(totalLabel,
				i18n(ConversionTable[distanceUnit].fromUnitTagPlural));
		else
			TQToolTip::add(totalLabel,
				i18n(ConversionTable[distanceUnit].toUnitTagPlural));
	}

	if(tripDistanceUnit != lastTUnit) {
		lastTUnit = tripDistanceUnit;
		TQToolTip::remove(tripLabel);
		if(!UseMetric)
			TQToolTip::add(tripLabel,
				i18n(ConversionTable[tripDistanceUnit].fromUnitTagPlural));
		else
			TQToolTip::add(tripLabel,
				i18n(ConversionTable[tripDistanceUnit].toUnitTagPlural));
	}

	//now draw everything
	TQString distance_s;
	TQString trip_s;
        double distance_d = 0;
        double trip_d = 0;

	if (Enabled) {
            distance_d = Distance;
            distance_s = FormatDistance(distance_d, distanceUnit);
            trip_d = TripDistance;
            trip_s = FormatDistance(trip_d, tripDistanceUnit);
	} else {
            distance_s = "------";
            trip_s = "------";
	}

	totalLabel->setValue(distance_d);
	tripLabel->setValue(trip_d);
}

/*
 * Not sure what this does, its from the original program.
 */
double Kodometer::multiplier(Units unit)
{
	double m = 10;

	switch (unit) {
		case mile : m *= 10.0;
		case foot : m *= 10.0;
		case inch : m *= 10.0; break;
	}
	return m;
}

/*
 * This is the bitch function where the _real_ work is done.  I
 * could have re-invented the query_pointer code, but this one is a best.
 *
 * This is code from the original program, responsible for converting the
 * number of pixels traveled into  a real-world coordinates.
 */
int Kodometer::CalcDistance(void)
{
	double dist, sum;
	int X, Y;
	double distMM, distInches, finalNewDist;
	double oldDistance, oldTripDistance;
	double newDistance, newTripDistance;
	int i, j, finalScreen, increment;
	Units oldDistanceUnit, oldTripDistanceUnit, currentUnit;
	int distanceChanged, tripDistanceChanged;

	int screenOrientation = K_Left;

	i = j = finalScreen = increment = 0;

	if ((lastXCoord == 0) && (lastYCoord == 0))
		return false;

	if ((lastXCoord == XCoord) && (lastYCoord == YCoord))
		return false;

	//Figure out which screen the pointer is on
	if (screenCount > 1) {
		while (i < screenCount)
			if (RootIDRet == screenInfo[i].root)
				break;
			else
				i++;
	}

	pointerScreen = i;

//	kdDebug() << "CalcDistance: screen: " << pointerScreen <<
//		 " x: " << XCoord << " y: " << YCoord << endl;

	// Adjust XCoord or YCoord for the screen its on, relative to screen 0
	// and screenOrientation.

	if (lastPointerScreen != -1 && pointerScreen != lastPointerScreen) {
		switch (screenOrientation) {
			case K_Left:
			case K_Top:
				finalScreen = 0;
				j = TQMAX(pointerScreen,lastPointerScreen) - 1;
				increment = -1;
				break;
			case K_Right:
			case K_Bottom:
				finalScreen = TQMAX(pointerScreen,lastPointerScreen) - 1;
				j = 0;
				increment = 1;
				break;
		}
		do {
			switch (screenOrientation) {
				case K_Left:
				case K_Right:
					if (pointerScreen > lastPointerScreen)
						XCoord += screenInfo[j].width;
					else
						lastXCoord += screenInfo[j].width;
					break;
				case K_Top:
				case K_Bottom:
					if (pointerScreen > lastPointerScreen)
						YCoord += screenInfo[j].height;
					else
						lastYCoord += screenInfo[j].height;
					break;
			}
			if (j != finalScreen)
				j += increment;
		} while (j != finalScreen);
//		kdDebug() << "    Adjusted for screen ch: x: " << XCoord <<
//			" y: " << YCoord << endl;
	}

//	kdDebug() << "In: Distance: " << Distance <<
//		" Trip Distance: " << TripDistance << endl;

	// Calculate distance in pixels first
	// using Pitagora

	X = XCoord - lastXCoord;
	X = X*X;

	Y = YCoord - lastYCoord;
	Y = Y*Y;

	sum = (double)X + (double)Y;
	dist = sqrt(sum);

	// Convert to millimeters
	distMM = dist / screenInfo[pointerScreen].PixelsPerMM;

	// Convert to inches
	distInches = distMM * 0.04;

	// Add an appropriate value to Distance, which may be
	// in a unit other than inches
	currentUnit = inch;
	finalNewDist = distInches;

	while (currentUnit < distanceUnit) {
		finalNewDist =
			finalNewDist / ConversionTable[currentUnit].maxFromBeforeNext;
		currentUnit++;
//		kdDebug() << "    New dist: " << dist << "p, " << distMM << "mm, " <<
//			distInches << "in, " << finalNewDist << " " <<
//			ConversionTable[currentUnit+1].fromUnitTagPlural << endl;
	}

//	kdDebug() << " Next part" << endl;

	oldDistance = Distance * multiplier(distanceUnit);

	Distance += finalNewDist;
	oldDistanceUnit = distanceUnit;

	if (ConversionTable[distanceUnit].maxFromBeforeNext != -1.0 &&
		Distance >= ConversionTable[distanceUnit].maxFromBeforeNext)
	{
		Distance = Distance / ConversionTable[distanceUnit].maxFromBeforeNext;
		distanceUnit++;
	}

	newDistance = Distance * multiplier(distanceUnit);
	distanceChanged = (distanceUnit != oldDistanceUnit ||
		(unsigned int)oldDistance != (unsigned int)newDistance);

	// Add an appropriate value to TripDistance, which may be
	// in a unit other than inches
	currentUnit = inch;
	finalNewDist = distInches;

	while (currentUnit < tripDistanceUnit) {
		finalNewDist = finalNewDist /
			ConversionTable[currentUnit].maxFromBeforeNext;
		currentUnit++;
	}

	oldTripDistance = TripDistance * multiplier(tripDistanceUnit);
	TripDistance += finalNewDist;
	oldTripDistanceUnit = tripDistanceUnit;

	if (ConversionTable[tripDistanceUnit].maxFromBeforeNext != -1.0 &&
		TripDistance >= ConversionTable[tripDistanceUnit].maxFromBeforeNext)
	{
		TripDistance = TripDistance /
			ConversionTable[tripDistanceUnit].maxFromBeforeNext;
		tripDistanceUnit++;
	}

	newTripDistance = TripDistance * multiplier(tripDistanceUnit);
	tripDistanceChanged = ((tripDistanceUnit != oldTripDistanceUnit) ||
		((unsigned int)oldTripDistance != (unsigned int)newTripDistance));


//	kdDebug() << "Out: Distance: " << Distance <<
//		"Trip Distance: " << TripDistance << endl;

	if ((distanceChanged) || (tripDistanceChanged))
		return true;
	else
		return false;
}

/*
 * This code can probably go away.  Its doing conversions from inches to
 * other units.  Its ugly C-style stuff, that  should't be done in a
 * pretty OO world.
 */
#define THERE_IS_A_NEXT (ConversionTable[unit].maxToBeforeNext != -1.0)
TQString Kodometer::FormatDistance(double &dist, Units unit)
{
    TQString string;
    const char *tag;
    int precision;

    if (UseMetric) {
        dist = dist * ConversionTable[unit].conversionFactor;
        if ((THERE_IS_A_NEXT) &&
            (dist > ConversionTable[unit].maxToBeforeNext))
        {
            dist = dist / ConversionTable[unit].maxToBeforeNext;
            unit++;
        }
        if (dist == 1.0)
            tag = ConversionTable[unit].toUnitTag;
        else
            tag = ConversionTable[unit].toUnitTagPlural;
	} else {
            if (dist == 1.0)
                tag = ConversionTable[unit].fromUnitTag;
            else
                tag = ConversionTable[unit].fromUnitTagPlural;
	}
	precision = ConversionTable[unit].printPrecision;

	string.sprintf ("%.*f %s", precision, dist, tag);
	return string;
}

/*
 * Use KConfig to read all settings from disk.  Note that whatever
 * happens here overrides the defaults, but there's not much
 * sanity-checking.
 */
void Kodometer::readSettings(void)
{
	KConfig* config = KGlobal::config();
	config->setGroup("Settings");

	UseMetric = config->readNumEntry("UseMetric", false);
	AutoReset = config->readNumEntry("AutoReset", true);

	TripDistance = config->readDoubleNumEntry("Trip", 0.0);
	Distance = config->readDoubleNumEntry("Distance", 0.0);

	distanceUnit = config->readNumEntry("DistanceUnit", inch);
	tripDistanceUnit = config->readNumEntry("TripUnit", inch);
}


/*
 * Save reality for use in the next session.
 */
void Kodometer::saveSettings(void)
{
	KConfig* config = KGlobal::config();
	config->setGroup("Settings");

	config->writeEntry("UseMetric", UseMetric);
	config->writeEntry("AutoReset", AutoReset);

	config->writeEntry("Trip", TripDistance);
	config->writeEntry("Distance", Distance);

	config->writeEntry("TripUnit", tripDistanceUnit);
	config->writeEntry("DistanceUnit", distanceUnit);

	config->sync();
}

// What in the world can this do?
void Kodometer::quit()
{
	saveSettings();
	kapp->quit();
}

#include "kodometer.moc"