summaryrefslogtreecommitdiffstats
path: root/src/gui/oscilloscopeview.cpp
blob: 8641c27c89d966215038dbe663f3db48715de1e1 (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
/***************************************************************************
 *   Copyright (C) 2005 by David Saxton                                    *
 *   david@bluehaze.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.                                   *
 ***************************************************************************/

#include "oscilloscope.h"
#include "oscilloscopedata.h"
#include "oscilloscopeview.h"
#include "probepositioner.h"
#include "simulator.h"

#include <tdeconfig.h>
#include <kdebug.h>
#include <tdelocale.h>
#include <tdeglobal.h>
#include <tdepopupmenu.h>
#include <tqcheckbox.h>
#include <tqcursor.h>
#include <tqevent.h>
#include <tqlabel.h>
#include <tqpainter.h>
#include <tqpixmap.h>
#include <tqscrollbar.h>
#include <tqtimer.h>

#include <algorithm>
#include <cmath>

inline ullong min( ullong a, ullong b )
{
	return a < b ? a : b;
}


OscilloscopeView::OscilloscopeView( TQWidget *parent, const char *name )
	: TQFrame( parent, name, WNoAutoErase ),
	b_needRedraw(true),
	m_pixmap(0l),
	m_fps(10),
	m_sliderValueAtClick(-1),
	m_clickOffsetPos(-1),
	m_pSimulator( Simulator::self() ),
	m_halfOutputHeight(0.0)
{
	TDEGlobal::config()->setGroup("Oscilloscope");
	m_fps = TDEGlobal::config()->readNumEntry( "FPS", 25 );
	
	setBackgroundMode(NoBackground);
	setMouseTracking(true);
	
	m_updateViewTmr = new TQTimer(this);
	connect( m_updateViewTmr, TQT_SIGNAL(timeout()), this, TQT_SLOT(updateViewTimeout()) );
}


OscilloscopeView::~OscilloscopeView()
{
	delete m_pixmap;
	m_pixmap = 0l;
}


void OscilloscopeView::updateView()
{
	if (m_updateViewTmr->isActive() )
		return;
	
	m_updateViewTmr->start( 1000/m_fps, true );
}


void OscilloscopeView::updateViewTimeout()
{
	b_needRedraw = true;
	repaint(false);
	updateTimeLabel();
}


void OscilloscopeView::updateTimeLabel()
{
	if ( hasMouse() )
	{
		int x = mapFromGlobal( TQCursor::pos() ).x();
		double time = (double(Oscilloscope::self()->scrollTime()) / LOGIC_UPDATE_RATE) + (x / Oscilloscope::self()->pixelsPerSecond());
		Oscilloscope::self()->timeLabel->setText( TQString::number( time, 'f', 6 ) );
	}
	
	else
		Oscilloscope::self()->timeLabel->setText( TQString() );
}


void OscilloscopeView::resizeEvent( TQResizeEvent *e )
{
	delete m_pixmap;
	m_pixmap = new TQPixmap( e->size() );
	b_needRedraw = true;
	TQFrame::resizeEvent(e);
}


void OscilloscopeView::mousePressEvent( TQMouseEvent *event )
{
	switch ( event->button() )
	{
		case TQt::LeftButton:
		{
			event->accept();
			m_clickOffsetPos = event->pos().x();
			m_sliderValueAtClick = Oscilloscope::self()->horizontalScroll->value();
			setCursor( TQt::SizeAllCursor );
			return;
		}
		
		case TQt::RightButton:
		{
			event->accept();
	
			TDEPopupMenu fpsMenu;
			fpsMenu.insertTitle( i18n("Framerate") );
	
			const int fps[] = { 10, 25, 50, 75, 100 };
	
			for ( uint i=0; i<5; ++i )
			{
				const int num = fps[i];
				fpsMenu.insertItem( i18n("%1 fps").arg(num), num );
				fpsMenu.setItemChecked( num, num == m_fps );
			}
	
			connect( &fpsMenu, TQT_SIGNAL(activated(int )), this, TQT_SLOT(slotSetFrameRate(int )) );
			fpsMenu.exec( event->globalPos() );
			return;
		}
		
		default:
		{
			TQFrame::mousePressEvent(event);
			return;
		}
	}
}


void OscilloscopeView::mouseMoveEvent( TQMouseEvent *event )
{
	event->accept();
	updateTimeLabel();
	
	if ( m_sliderValueAtClick != -1 )
	{
		int dx = event->pos().x() - m_clickOffsetPos;
		int dTick = int( dx * Oscilloscope::self()->sliderTicksPerSecond() / Oscilloscope::self()->pixelsPerSecond() );
		Oscilloscope::self()->horizontalScroll->setValue( m_sliderValueAtClick - dTick );
	}
}


void OscilloscopeView::mouseReleaseEvent( TQMouseEvent *event )
{
	if ( m_sliderValueAtClick == -1 )
		return TQFrame::mouseReleaseEvent(event);
	
	event->accept();
	m_sliderValueAtClick = -1;
	setCursor( TQt::ArrowCursor );
}


void OscilloscopeView::slotSetFrameRate( int fps )
{
	m_fps = fps;
	TDEGlobal::config()->setGroup("Oscilloscope");
	TDEGlobal::config()->writeEntry( "FPS", m_fps );
}


// returns a % b
static double lld_modulus( llong a, double b )
{
	return double(a) - llong(a/b)*b;
}


void OscilloscopeView::paintEvent( TQPaintEvent *e )
{
	TQRect r = e->rect();
	
	if (b_needRedraw)
	{
		updateOutputHeight();
		const double pixelsPerSecond = Oscilloscope::self()->pixelsPerSecond();
		
		TQPainter p;
		m_pixmap->fill( paletteBackgroundColor() );
		p.begin(m_pixmap);
		p.setClipRegion(e->region());
		
		//BEGIN Draw vertical marker lines
		const double divisions = 5.0;
		const double min_sep = 10.0;
		
		double spacing = pixelsPerSecond/(std::pow( divisions, std::floor(std::log(pixelsPerSecond/min_sep)/std::log(divisions)) ));
		
		// Pixels offset is the number of pixels that the view is scrolled along
		const llong pixelsOffset = llong(Oscilloscope::self()->scrollTime()*pixelsPerSecond/LOGIC_UPDATE_RATE);
		double linesOffset = - lld_modulus( pixelsOffset, spacing );
		
		int blackness = 256 - int(184.0 * spacing / (min_sep*divisions*divisions));
		p.setPen( TQColor( blackness, blackness, blackness ) );
		
		for ( double i = linesOffset; i <= frameRect().width(); i += spacing )
			p.drawLine( int(i), 1, int(i), frameRect().height()-2 );
		
		
		
		spacing *= divisions;
		linesOffset = - lld_modulus( pixelsOffset, spacing );
		
		blackness = 256 - int(184.0 * spacing / (min_sep*divisions*divisions));
		p.setPen( TQColor( blackness, blackness, blackness ) );
		
		for ( double i = linesOffset; i <= frameRect().width(); i += spacing )
			p.drawLine( int(i), 1, int(i), frameRect().height()-2 );
		
		
		
		spacing *= divisions;
		linesOffset = - lld_modulus( pixelsOffset, spacing );
		
		blackness = 256 - int(184.0);
		p.setPen( TQColor( blackness, blackness, blackness ) );
		
		for ( double i = linesOffset; i <= frameRect().width(); i += spacing )
			p.drawLine( int(i), 1, int(i), frameRect().height()-2 );
		//END Draw vertical marker lines
		
		drawLogicData(p);
		drawFloatingData(p);
		
		p.setPen(TQt::black);
		p.drawRect( frameRect() );
		
		b_needRedraw = false;
	}
	
	bitBlt( this, r.x(), r.y(), m_pixmap, r.x(), r.y(), r.width(), r.height() );
}


void OscilloscopeView::updateOutputHeight()
{
	m_halfOutputHeight = int((Oscilloscope::self()->probePositioner->probeOutputHeight() - (probeArrowWidth/Oscilloscope::self()->numberOfProbes()))/2)-1;
}


void OscilloscopeView::drawLogicData( TQPainter & p )
{
	const double pixelsPerSecond = Oscilloscope::self()->pixelsPerSecond();
	
	const LogicProbeDataMap::iterator end = Oscilloscope::self()->m_logicProbeDataMap.end();
	for ( LogicProbeDataMap::iterator it = Oscilloscope::self()->m_logicProbeDataMap.begin(); it != end; ++it )
	{
		// When searching for the next logic value to display, we look along
		// until there is a recorded point which is at least one pixel along
		// If we are zoomed out far, there might be thousands of data points
		// between each pixel. It is time consuming searching for the next point
		// to display one at a time, so we record the average number of data points
		// between pixels ( = deltaAt / totalDeltaAt )
		llong deltaAt = 1;
		int totalDeltaAt = 1;
		
		LogicProbeData * probe = it.data();
		StoredData<LogicDataPoint> * data = &(probe->m_data);
		
		if ( data->allocatedUpTo() == 0 )
			continue;
		
		const int midHeight = Oscilloscope::self()->probePositioner->probePosition(probe);
		const llong timeOffset = Oscilloscope::self()->scrollTime();
		
		// Draw the horizontal line indicating the midpoint of our output
		p.setPen( TQColor( 228, 228, 228 ) );
		p.drawLine( 0, midHeight, width(), midHeight );
		
		// Set the pen colour according to the colour the user has selected for the probe
		p.setPen( probe->color() );
		
		// The smallest time step that will display in our oscilloscope
		const int minTimeStep = int(LOGIC_UPDATE_RATE/pixelsPerSecond);
		
		llong at = probe->findPos(timeOffset);
		const llong maxAt = probe->insertPos();
		llong prevTime = data->dataAt(at).time;
		int prevX = (at > 0) ? 0 : int((prevTime - timeOffset)*(pixelsPerSecond/LOGIC_UPDATE_RATE));
		bool prevHigh = data->dataAt(at).value;
		int prevY = midHeight + int(prevHigh ? -m_halfOutputHeight : +m_halfOutputHeight);
		while ( at < maxAt )
		{
			// Search for the next pos which will show up at our zoom level
			llong previousAt = at;
			llong dAt = deltaAt / totalDeltaAt;
			
			while ( (dAt > 1) && (at < maxAt) && ( (llong(data->dataAt(at).time) - prevTime) != minTimeStep ) )
			{
				// Search forwards until we overshoot
				while ( at < maxAt && ( llong(data->dataAt(at).time) - prevTime ) < minTimeStep )
					at += dAt;
				dAt /= 2;
				
				// Search backwards until we undershoot
				while ( (at < maxAt) && ( llong(data->dataAt(at).time) - prevTime ) > minTimeStep )
				{
					at -= dAt;
					if ( at < 0 )
						at = 0;
				}
				dAt /= 2;
			}
			
			// Possibly increment the value of at found by one (or more if this is the first go)
			while ( (previousAt == at) || ((at < maxAt) && ( llong(data->dataAt(at).time) - prevTime ) < minTimeStep) )
				at++;
			
			if ( at >= maxAt )
				break;
			
			// Update the average values
			deltaAt += at - previousAt;
			totalDeltaAt++;
			
			bool nextHigh = data->dataAt(at).value;
			if ( nextHigh == prevHigh )
				continue;
			llong nextTime = data->dataAt(at).time;
			int nextX = int((nextTime - timeOffset)*(pixelsPerSecond/LOGIC_UPDATE_RATE));
			int nextY = midHeight + int(nextHigh ? -m_halfOutputHeight : +m_halfOutputHeight);
			
			p.drawLine( prevX, prevY, nextX, prevY );
			p.drawLine( nextX, prevY, nextX, nextY );
			
			prevHigh = nextHigh;
			prevTime = nextTime;
			prevX = nextX;
			prevY = nextY;
				
			if ( nextX > width() )
				break;
		};
		
		// If we could not draw right to the end; it is because we exceeded
		// maxAt
		if ( prevX < width() )
			p.drawLine( prevX, prevY, width(), prevY );
	}
}


#define v_to_y int(midHeight - (logarithmic ? ( (v>0) ? log(v/lowerAbsValue) : -log(-v/lowerAbsValue) ) : v) * sf)


void OscilloscopeView::drawFloatingData( TQPainter & p )
{
	const double pixelsPerSecond = Oscilloscope::self()->pixelsPerSecond();
	
	const FloatingProbeDataMap::iterator end = Oscilloscope::self()->m_floatingProbeDataMap.end();
	for ( FloatingProbeDataMap::iterator it = Oscilloscope::self()->m_floatingProbeDataMap.begin(); it != end; ++it )
	{
		FloatingProbeData * probe = it.data();
		StoredData<float> * data = &(probe->m_data);
		
		if ( data->allocatedUpTo() == 0 )
			continue;
		
		bool logarithmic = probe->scaling() == FloatingProbeData::Logarithmic;
		double lowerAbsValue = probe->lowerAbsValue();
		double sf = m_halfOutputHeight / (logarithmic ? log(probe->upperAbsValue()/lowerAbsValue) : probe->upperAbsValue());
		
		const int midHeight = Oscilloscope::self()->probePositioner->probePosition(probe);
		const llong timeOffset = Oscilloscope::self()->scrollTime();
		
		// Draw the horizontal line indicating the midpoint of our output
		p.setPen( TQColor( 228, 228, 228 ) );
		p.drawLine( 0, midHeight, width(), midHeight );
		
		// Set the pen colour according to the colour the user has selected for the probe
		p.setPen( probe->color() );
		
		llong at = probe->findPos(timeOffset); 
		const llong maxAt = probe->insertPos();
		llong prevTime = probe->toTime(at);
		
		double v = data->dataAt((at>0)?at:0);
		int prevY = v_to_y;
		int prevX = int((prevTime - timeOffset)*(pixelsPerSecond/LOGIC_UPDATE_RATE));
		
		while ( at < maxAt-1 )
		{
			at++;
			
			ullong nextTime = prevTime + ullong(LOGIC_UPDATE_RATE/LINEAR_UPDATE_RATE);
			
			double v = data->dataAt((at>0)?at:0);
			int nextY = v_to_y;
			int nextX = int((nextTime - timeOffset)*(pixelsPerSecond/LOGIC_UPDATE_RATE));
			
			p.drawLine( prevX, prevY, nextX, nextY );
				
			prevTime = nextTime;
			prevX = nextX;
			prevY = nextY;
			
			if ( nextX > width() )
				break;
		};
		
		// If we could not draw right to the end; it is because we exceeded
		// maxAt
		if ( prevX < width() )
			p.drawLine( prevX, prevY, width(), prevY );
	}
}


#include "oscilloscopeview.moc"