summaryrefslogtreecommitdiffstats
path: root/src/circuitdocument.cpp
blob: 01f4178ea9692a5c6b2403e9ab863f047b044de2 (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
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
/***************************************************************************
 *   Copyright (C) 2003-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 "canvasmanipulator.h"
#include "circuitdocument.h"
#include "circuitview.h"
#include "component.h"
#include "connector.h"
#include "core/ktlconfig.h"
#include "cnitemgroup.h"
#include "documentiface.h"
#include "drawpart.h"
#include "ecnode.h"
#include "itemdocumentdata.h"
#include "ktechlab.h"
#include "pin.h"
#include "simulator.h"
#include "subcircuits.h"
#include "switch.h"

#include <kdebug.h>
#include <kinputdialog.h> 
#include <klocale.h>
#include <kmessagebox.h>
#include <tqregexp.h>
#include <tqtimer.h> 


CircuitDocument::CircuitDocument( const TQString & caption, KTechlab *ktechlab, const char *name )
	: ICNDocument( caption, ktechlab, name )
{
	m_pOrientationAction = new TDEActionMenu( i18n("Orientation"), "rotate", this );
	
	m_type = Document::dt_circuit;
	m_pDocumentIface = new CircuitDocumentIface(this);
	m_fileExtensionInfo = i18n("*.circuit|Circuit(*.circuit)\n*|All Files");
	
	m_cmManager->addManipulatorInfo( CMSelect::manipulatorInfo() );
	m_cmManager->addManipulatorInfo( CMDraw::manipulatorInfo() );
	m_cmManager->addManipulatorInfo( CMRightClick::manipulatorInfo() );
	m_cmManager->addManipulatorInfo( CMRepeatedItemAdd::manipulatorInfo() );
	m_cmManager->addManipulatorInfo( CMItemResize::manipulatorInfo() );
	m_cmManager->addManipulatorInfo( CMItemDrag::manipulatorInfo() );
	
	connect( this, TQT_SIGNAL(connectorAdded(Connector*)), this, TQT_SLOT(requestAssignCircuits()) );
	connect( this, TQT_SIGNAL(connectorAdded(Connector*)), this, TQT_SLOT(connectorAdded(Connector*)) );
	
	m_updateCircuitsTmr = new TQTimer();
	connect( m_updateCircuitsTmr, TQT_SIGNAL(timeout()), this, TQT_SLOT(assignCircuits()) );
	
	requestStateSave();
}

CircuitDocument::~CircuitDocument()
{
	m_bDeleted = true;
	deleteCircuits();
	
	delete m_updateCircuitsTmr;
	m_updateCircuitsTmr = 0l;
	
	delete m_pDocumentIface;
	m_pDocumentIface = 0l;
}


void CircuitDocument::slotInitItemActions( Item *itemBase )
{
	ICNDocument::slotInitItemActions(itemBase);
	
	CircuitView * activeCircuitView = dynamic_cast<CircuitView*>(activeView());
	if ( !p_ktechlab || !activeCircuitView )
		return;
	
	Component * item = dynamic_cast<Component*>(itemBase);
	
	if ( !item && m_selectList->count() > 0 || !m_selectList->itemsAreSameType() )
		return;
	
	TDEAction * orientation_actions[] = {
		activeCircuitView->action("edit_orientation_0"),
		activeCircuitView->action("edit_orientation_90"),
		activeCircuitView->action("edit_orientation_180"),
		activeCircuitView->action("edit_orientation_270") };

	if ( !item || !item->canRotate() )
	{
		for ( unsigned i = 0; i < 4; ++i )
			orientation_actions[i]->setEnabled(false);
		return;
	}

	for ( unsigned i = 0; i < 4; ++ i)
	{
		orientation_actions[i]->setEnabled(true);
		m_pOrientationAction->remove( orientation_actions[i] );
		m_pOrientationAction->insert( orientation_actions[i] );
	}
	
	if ( item->angleDegrees() == 0 )
		(static_cast<TDEToggleAction*>( orientation_actions[0] ))->setChecked(true);
	
	else if ( item->angleDegrees() == 90 )
		(static_cast<TDEToggleAction*>( orientation_actions[1] ))->setChecked(true);
	
	else if ( item->angleDegrees() == 180 )
		(static_cast<TDEToggleAction*>( orientation_actions[2] ))->setChecked(true);
	
	else if ( item->angleDegrees() == 270 )
		(static_cast<TDEToggleAction*>( orientation_actions[3] ))->setChecked(true);
}


void CircuitDocument::rotateCounterClockwise()
{
	m_selectList->slotRotateCCW();
	requestRerouteInvalidatedConnectors();
}
void CircuitDocument::rotateClockwise()
{
	m_selectList->slotRotateCW();
	requestRerouteInvalidatedConnectors();
}
void CircuitDocument::itemFlip()
{
	m_selectList->slotFlip();
	requestRerouteInvalidatedConnectors();
}
void CircuitDocument::setOrientation0()
{
	m_selectList->slotSetOrientation0();
	requestRerouteInvalidatedConnectors();
}
void CircuitDocument::setOrientation90()
{
	m_selectList->slotSetOrientation90();
	requestRerouteInvalidatedConnectors();
}
void CircuitDocument::setOrientation180()
{
	m_selectList->slotSetOrientation180();
	requestRerouteInvalidatedConnectors();
}
void CircuitDocument::setOrientation270()
{
	m_selectList->slotSetOrientation270();
	requestRerouteInvalidatedConnectors();
}


View *CircuitDocument::createView( ViewContainer *viewContainer, uint viewAreaId, const char *name )
{
	View *view = new CircuitView( this, viewContainer, viewAreaId, name );
	handleNewView(view);
	return view;
}


void CircuitDocument::slotUpdateConfiguration()
{
	ICNDocument::slotUpdateConfiguration();
	
	NodeList::iterator nodeEnd = m_nodeList.end();
	for ( NodeList::iterator it = m_nodeList.begin(); it != nodeEnd; ++it )
	{
		(static_cast<ECNode*>((Node*)*it))->setShowVoltageBars( KTLConfig::showVoltageBars() );
	}
	
	ComponentList::iterator componentsEnd = m_componentList.end();
	for ( ComponentList::iterator it = m_componentList.begin(); it != componentsEnd; ++it )
		(*it)->slotUpdateConfiguration();
}


void CircuitDocument::update()
{
	ICNDocument::update();
	
	if ( KTLConfig::showVoltageBars() )
	{
		NodeList::iterator end = m_nodeList.end();
		for ( NodeList::iterator it = m_nodeList.begin(); it != end; ++it )
		{
			(static_cast<ECNode*>((Node*)*it))->setNodeChanged();
		}
	}
}


void CircuitDocument::fillContextMenu( const TQPoint &pos )
{
	ICNDocument::fillContextMenu(pos);
	
	CircuitView * activeCircuitView = dynamic_cast<CircuitView*>(activeView());
	
	if ( m_selectList->count() < 1 || !activeCircuitView )
		return;
	
	Component * item = dynamic_cast<Component*>( selectList()->activeItem() );
	
	// NOTE: I negated this whole condition because I couldn't make out quite what the
	//logic was --electronerd
	if (!( !item && m_selectList->count() > 0 || !m_selectList->itemsAreSameType() ))
	{	
		TDEAction * orientation_actions[] = {
			activeCircuitView->action("edit_orientation_0"),
			activeCircuitView->action("edit_orientation_90"),
			activeCircuitView->action("edit_orientation_180"),
			activeCircuitView->action("edit_orientation_270") };
	
		if ( !item || !item->canRotate() )
			return;
	
		for ( unsigned i = 0; i < 4; ++ i)
		{
			m_pOrientationAction->remove( orientation_actions[i] );
			m_pOrientationAction->insert( orientation_actions[i] );
		}
		
		TQPtrList<TDEAction> orientation_actionlist;
	// 	orientation_actionlist.prepend( new TDEActionSeparator() );
		orientation_actionlist.append( m_pOrientationAction );
		p_ktechlab->plugActionList( "orientation_actionlist", orientation_actionlist );
	}
	
	if(m_selectList->count() > 1 && countExtCon(m_selectList->items()) > 0)
	{
		TQPtrList<TDEAction> component_actionlist;
	// 	component_actionlist.append( new TDEActionSeparator() );
		component_actionlist.append( activeCircuitView->action("circuit_create_subcircuit") );
		p_ktechlab->plugActionList( "component_actionlist", component_actionlist );
	}
}


void CircuitDocument::deleteCircuits()
{
	const CircuitList::iterator end = m_circuitList.end();
	for ( CircuitList::iterator it = m_circuitList.begin(); it != end; ++it )
	{
		Simulator::self()->detachCircuit(*it);
		delete *it;
	}
	m_circuitList.clear();
	m_pinList.clear();
	m_wireList.clear();
}


void CircuitDocument::requestAssignCircuits()
{
// 	kdDebug() << k_funcinfo << endl;
	deleteCircuits();
	m_updateCircuitsTmr->stop();
	m_updateCircuitsTmr->start( 0, true );
}


void CircuitDocument::connectorAdded( Connector * connector )
{
	if (connector)
	{
		connect( connector, TQT_SIGNAL(numWiresChanged(unsigned )), this, TQT_SLOT(requestAssignCircuits()) );
		connect( connector, TQT_SIGNAL(removed(Connector*)), this, TQT_SLOT(requestAssignCircuits()) );
	}
}


void CircuitDocument::itemAdded( Item * item)
{
	ICNDocument::itemAdded( item );
	componentAdded( item );
}


void CircuitDocument::componentAdded( Item * item )
{
	Component * component = dynamic_cast<Component*>(item);
	if (!component)
		return;
	
	requestAssignCircuits();
	
	connect( component, TQT_SIGNAL(elementCreated(Element*)), this, TQT_SLOT(requestAssignCircuits()) );
	connect( component, TQT_SIGNAL(elementDestroyed(Element*)), this, TQT_SLOT(requestAssignCircuits()) );
	connect( component, TQT_SIGNAL(removed(Item*)), this, TQT_SLOT(componentRemoved(Item*)) );
	
	// We don't attach the component to the Simulator just yet, as the
	// Component's vtable is not yet fully constructed, and so Simulator can't
	// tell whether or not it is a logic component
	if ( !m_toSimulateList.contains(component) )
		m_toSimulateList << component;
}


void CircuitDocument::componentRemoved( Item * item )
{
	Component * component = dynamic_cast<Component*>(item);
	if (!component)
		return;
	m_componentList.remove(component);
	
	requestAssignCircuits();
	Simulator::self()->detachComponent(component);
}


void CircuitDocument::calculateConnectorCurrents()
{
	const CircuitList::iterator circuitEnd = m_circuitList.end();
	for ( CircuitList::iterator it = m_circuitList.begin(); it != circuitEnd; ++it )
		(*it)->updateCurrents();
	
	PinList groundPins;
	
	// Tell the Pins to reset their calculated currents to zero
	m_pinList.remove((Pin*)0l);
	const PinList::iterator pinEnd = m_pinList.end();
	for ( PinList::iterator it = m_pinList.begin(); it != pinEnd; ++it )
	{
		if ( Pin *n = dynamic_cast<Pin*>((Pin*)*it) )
		{
			n->resetCurrent();
			n->setSwitchCurrentsUnknown();
			
			if ( !n->parentECNode()->isChildNode() )
			{
				n->setCurrentKnown( true );
				// (and it has a current of 0 amps)
			}
			else if ( n->groundType() == Pin::gt_always )
			{
				groundPins << n;
				n->setCurrentKnown( false );
			}
			else
			{
				// Child node that is non ground
				n->setCurrentKnown( n->parentECNode()->numPins() < 2 );
			}
		}
	}
	
	
	// Tell the components to update their ECNode's currents' from the elements
	const ComponentList::iterator componentEnd = m_componentList.end();
	for ( ComponentList::iterator it = m_componentList.begin(); it != componentEnd; ++it )
		(*it)->setNodalCurrents();
	
	
	// And now for the wires and switches...
	m_wireList.remove((Wire*)0l);
	const WireList::iterator clEnd = m_wireList.end();
	for ( WireList::iterator it = m_wireList.begin(); it != clEnd; ++it )
		(*it)->setCurrentKnown(false);
	
	SwitchList switches = m_switchList;
	WireList wires = m_wireList;
	bool found = true;
	while ( (!wires.isEmpty() || !switches.isEmpty() || !groundPins.isEmpty()) && found )
	{
		found = false;
		
		WireList::iterator wiresEnd = wires.end();
		for ( WireList::iterator it = wires.begin(); it != wiresEnd; )
		{
			if ( (*it)->calculateCurrent() )
			{
				found = true;
				WireList::iterator oldIt = it;
				++it;
				wires.remove(oldIt);
			}
			else
				++it;
		}
		
		SwitchList::iterator switchesEnd = switches.end();
		for ( SwitchList::iterator it = switches.begin(); it != switchesEnd; )
		{
			if ( (*it)->calculateCurrent() )
			{
				found = true;
				SwitchList::iterator oldIt = it;
				++it;
				switches.remove(oldIt);
			}
			else
				++it;
		}
		
		PinList::iterator groundPinsEnd = groundPins.end();
		for ( PinList::iterator it = groundPins.begin(); it != groundPinsEnd; )
		{
			if ( (*it)->calculateCurrentFromWires() )
			{
				found = true;
				PinList::iterator oldIt = it;
				++it;
				groundPins.remove(oldIt);
			}
			else
				++it;
		}
	}
}


void CircuitDocument::assignCircuits()
{
	// Now we can finally add the unadded components to the Simulator
	const ComponentList::iterator toSimulateEnd = m_toSimulateList.end();
	for ( ComponentList::iterator it = m_toSimulateList.begin(); it != toSimulateEnd; ++it )
		Simulator::self()->attachComponent(*it);
	m_toSimulateList.clear();
	
	
	
	// Stage 0: Build up pin and wire lists
	m_pinList.clear();
	const NodeList::const_iterator nodeListEnd = m_nodeList.end();
	for ( NodeList::const_iterator it = m_nodeList.begin(); it != nodeListEnd; ++it )
	{
		if ( ECNode * ecnode = dynamic_cast<ECNode*>((Node*)*it) )
		{
			for ( unsigned i = 0; i < ecnode->numPins(); i++ )
				m_pinList << ecnode->pin(i);
		}
	}
	
	m_wireList.clear();
	const ConnectorList::const_iterator connectorListEnd = m_connectorList.end();
	for ( ConnectorList::const_iterator it = m_connectorList.begin(); it != connectorListEnd; ++it )
	{
		for ( unsigned i = 0; i < (*it)->numWires(); i++ )
			m_wireList << (*it)->wire(i);
	}
	
	
	
	
	typedef TQValueList<PinList> PinListList;
	
	// Stage 1: Partition the circuit up into dependent areas (bar splitting
	// at ground pins)
	PinList unassignedPins = m_pinList;
	PinListList pinListList;
	while ( !unassignedPins.isEmpty() )
	{
		PinList pinList;
		getPartition( *unassignedPins.begin(), & pinList, & unassignedPins );
		pinListList.append(pinList);
	}
// 	kdDebug () << "pinListList.size()="<<pinListList.size()<<endl;
	
	// Stage 2: Split up each partition into circuits by ground pins
	const PinListList::iterator nllEnd = pinListList.end();
	for ( PinListList::iterator it = pinListList.begin(); it != nllEnd; ++it )
		splitIntoCircuits(&*it);
	
	// Stage 3: Initialize the circuits
	m_circuitList.remove(0l);
	CircuitList::iterator circuitListEnd = m_circuitList.end();
	for ( CircuitList::iterator it = m_circuitList.begin(); it != circuitListEnd; ++it )
		(*it)->init();
	
	m_switchList.clear();
	m_componentList.clear();
	const ItemList::const_iterator cilEnd = m_itemList.end();
	for ( ItemList::const_iterator it = m_itemList.begin(); it != cilEnd; ++it )
	{
		Component * component = dynamic_cast<Component*>((Item*)(*it));
		if ( !component )
			continue;
		
		m_componentList << component;
		component->initElements(0);
		m_switchList += component->switchList();
	}
	
	circuitListEnd = m_circuitList.end();
	for ( CircuitList::iterator it = m_circuitList.begin(); it != circuitListEnd; ++it )
		(*it)->createMatrixMap();
	
	for ( ItemList::const_iterator it = m_itemList.begin(); it != cilEnd; ++it )
	{
		Component * component = dynamic_cast<Component*>((Item*)(*it));
		if (component)
			component->initElements(1);
	}
	
	circuitListEnd = m_circuitList.end();
	for ( CircuitList::iterator it = m_circuitList.begin(); it != circuitListEnd; ++it )
	{
		(*it)->initCache();
		Simulator::self()->attachCircuit(*it);
	}
}


void CircuitDocument::getPartition( Pin *pin, PinList *pinList, PinList *unassignedPins, bool onlyGroundDependent )
{
	if (!pin)
		return;
	
	unassignedPins->remove(pin);
	
	if ( pinList->contains(pin) )
		return;
	pinList->append(pin);
	
	const PinList localConnectedPins = pin->localConnectedPins();
	const PinList::const_iterator end = localConnectedPins.end();
	for ( PinList::const_iterator it = localConnectedPins.begin(); it != end; ++it )
		getPartition( *it, pinList, unassignedPins, onlyGroundDependent );
	
	const PinList groundDependentPins = pin->groundDependentPins();
	const PinList::const_iterator dEnd = groundDependentPins.end();
	for ( PinList::const_iterator it = groundDependentPins.begin(); it != dEnd; ++it )
		getPartition( *it, pinList, unassignedPins, onlyGroundDependent );
	
	if (!onlyGroundDependent)
	{
		PinList circuitDependentPins = pin->circuitDependentPins();
		const PinList::const_iterator dEnd = circuitDependentPins.end();
		for ( PinList::const_iterator it = circuitDependentPins.begin(); it != dEnd; ++it )
			getPartition( *it, pinList, unassignedPins, onlyGroundDependent );
	}
}


void CircuitDocument::splitIntoCircuits( PinList *pinList )
{
	// First: identify ground
	PinList unassignedPins = *pinList;
	typedef TQValueList<PinList> PinListList;
	PinListList pinListList;
	while ( !unassignedPins.isEmpty() )
	{
		PinList tempPinList;
		getPartition( *unassignedPins.begin(), & tempPinList, & unassignedPins, true );
		pinListList.append(tempPinList);
	}
	const PinListList::iterator nllEnd = pinListList.end();
	for ( PinListList::iterator it = pinListList.begin(); it != nllEnd; ++it )
		Circuit::identifyGround(*it);
	
	

	bool allGround = false;
	while ( !pinList->isEmpty() && !allGround )
	{
		PinList::iterator end = pinList->end();
		PinList::iterator it = pinList->begin();
		
		while ( it != end && (*it)->eqId() == -1 )
			++it;
		
		if ( it == end )
			allGround = true;
		
		else
		{
			Circuitoid *circuitoid = new Circuitoid;
			recursivePinAdd( *it, circuitoid, pinList );
			
			if ( !tryAsLogicCircuit(circuitoid) )
				m_circuitList += createCircuit(circuitoid);
			
			delete circuitoid;
		}
	}
	
	
	// Remaining pins are ground; tell them about it
	// TODO This is a bit hacky....
	const PinList::iterator end = pinList->end();
	for ( PinList::iterator it = pinList->begin(); it != end; ++it )
	{
		(*it)->setVoltage(0.0);
		
		ElementList elements = (*it)->elements();
		const ElementList::iterator eEnd = elements.end();
		for ( ElementList::iterator it = elements.begin(); it != eEnd; ++it )
		{
			if ( LogicIn * logicIn = dynamic_cast<LogicIn*>(*it) )
			{
				logicIn->setLastState(false);
				logicIn->callCallback();
			}
		}
	}
}


void CircuitDocument::recursivePinAdd( Pin *pin, Circuitoid *circuitoid, PinList *unassignedPins )
{
	if (!pin)
		return;
	
	if ( pin->eqId() != -1 )
		unassignedPins->remove(pin);
	
	if ( circuitoid->contains(pin) )
		return;
	circuitoid->addPin(pin);
	
	if ( pin->eqId() == -1 )
		return;
	
	const PinList localConnectedPins = pin->localConnectedPins();
	const PinList::const_iterator end = localConnectedPins.end();
	for ( PinList::const_iterator it = localConnectedPins.begin(); it != end; ++it )
		recursivePinAdd( *it, circuitoid, unassignedPins );
	
	const WireList inputList = pin->inputWireList();
	WireList::const_iterator conEnd = inputList.end();
	for ( WireList::const_iterator it = inputList.begin(); it != conEnd; ++it )
		circuitoid->addWire(*it);
	
	const WireList outputList = pin->outputWireList();
	conEnd = outputList.end();
	for ( WireList::const_iterator it = outputList.begin(); it != conEnd; ++it )
		circuitoid->addWire(*it);
	
	const PinList groundDependentPins = pin->groundDependentPins();
	const PinList::const_iterator gdEnd = groundDependentPins.end();
	for ( PinList::const_iterator it = groundDependentPins.begin(); it != gdEnd; ++it )
		recursivePinAdd( *it, circuitoid, unassignedPins );
	
	const PinList circuitDependentPins = pin->circuitDependentPins();
	const PinList::const_iterator cdEnd = circuitDependentPins.end();
	for ( PinList::const_iterator it = circuitDependentPins.begin(); it != cdEnd; ++it )
		recursivePinAdd( *it, circuitoid, unassignedPins );
	
	const ElementList elements = pin->elements();
	const ElementList::const_iterator eEnd = elements.end();
	for ( ElementList::const_iterator it = elements.begin(); it != eEnd; ++it )
		circuitoid->addElement(*it);
}


bool CircuitDocument::tryAsLogicCircuit( Circuitoid *circuitoid )
{
	if (!circuitoid)
		return false;
	
	if ( circuitoid->elementList.size() == 0 )
	{
		// This doesn't quite belong here...but whatever. Initialize all
		// pins to voltage zero as they won't get set to zero otherwise
		const PinList::const_iterator pinListEnd = circuitoid->pinList.constEnd();
		for ( PinList::const_iterator it = circuitoid->pinList.constBegin(); it != pinListEnd; ++it )
			(*it)->setVoltage(0.0);
		
		// A logic circuit only requires there to be no non-logic components,
		// and at most one LogicOut - so this qualifies
		return true;
	}
	
	LogicInList logicInList;
	LogicOut *out = 0l;
	
	uint logicInCount = 0;
	uint logicOutCount = 0;
	ElementList::const_iterator end = circuitoid->elementList.end();
	for ( ElementList::const_iterator it = circuitoid->elementList.begin(); it != end; ++it )
	{
		if ( (*it)->type() == Element::Element_LogicOut )
		{
			logicOutCount++;
			out = static_cast<LogicOut*>(*it);
		}
		else if ( (*it)->type() == Element::Element_LogicIn )
		{
			logicInCount++;
			logicInList += static_cast<LogicIn*>(*it);
		}
		else
			return false;
	}
	if ( logicOutCount > 1 )
		return false;
	
	else if ( logicOutCount == 1 )
		Simulator::self()->createLogicChain( out, logicInList, circuitoid->pinList );
	
	else
	{
		// We have ourselves stranded LogicIns...so lets set them all to low
		
		const PinList::const_iterator pinListEnd = circuitoid->pinList.constEnd();
		for ( PinList::const_iterator it = circuitoid->pinList.constBegin(); it != pinListEnd; ++it )
			(*it)->setVoltage(0.0);
		
		for ( ElementList::const_iterator it = circuitoid->elementList.begin(); it != end; ++it )
		{
			LogicIn * logicIn = static_cast<LogicIn*>(*it);
			logicIn->setNextLogic(0l);
			logicIn->setElementSet(0l);
			if ( logicIn->isHigh() )
			{
				logicIn->setLastState(false);
				logicIn->callCallback();
			}
		}
	}
	
	return true;
}


Circuit *CircuitDocument::createCircuit( Circuitoid *circuitoid )
{
	if (!circuitoid) {
		return 0l;
	}
	
	Circuit *circuit = new Circuit();
	
	const PinList::const_iterator nEnd = circuitoid->pinList.end();
	for ( PinList::const_iterator it = circuitoid->pinList.begin(); it != nEnd; ++it )
		circuit->addPin(*it);
	
	const ElementList::const_iterator eEnd = circuitoid->elementList.end();
	for ( ElementList::const_iterator it = circuitoid->elementList.begin(); it != eEnd; ++it )
		circuit->addElement(*it);
	
	return circuit;
}



void CircuitDocument::createSubcircuit()
{
	ItemList itemList = m_selectList->items();
	const ItemList::iterator itemListEnd = itemList.end();
	for ( ItemList::iterator it = itemList.begin(); it != itemListEnd; ++it )
	{
		if ( !dynamic_cast<Component*>((Item*)*it) )
			*it = 0l;
	}
	itemList.remove((Item*)0l);
	
	if ( itemList.isEmpty() )
	{
		KMessageBox::sorry( activeView(), i18n("No components were found in the selection.") );
		return;
	}
	
	// Number of external connections
	const int extConCount = countExtCon(itemList);
	if ( extConCount == 0 )
	{
		KMessageBox::sorry( activeView(), i18n("No External Connection components were found in the selection.") );
		return;
	}
	
	bool ok;
	const TQString name = KInputDialog::getText( "Subcircuit", "Name", TQString(), &ok, activeView() );
	if (!ok)
		return;
	
	SubcircuitData subcircuit;
	subcircuit.addItems(itemList);
	subcircuit.addNodes( getCommonNodes(itemList) );
	subcircuit.addConnectors( getCommonConnectors(itemList) );
	
	Subcircuits::addSubcircuit( name, subcircuit.toXML() );
}


int CircuitDocument::countExtCon( const ItemList &itemList ) const
{
	int count = 0;
	const ItemList::const_iterator end = itemList.end();
	for ( ItemList::const_iterator it = itemList.begin(); it != end; ++it )
	{
		Item * item = *it;
    	if ( item && item->type() == "ec/external_connection" )
			count++;
	}
	return count;
}


bool CircuitDocument::isValidItem( const TQString &itemId )
{
	return itemId.startsWith("ec/") || itemId.startsWith("dp/") || itemId.startsWith("sc/");
}


bool CircuitDocument::isValidItem( Item *item )
{
	return (dynamic_cast<Component*>(item) || dynamic_cast<DrawPart*>(item));
}


void CircuitDocument::displayEquations()
{
	kdDebug() << "######################################################" << endl;
	const CircuitList::iterator end = m_circuitList.end();
	int i = 1;
	for ( CircuitList::iterator it = m_circuitList.begin(); it != end; ++it )
	{
		kdDebug() << "Equation set "<<i<<":\n";
		(*it)->displayEquations();
		i++;
	}
	kdDebug() << "######################################################" << endl;
}


#include "circuitdocument.moc"