Typica is a free program for professional coffee roasters. https://typica.us
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

typica.w 598KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244
  1. % Instructions for generating source code and documentation
  2. % Step 1. Convert metapost diagrams into PDF documents
  3. % $ mptopdf pipes.mp ; epstopdf pipes.ps
  4. % $ mptopdf roast.mp ; epstopdf roast.ps
  5. % $ mptopdf search.mp ; epstopdf search.ps
  6. % Step 2. Weave and typeset
  7. % $ cweave typica
  8. % $ pdftex typica
  9. % Step 3. Tangle and moc
  10. % $ ctangle typica ; mv typica.c typica.cpp
  11. % $ moc typica.cpp > moc_typica.cpp
  12. %
  13. % If you have trouble compiling, check to make sure the required headers are in
  14. % your header search path and check to make sure the required libraries are
  15. % linked. If using qmake to generate a project file, remember to add the
  16. % following lines to your .pro file:
  17. % QT += xml
  18. % QT += script
  19. % Document style instructions
  20. \input graphicx.tex
  21. \mark{\noexpand\nullsec0{A Note on Notation}}
  22. \def\pn{Typica}
  23. \def\filebase{typica}
  24. \def\version{1.4.3 \number\year-\number\month-\number\day}
  25. \def\years{2007--2013}
  26. \def\title{\pn{} (Version \version)}
  27. \newskip\dangerskipb
  28. \newskip\dangerskip
  29. \dangerskip=20pt
  30. \dangerskipb=42pt
  31. \def\hang{\hangindent\dangerskip}
  32. \def\hangb{\hangindent\dangerskipb}
  33. \font\manual=manfnt at 12pt
  34. \def\danbend{{\manual\char127}}
  35. \def\datanger{\medbreak\begingroup\clubpenalty=10000
  36. \def\par{\endgraf\endgroup\medbreak} \noindent\hang\hangafter=-2
  37. \hbox to0pt{\hskip-3.5pc\danbend\hfill}}
  38. \outer\def\danger{\datanger}%
  39. %
  40. \def\datangerb{\medbreak\begingroup\clubpenalty=10000
  41. \def\par{\endgraf\endgroup\medbreak} \noindent\hang\hangafter=-2
  42. \hbox to0pt{\hskip-3.5pc\danbend\hfill}}
  43. \outer\def\dangerb{\datangerb}
  44. \def\endanger{\medskip}
  45. \def\nullsec{\S1}
  46. \def\lheader{\mainfont\the\pageno\kern1pc(\topsecno)\eightrm
  47. \qquad\grouptitle\hfill\title}
  48. \def\rheader{\eightrm\title\hfill\grouptitle\qquad\mainfont
  49. (\topsecno)\kern1pc\the\pageno}
  50. \def\botofcontents{\vfill
  51. \noindent Copyright \copyright\ \years~Neal Evan Wilson
  52. \bigskip\noindent Permission is hereby granted, free of charge, to any
  53. person obtaining a copy of this software and associated documentation files
  54. (the ``Software''), to deal in the Software without restriction, including
  55. without limitation the rights to use, copy, modify, merge, publish,
  56. distribute, sublicense, and/or sell copies of the Software, and to permit
  57. persons to whom the Software is furnished to do so, subject to the following
  58. conditions:\medskip
  59. The above copyright notice and this permission notice shall be included in
  60. all copies or substantial portions of the Software.\medskip
  61. THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  62. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  63. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  64. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  65. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  66. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  67. IN THE SOFTWARE.
  68. \bigskip\noindent Parts of \pn{} are from QextSerialPort which is used under the
  69. MIT license as follows:
  70. \bigskip\noindent Copyright \copyright\ 2000--2003 Wayne Roth
  71. \noindent Copyright \copyright\ 2004--2007 Stefan Sander
  72. \noindent Copyright \copyright\ 2007 Michal Policht
  73. \noindent Copyright \copyright\ 2008 Brandon Fosdick
  74. \noindent Copyright \copyright\ 2009--2010 Liam Staskawicz
  75. \noindent Copyright \copyright\ 2011 Debao Zhang
  76. \bigskip\noindent Web: http://code.google.com/p/qextserialport/
  77. \bigskip\noindent Permission is hereby granted, free of charge, to any person obtaining
  78. a copy of this software and associated documentation files (the
  79. ``Software''), to deal in the Software without restriction, including
  80. without limitation the rights to use, copy, modify, merge, publish,
  81. distribute, sublicense, and/or sell copies of the Software, and to
  82. permit persons to whom the Software is furnished to do so, subject to
  83. the following conditions:
  84. The above copyright notice and this permission notice shall be
  85. included in all copies or substantial portions of the Software.
  86. THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
  87. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  88. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  89. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  90. LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  91. OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  92. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  93. }
  94. \let\K=\leftarrow
  95. \def\CPLUSPLUS/{{%
  96. \mc C{\hbox{\kern.5pt\raise1pt\hbox{\sevenrm+\kern-1pt+}\kern.5pt}}
  97. \spacefactor1000}}
  98. \def\PP{\uparrow}
  99. \def\MM{\downarrow}
  100. \newbox\DCBox
  101. \setbox\DCBox=\hbox{$\in$}
  102. \def\DC{\copy\DCBox}
  103. \newbox\MODbox \setbox\MODbox=\hbox{\eightrm MOD}
  104. \def\MOD{\mathbin{\copy\MODbox}}
  105. % Title page
  106. \font\authorfont=cmr12
  107. \null\vfill
  108. \centerline{\titlefont \pn}
  109. \vskip 18pt\centerline{(Version \version)}
  110. \vskip 24pt\centerline{\authorfont Neal Evan Wilson}
  111. \vfill
  112. \titletrue\eject\hbox to 0pt{}
  113. \pageno=0 \titletrue\eject
  114. \secpagedepth=1
  115. % Convenience macros
  116. \def\newline{\vskip\baselineskip}
  117. \def\cweb{\.{CWEB}}
  118. \def\web{\.{WEB}}
  119. \newcount\footnotenumber
  120. \def\nfnote{\global\advance\footnotenumber by 1
  121. \footnote{$^{\the\footnotenumber}$}}
  122. % Listing macro from The TeXBook. See page 381 for an explaination.
  123. \def\uncatcodespecials{\def\do##1{\catcode`##1=12 }\dospecials}
  124. \newcount\lineno
  125. \def\setupverbatim{\tt \lineno=0
  126. \def\par{\leavevmode\endgraf} \catcode`\`=\active
  127. \obeylines \uncatcodespecials \obeyspaces
  128. \everypar{\advance\lineno by1 \llap{\sevenrm\the\lineno\ \ }}}
  129. {\obeyspaces\global\let =\ }
  130. \def\listing#1{\par\begingroup\setupverbatim\input#1 \endgroup}
  131. % Javascript chunk handling
  132. \def\jsfile#1#2{\Y\B\4\X\secno:\.{#1}\X${}\E{}\6$\par
  133. \listing{#2}}
  134. % Type formatting
  135. @s QTime int
  136. @s QMetaType int
  137. @s DAQ int
  138. @s Channel int
  139. @s QString int
  140. @s QObject int
  141. @s QThread int
  142. @s DAQImplementation int
  143. @s QVector int
  144. @s TaskHandle int
  145. @s qint32 int
  146. @s int32 int
  147. @s QMessageBox int
  148. @s QLCDNumber int
  149. @s QWidget int
  150. @s AnnotationButton int
  151. @s AnnotationSpinBox int
  152. @s QPushButton int
  153. @s QTimer int
  154. @s QAction int
  155. @s QApplication int
  156. @s PackLayout int
  157. @s QLayout int
  158. @s QLayoutItem int
  159. @s QRect int
  160. @s QList int
  161. @s QSize int
  162. @s QGraphicsScene int
  163. @s SceneButton int
  164. @s QGraphicsSceneMouseEvent int
  165. @s QPoint int
  166. @s true const
  167. @s false const
  168. @s QGraphicsView int
  169. @s QGraphicsTextItem int
  170. @s QFrame int
  171. @s QPaintDevice int
  172. @s QColor int
  173. @s QBrush int
  174. @s QHash int
  175. @s QPointF int
  176. @s QGraphicsLineItem int
  177. @s MeasurementModel int
  178. @s QTableView int
  179. @s QVariant int
  180. @s QAbstractItemView int
  181. @s QAbstractItemModel int
  182. @s QStringList int
  183. @s QModelIndex int
  184. @s MeasurementList int
  185. @s QVariantList int
  186. @s QSplitter int
  187. @s QHBoxLayout int
  188. @s QMainWindow int
  189. @s QCoreApplication int
  190. @s QSettings int
  191. @s QMenu int
  192. @s QCloseEvent int
  193. @s LogEditWindow int
  194. @s QFile int
  195. @s QFileInfo int
  196. @s QDir int
  197. @s QXmlStreamWriter int
  198. @s QXmlStreamReader int
  199. @s QIODevice int
  200. @s QLabel int
  201. @s QTimeEdit int
  202. @s QSpinBox int
  203. @s QDoubleSpinBox int
  204. @s ThermocoupleType int
  205. @s TemperatureUnits int
  206. @s Qt int
  207. @s emit throw
  208. @s TemperatureDisplay int
  209. @s ZeroEmitter int
  210. @s MeasurementAdapter int
  211. @s GraphView int
  212. @s ZoomLog int
  213. @s TimerDisplay int
  214. @s QBoxLayout int
  215. @s WidgetDecorator int
  216. @s XMLInput int
  217. @s XMLOutput int
  218. @s CSVOutput int
  219. @s QTextStream int
  220. @s QTranslator int
  221. @s QLocale int
  222. @s Application int
  223. @s QScriptContext int
  224. @s QScriptEngine int
  225. @s QScriptEngineDebugger int
  226. @s QScriptValue int
  227. @s FakeDAQ int
  228. @s QMenuBar int
  229. @s QKeySequence int
  230. @s QFileDialog int
  231. @s Measurement int
  232. @s Date int
  233. @s QLibrary int
  234. @s daqfp int
  235. @s QResizeEvent int
  236. @s QVBoxLayout int
  237. @s QByteArray int
  238. @s QSqlDatabase int
  239. @s QComboBox int
  240. @s QXmlStreamAttribute int
  241. @s QSqlQuery int
  242. @s QLineEdit int
  243. @s QDoubleValidator int
  244. @s QIntValidator int
  245. @s QTextEdit int
  246. @s QStandardItemModel int
  247. @s QValidator int
  248. @s QMap int
  249. @s QDomElement int
  250. @s QDomNodeList int
  251. @s QDomNode int
  252. @s QStack int
  253. @s QDomDocument int
  254. @s QDomNamedNodeMap int
  255. @s QFormLayout int
  256. @s QAbstractButton int
  257. @s QAbstractScrollArea int
  258. @s SqlComboBox int
  259. @s QUuid int
  260. @s SqlComboBoxDelegate int
  261. @s QItemDelegate int
  262. @s SqlConnectionSetup int
  263. @s QDialog int
  264. @s QCheckBox int
  265. @s SaltModel int
  266. @s QStyleOptionViewItem int
  267. @s QBuffer int
  268. @s QDateEdit int
  269. @s QCalendarWidget int
  270. @s QDate int
  271. @s QFocusEvent int
  272. @s QGridLayout int
  273. @s QScrollArea int
  274. @s QSqlQueryModel int
  275. @s QSqlRecord int
  276. @s QSqlResult int
  277. @s SqlQueryConnection int
  278. @s QFont int
  279. @s SqlQueryView int
  280. @s QTextDocument int
  281. @s QTextCursor int
  282. @s QTextFrame int
  283. @s ReportTable int
  284. @s QTextTable int
  285. @s QTextTableFormat int
  286. @s QTextFrameFormat int
  287. @s QTextTableCell int
  288. @s QPrinter int
  289. @s QPrintDialog int
  290. @s QSqlError int
  291. @s FormArray int
  292. @s QRegExp int
  293. @s QRegExpValidator int
  294. @s QDomDocumentFragment int
  295. @s QStackedLayout int
  296. @s QMouseEvent int
  297. @s QGraphicsPolygonItem int
  298. @s QPolygonF int
  299. @s QGraphicsPathItem int
  300. @s QPainterPath int
  301. @s QXmlQuery int
  302. @s QGraphicsItem int
  303. @s QWebView int
  304. @s QUrl int
  305. @s QShowEvent int
  306. @s QDateTimeEdit int
  307. @s ThresholdDetector int
  308. @s EdgeDirection int
  309. @s DeviceTreeModelNode int
  310. @s QMetaObject int
  311. @s QTreeView int
  312. @s QToolButton int
  313. @s QextPortInfo int
  314. @s QextSerialEnumerator int
  315. @s QMetaEnum int
  316. @s quint16 int
  317. @s QextSerialPort int
  318. @s QGroupBox int
  319. @s QVariantMap int
  320. @s QIcon int
  321. @s QFileInfoList int
  322. @s QMetaMethod int
  323. @f error normal
  324. @f line normal
  325. @f signals public
  326. @f slots int
  327. @f qRegisterMetaType make_pair
  328. @f READ TeX
  329. @f WRITE TeX
  330. @f tr TeX
  331. @f this TeX
  332. @f foreach while
  333. @f qobject_cast make_pair
  334. @f t1 TeX
  335. @f t2 TeX
  336. @f AppInstance TeX
  337. @f getself make_pair
  338. @f TYPE TeX
  339. @f argument make_pair
  340. @f toScriptValue make_pair
  341. @f arg1 TeX
  342. @f arg2 TeX
  343. @f arg3 TeX
  344. @f arg4 TeX
  345. @f findChild make_pair
  346. @f qscriptvalue_cast make_pair
  347. \def\READ{\kern4pt{\tt READ}\kern4pt}
  348. \def\WRITE{\kern4pt{\tt WRITE}\kern4pt}
  349. \def\tr{\delta}
  350. \def\this{\forall}
  351. \def\t#1{t_{#1}}
  352. \def\AppInstance{\.{AppInstance}}
  353. \def\TYPE{\cal T\kern1pt}
  354. \def\arg#1{arg_{#1}}
  355. % Document
  356. @** A Note on Notation.
  357. \noindent As noted by Falkoff and Iverson\nfnote{A.~D.~Falkoff and
  358. K.~E.~Iverson, ``The Design of APL'' (1973)}~there is little need to limit the
  359. typography used to represent a computer program in print. The printed code of
  360. \pn{} uses a number of notations that I have found useful in making clear the
  361. intent of the code. For example, a common mistake in \CPLUSPLUS/ \kern-0.5em
  362. code is the confusion of assignment ({\tt =}) with a test for equality
  363. ({\tt ==}). The \web{} convention of using |=| for assignment and |==| to test
  364. for equality makes such errors obvious at a glance. A list of special symbols
  365. and the equivalent \CPLUSPLUS/text is provided in Table \secno. Most of these
  366. symbols should be familiar\nfnote{The {\tt NULL} symbol is a break with the
  367. conventions of most Qt applications. According the the \CPLUSPLUS/standard, |0|
  368. is both an integer constant and a null pointer constant. Most programs using Qt
  369. use |0| in place of any name for the null pointer, however conceptually these
  370. are two very different things. The notation chosen here was used by Knuth for
  371. similar purposes and seems to have worked well there.}.
  372. \medskip
  373. \settabs 9 \columns
  374. \+&&&{\tt =}&|=|&Assignment\cr
  375. \+&&&{\tt --}&|--|&Decrement\cr
  376. \+&&&{\tt ==}&|==|&Equality Test\cr
  377. \+&&&{\tt >=}&|>=|&Greater or Equal Test\cr
  378. \+&&&{\tt ++}&|++|&Increment\cr
  379. \+&&&{\tt !=}&|!=|&Inequality Test\cr
  380. \+&&&{\tt <=}&|<=|&Less or Equal Test\cr
  381. \+&&&{\tt \char'046\char'046}&$\land$&Logical AND\cr
  382. \+&&&{\tt \char'174\char'174}&$\lor$&Logical OR\cr
  383. \+&&&{\tt ::}&|::|&Member of\cr
  384. \+&&&{\tt !}&|!|&Negation\cr
  385. \+&&&{\tt NULL}&|NULL|&Null Pointer\cr
  386. \+&&&{\tt this}&|this|&Object\cr
  387. \+&&&{\tt \%}&|%|&Remainder\cr
  388. \+&&&{\tt tr()}&|tr()|&Translate\cr
  389. \smallskip
  390. \centerline{Table \secno: Special Characters In \pn}
  391. \medskip
  392. Reserved words are set in bold face. As some of these reserved words are also
  393. the names of types, type names that are not specified in \CPLUSPLUS/are also
  394. set in bold face. Type placeholders in template definitions, however, are set in
  395. caligraphic capitals to emphasize that it will be replaced with a real type at
  396. compile time. Variables and class members are set in italics, character strings
  397. are set in a typewriter style with visible spaces. Macro names are also set in
  398. typewriter style. Numeric constants and plain text comments are set in an
  399. upright roman style. Comments containing \CEE/ or mathematics are styled as
  400. such. Code that will be interpreted by the ECMA-262 host environment has no
  401. pretty printing.
  402. \danger With apologies to prof.~Knuth\nfnote{This symbol was introduced in
  403. {\underbar{Computers~\char'046~Typesetting}} (Knuth, 1984) to point out material
  404. that is for ``wizards only.'' It seems to be as appropriate a symbol as any to
  405. point out the darker corners of this program.}, code that is known to be
  406. potentially buggy is flagged with a dangerous bend sign. Some of this code is
  407. buggy due to issues with the code \pn{} depends on, others are things that
  408. should be fixed in \pn{}. Of course, there may also be bugs that have not yet
  409. been noticed or have not been attached to a particular block of code.\endanger
  410. A basic familiarity with literate programming techniques (particularly the
  411. conventions of \cweb{}), Qt, and \CPLUSPLUS/is recommended before altering the
  412. program, but an effort has been made to keep the program understandable for
  413. those who are only interested in studying it.
  414. @** Changes from Version 1{\char`.}4.
  415. \noindent An improper conversion bug when viewing data in Celsius has been
  416. corrected.
  417. Modbus RTU device configurations in which no configuration information was
  418. requested from the device at setup time previously did not collect any
  419. measurements. This has been fixed.
  420. The script binding for |QTime| now features the {\tt valueOf()} method. This is
  421. called implicitly when comparing two time values and allows the results of such
  422. comparisons to be as one might expect.
  423. The script binding for SqlComboBox now supports |findText()|.
  424. @** Changes from Version 1{\char`.}3.
  425. \noindent The {\tt CalendarPopupEdit}, {\tt CoffeeOrderForm}, and
  426. {\tt CoffeeItemPurchaseEditor} classes have been removed.
  427. Data exported in CSV now depends on the current view granularity.
  428. Derived data series by linear spline interpolation now supported.
  429. Both NI DAQmx Base and NI DAQmx are now supported in the same build along
  430. with all other new hardware support.
  431. Changes have been made to improve support for collecting measurements from
  432. multiple devices.
  433. The |GraphView| now supports roast profile translation. A new class has been
  434. added to support this feature.
  435. The new {\tt -c} command line argument allows the load configuration prompt
  436. to be bypassed.
  437. Support for reports loaded into a menu dynamically and for presenting reports
  438. in a menu hierarchy.
  439. The ZoomLog should no longer be editable.
  440. Basic use of |QWebView| has been added. This has been used to enable printing
  441. roast profiles and allows for a larger range of reports than is possible with
  442. the reporting framework used previously. The old reporting framework is still
  443. available for compatability with old configurations, however that code is now
  444. considered to be depreciated.
  445. The |ZoomLog| is now capable of dispaying temperature measurements in various
  446. units.
  447. Ambiguity in library bindings has been eliminated to improve reliability of
  448. Windows builds.
  449. Minor changes to improve coding style consistency.
  450. |QIODevice| has been extended for simpler use with classes that expect string
  451. data.
  452. New convenience properties have been added to the |QDateEdit| script binding.
  453. Database error reporting has been improved.
  454. The {\tt <stretch>} element can now be used in horizontal and vertical layouts.
  455. This can be used to change the distribution of excess space in a layout in ways
  456. that look better than the default handling.
  457. The |MeasurementTimeOffset| filter now works correctly when midnight occurs
  458. during a batch.
  459. The |openEntryRow| signal has been added to |SqlQueryView|. This can be used in
  460. situations where it is not convenient to have a unique identifier in the first
  461. column of the view. An invokable |data()| method was also added to this class.
  462. Preliminary support for Modbus RTU devices has been added.
  463. A new device and logging window configuration system has been introduced which
  464. allows people to edit their device configuration graphically instead of needing
  465. to create new configuration XML documents for the most common types of
  466. configuration change.
  467. Table views expecting numeric data now support entering arithmetical
  468. expressions for evaluation.
  469. @** Changes from Version 1{\char`.}2.
  470. \noindent A vast number of changes have been made to the source code since
  471. version 1.2.
  472. @* New Reporting Framework.
  473. \noindent A new reporting framework has been added to \pn{}, greatly simplifying
  474. the creation of reports. See the Reporting section for full details.
  475. @* New Classes.
  476. \noindent The |AnnotationSpinBox| class has been introduced. This allows manual
  477. entry of numerical annotations. The use of this class is not recommended as it
  478. would almost certainly be better to have this information logged automatically.
  479. The class is provided for situations in which this is prohibitively expensive.
  480. The |FormArray| class has been introduced. This class makes it easy to create
  481. user interface elements consisting of an arbitrary number of duplicated forms.
  482. This depreciates the {\tt CoffeeOrderForm} and {\tt CoffeeItemPurchaseEditor}
  483. classes.
  484. A proxy class named |SqlQueryConnection| has been added. This wraps |QSqlQuery|
  485. and manages its own |QSqlDatabase| connection. The |invalidate()| property has
  486. been added to query objects in the host environment in order to correct database
  487. connection leaks.
  488. Horizontal and vertical scale widgets have been added to improve the user
  489. experience when filling out cupping forms.
  490. @* Modified Classes.
  491. \noindent The |XMLOutput|, |XMLInput|, |CSVOutput|, and |ZoomLog| classes have
  492. been modified along with the XML format used by \pn{} to support saving and
  493. restoring multiple data series in a single file.
  494. Inserting measurements into a model has been optimized for the most common use.
  495. A large reduction in CPU utilization from \pn{} should be observed.
  496. @* New Configuration Options.
  497. \noindent Several additional methods have been added to the host environment for
  498. working with tables created by {\tt <sqltablearray>} elements. The |data()| and
  499. |setData()| methods can be used for examining and manipulating data in table
  500. cells. The |quotedColumnArray()| method can be used to obtain arrays suitable
  501. for insertion in {\tt text[]} fields of a database. The |bindableColumnArray()|
  502. and |bindableQuotedColumnArray()| methods produce values appropriate for binding
  503. to query placeholders.
  504. The |sqlToArray()| method has been modified to strip quote characters from the
  505. start and end of each array element if that element is quoted.
  506. It is now possible to change the application default fonts from the host
  507. environment.
  508. There are new layout options available. Grid layouts and stacked layouts are now
  509. available. It is also possible to assign an ID to any layout for manipulation
  510. from script code.
  511. It is now possible to specify that a combo box should be editable without adding
  512. script code.
  513. It is now possible to apply validators to line edits through configuration
  514. element attributes. Numeric, integer, and regular expression validators are
  515. supported.
  516. Support for Qt stylesheets has been added. Please use this sparingly.
  517. |QXmlStreamWriter| and |QXmlStreamReader| can now be used from within the host
  518. environment.
  519. @* New Versions of Qt.
  520. \noindent \pn{} has been linked against Qt 4.6.2 and is tested as working on Mac
  521. OS X 10.6.
  522. @* Bug fixes.
  523. \noindent A change in the |Application| class eliminates a problem with
  524. segmentation faults in the Linux build.
  525. @** Changes from Version 1{\char`.}1.
  526. \noindent The code has been tested when linked against NI-DAQmxBase 3.2 for use
  527. with a NI USB-9162 Hi-Speed USB Carrier. No code changes were required and no
  528. text appears on the console.
  529. NI-DAQmxBase is linked at run time rather than compile time. Also, nidaqmxbase.h
  530. is no longer required.
  531. It is now possible to inspect a |Measurement| object to determine the unit used
  532. for the measurement or create a new |Measurement| converted to a different unit.
  533. Recent versions of Qt have corrected bugs in the graphics view architecture.
  534. This has allowed some of the kludges of previous versions to be removed. The use
  535. of Qt 4.4.3 is now recommended.
  536. The configuration system has been changed significantly. The preferred method of
  537. describing the user interface is with an XML description with application data
  538. flow still defined through script fragments. Most configurations from version
  539. 1.1 should continue to work when wrapped in {\tt <application><program>} XML
  540. elements, however the new configuration system makes it easier to produce far
  541. more complex and featureful configurations. Work on this portion of the code is
  542. not complete and requires additional documentation which is beyond the scope of
  543. the source code documentation.
  544. Several new classes have been added to the host environment.
  545. The |Application| class now manages a connection to a PostgreSQL database which
  546. other classes and the host environment can use to interact with a database.
  547. The {\tt RoastControlWindow} class used in version 1.0 and depreciated in
  548. version 1.1 has been removed.
  549. @* Bug fixes.
  550. \noindent The |GraphView| class now scales the graph to fit the viewport when
  551. the widget is resized. This was not the case prior to version 1.1.3.
  552. @** Changes from Version 1{\char`.}0.
  553. \noindent The most substantial change from \pn{} version 1.0 is the introduction
  554. of an ECMA-262 host environment intended for setting up the user interface and
  555. program data flow. The old {\tt RoastControlWindow} class was depreciated.
  556. This host environment provides access to most of the classes in \pn{} and a
  557. selection of classes from Qt. These classes can be used in scripts to the extent
  558. needed to prevent feature regressions. The example scripts provided should work,
  559. however attempts to go beyond what is provided by these examples may require
  560. modification to the source code.
  561. @* Bug fixes.
  562. \noindent The |TimerDisplay| class had a bug that would cause three error
  563. messages to appear on the console for every |TimerDisplay| object instantiated.
  564. This bug was fixed in version 1.0.6.
  565. When the user interface and data flow was hard coded, other parts of the program
  566. could make assumptions that are not necessarily true in different configurations
  567. without being detected. Moving from a configuration with one channel on the DAQ
  568. to a configuration with two revealed faulty assumptions in two classes.
  569. The |DAQImplementation| class used a constant 1 instead of the number of
  570. channels to specify the size of the measurement buffer. The result of this was
  571. that no measurements would be generated when more than one channel was set up.
  572. This bug was fixed in version 1.0.7.
  573. The |XMLOutput| class failed to handle rows with no value in the temperature
  574. column for rows with values in any column after the temperature column. Such
  575. rows were never produced in version 1.0 but can be produced now. Such rows were
  576. frequently produced during development. This bug was fixed in version 1.0.8.
  577. @** Introduction.
  578. \noindent A common tool in the craft of coffee roasting is the data logger.
  579. Perhaps the most commonly used of these fall into the category of manual data
  580. loggers which require the roaster to use paper and a writing utensil,
  581. periodically recording measurements and noting control changes and observations
  582. of interest as needed.
  583. While there are many benefits to recording roast data\nfnote{Torrey Lee, Stephan
  584. Diedrich, Carl Staub, and Jack Newall, ``How to Obtain Excellence with Drum
  585. Roasters'' (2002) {\it Specialty Coffee Association of America 14$^{th}$ Annual
  586. Conference and Exhibition}}, there are a number of limitations to the manual
  587. approach; maintaining the records in a useful order is time consuming and error
  588. prone, it is difficult to work with aggregates of such records, and the
  589. attention required to log the data by hand can distract from the roasting. Using
  590. a computer with automatic data logging software designed with coffee roasting in
  591. mind can reduce or eliminate these deficiencies. \pn{} is one such program.
  592. The file {\tt \filebase.w} contains both \CPLUSPLUS/source code and the
  593. documentation for that code. This file is intended to be processed by
  594. \cweb\nfnote{Donald E. Knuth and Silvio Levy, ``The \cweb{} System of Structured
  595. Documentation'' (1994)}~to produce source code for your compiler and plain
  596. \TeX{}\nfnote{\TeX{} (pronounced $\tau\epsilon\chi$) is a trademark of the
  597. American Mathematical Society.} documentation that can be used to generate a PDF
  598. document for gorgeous printable documentation. These generated files may have
  599. been distributed with your copy of {\tt \filebase.w} for convenience.
  600. Changes to the program can be made in three ways. \cweb{} provides a patching
  601. mechanism which can be used to experiment with the code without risk of
  602. clobbering it. Instructions for the construction of such a change file can be
  603. found in the \cweb{} documentation. Adding the name of the change file to the
  604. invocation of {\tt ctangle} and {\tt cweave} will incorporate that change
  605. seamlessly in both source and documentation files. A section is provided at the
  606. end of this program for use with this mechanism in the case that new sections
  607. must be added. Another way to create persistent modifications is to alter
  608. {\tt \filebase.w} however this may make it more difficult to use changes with
  609. future versions of the software. Changes should not be made to
  610. {\tt \filebase.cpp} if these changes are expected to persist. Finally, it is
  611. possible to make many changes to how the program looks and behaves by creating a
  612. new configuration document for the program to load. Modifications made in this
  613. way do not even require recompiling the software. Examples that can serve as a
  614. starting point for such customizations are provided with \pn{}.
  615. \pn{} is a work in progress. There are several portions of the documentation
  616. that contain suggestions for future improvement. These notes provide clues for
  617. my future development plans. Naturally, if you have needs which are not quite
  618. addressed by this program, you should feel free to modify the code to suit your
  619. needs. Hopefully this will be easy to do.
  620. In the spirit of Benjamin Franklin\nfnote{``\dots as we enjoy great advantages
  621. from the inventions of others, we should be glad of an opportunity to serve
  622. others by any invention of ours; and this we should do freely and
  623. generously.''
  624. --- Benjamin Franklin, \underbar{The Private Life of the Late
  625. Benjamin Franklin, LL.D.~Originally
  626. Written By Himself, And Now}\par\noindent
  627. \underbar{Translated From The French} (1793)}, \pn{} is shared
  628. with minimal restriction (see the license after the table of contents for legal
  629. requirements). Libraries used by \pn{} may have other restrictions. Before
  630. undertaking to distribute a binary created from this code, you may want to
  631. either determine your rights with regard to these libraries or modify the
  632. program to remove them.
  633. The following is an overview of the structure of \pn:
  634. @d PROGRAM_NAME "Typica"
  635. @c
  636. @<Header files to include@>@/
  637. @<Class declarations@>@/
  638. @<Function prototypes for scripting@>@/
  639. @<Class implementations@>@/
  640. @<Functions for scripting@>@/
  641. @<The main program@>
  642. #include "moc_typica.cpp"
  643. @ \pn{} is made of a number of distinct classes.
  644. @<Class implementations@>=
  645. @<NodeInserter implementation@>@/
  646. @<Measurement implementation@>@/
  647. @<DAQ Implementation@>@/
  648. @<FakeDAQ Implementation@>@/
  649. @<Channel Implementation@>@/
  650. @<TemperatureDisplay Implementation@>@/
  651. @<MeasurementTimeOffset Implementation@>@/
  652. @<ZeroEmitter Implementation@>@/
  653. @<MeasurementAdapter Implementation@>@/
  654. @<GraphView Implementation@>@/
  655. @<ZoomLog Implementation@>@/
  656. @<MeasurementModel Implementation@>@/
  657. @<AnnotationButton Implementation@>@/
  658. @<AnnotationSpinBox Implementation@>@/
  659. @<TimerDisplay Implementation@>@/
  660. @<PackLayout Implementation@>@/
  661. @<SceneButton Implementation@>@/
  662. @<WidgetDecorator Implementation@>@/
  663. @<LogEditWindow Implementation@>@/
  664. @<XMLOutput Implementation@>@/
  665. @<XMLInput Implementation@>@/
  666. @<CSVOutput Implementation@>@/
  667. @<SaltModel Implementation@>@/
  668. @<SqlComboBox Implementation@>@/
  669. @<SqlComboBoxDelegate Implementation@>@/
  670. @<Application Implementation@>@/
  671. @<SqlConnectionSetup implementation@>@/
  672. @<SqlQueryView implementation@>@/
  673. @<SqlQueryConnection implementation@>@/
  674. @<ReportTable implementation@>@/
  675. @<FormArray implementation@>@/
  676. @<ScaleControl implementation@>@/
  677. @<IntensityControl implementation@>@/
  678. @<ThresholdDetector Implementation@>@/
  679. @<PortSelector implementation@>@/
  680. @<BaudSelector implementation@>@/
  681. @<ParitySelector implementation@>@/
  682. @<FlowSelector implementation@>@/
  683. @<StopSelector implementation@>@/
  684. @<ModbusConfigurator implementation@>@/
  685. @<ShortHexSpinBox implementation@>@/
  686. @<ModbusRTUDevice implementation@>@/
  687. @<DeviceTreeModelNode implementation@>@/
  688. @<DeviceTreeModel implementation@>@/
  689. @<BasicDeviceConfigurationWidget implementation@>@/
  690. @<DeviceConfigurationWindow implementation@>@/
  691. @<Ni9211TcConfWidget implementation@>@/
  692. @<NiDaqMxBase9211ConfWidget implementation@>@/
  693. @<NiDaqMxBaseDriverConfWidget implementation@>@/
  694. @<ReportAction implementation@>@/
  695. @<NumericDelegate implementation@>@/
  696. @<NiDaqMxDriverConfWidget implementation@>@/
  697. @<NiDaqMx9211ConfWidget implementation@>@/
  698. @<NiDaqMxTc01ConfWidget implementation@>@/
  699. @<ModbusRtuPortConfWidget implementation@>@/
  700. @<ModbusRtuDeviceConfWidget implementation@>@/
  701. @<ModbusRtuDeviceTPvConfWidget implementation@>@/
  702. @<ModbusRtuDeviceTSvConfWidget implementation@>@/
  703. @<RoasterConfWidget implementation@>@/
  704. @<AnnotationButtonConfWidget implementation@>@/
  705. @<NoteSpinConfWidget implementation@>@/
  706. @<LinearCalibrator Implementation@>@/
  707. @<LinearSplineInterpolator Implementation@>@/
  708. @<LinearSplineInterpolationConfWidget implementation@>@/
  709. @<TranslationConfWidget implementation@>@/
  710. @ A few headers are required for various parts of \pn{}. These allow the use of
  711. various Qt modules.
  712. @<Header files to include@>=
  713. #include <QtCore>
  714. #include <QtGui>
  715. #include <QtScript>
  716. #include <QtScriptTools>
  717. #include <QtXml>
  718. #include <QtSql>
  719. #include <QtDebug>
  720. #include <QtXmlPatterns>
  721. #include <QtWebKit>
  722. @** The Scripting Engine.
  723. \noindent The main enhancement of \pn{} version 1.1 is the introduction of a
  724. scriptable environment. This change allows people to easily customize \pn{}
  725. without having to alter the program code. Instead, the user interface and
  726. program data flow is set up with a small script that runs in an ECMA-262 host
  727. environment\nfnote{Standard ECMA-262, 3$^{\rm{rd}}$ Edition\par\hbox{\indent%
  728. \pdfURL{%
  729. http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf}%
  730. {http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf}}}
  731. which requires
  732. significantly less expertise to modify than \pn{} itself. Such a scripting
  733. environment will be familiar to anybody with experience using JavaScript on web
  734. pages or ActionScript in Flash. \pn{}'s configuration system was later updated
  735. to support running several script fragments found in an XML configuration
  736. document.
  737. Most of the application classes are available from the scripting environment.
  738. The functions that make this possible are presented along with the classes. A
  739. selection of classes provided by Qt are also available. These are presented
  740. here.
  741. This chunk provides two |QScriptValue| objects which are used in other sections
  742. appended to this chunk.
  743. @<Set up the scripting engine@>=
  744. QScriptEngine *engine = new QScriptEngine;
  745. QScriptValue constructor;
  746. QScriptValue value;
  747. @ A common task when working with objects created from a script is finding the
  748. object a method is called on from the current script context. The code for this
  749. is simple, but lengthy. This is shortened with the use of a template function
  750. that obtains the object in question and casts it to the appropriate type. If an
  751. incorrect type is specified, a null pointer or similarly invalid value will be
  752. returned.
  753. @<Functions for scripting@>=
  754. template<class TYPE> TYPE@, getself(QScriptContext *context)
  755. {
  756. TYPE@, self = qobject_cast<TYPE>(context->thisObject().toQObject());
  757. return self;
  758. }
  759. template<> QTime getself(QScriptContext *context)
  760. {
  761. QTime self = context->thisObject().toVariant().toTime();
  762. return self;
  763. }
  764. template<> SqlQueryConnection* getself(QScriptContext *context)
  765. {
  766. SqlQueryConnection *self =@|
  767. (SqlQueryConnection *)qscriptvalue_cast<void *>(context->thisObject());
  768. return self;
  769. }
  770. template<> QXmlQuery* getself(QScriptContext *context)
  771. {
  772. QXmlQuery *self =
  773. (QXmlQuery *)qscriptvalue_cast<void *>(context->thisObject());
  774. return self;
  775. }
  776. template<> QXmlStreamWriter* getself(QScriptContext *context)
  777. {
  778. QXmlStreamWriter *self = @|
  779. (QXmlStreamWriter *)qscriptvalue_cast<void *>(context->thisObject());
  780. return self;
  781. }
  782. template<> QXmlStreamReader* getself(QScriptContext *context)
  783. {
  784. QXmlStreamReader *self = @|
  785. (QXmlStreamReader *)qscriptvalue_cast<void *>(context->thisObject());
  786. return self;
  787. }
  788. @ Another common task is obtaining the arguments of a method call from the
  789. script context and casting these arguments to the proper type. This is once
  790. again done with templates.
  791. @<Functions for scripting@>=
  792. template<class TYPE> TYPE@, argument(int arg, QScriptContext *context)
  793. {
  794. TYPE@, argument = qobject_cast<TYPE>(context->argument(arg).toQObject());
  795. return argument;
  796. }
  797. template<> QString argument(int arg, QScriptContext *context)
  798. {
  799. return context->argument(arg).toString();
  800. }
  801. template<> QVariant argument(int arg, QScriptContext *context)
  802. {
  803. return context->argument(arg).toVariant();
  804. }
  805. template<> int argument(int arg, QScriptContext *context)
  806. {
  807. return context->argument(arg).toInt32();
  808. }
  809. template<> SqlQueryConnection* argument(int arg, QScriptContext *context)
  810. {
  811. return (SqlQueryConnection *)
  812. qscriptvalue_cast<void *>(context->argument(arg));
  813. }
  814. template<> QModelIndex argument(int arg, QScriptContext *context)
  815. {
  816. return qscriptvalue_cast<QModelIndex>(context->argument(arg));
  817. }
  818. @ The scripting engine is informed of a number of classes defined elsewhere in
  819. the program. Code related to scripting these classes is grouped with the code
  820. implementing the classes. Additionally, there are several classes from Qt which
  821. are also made scriptable. These are detailed in the following sections.
  822. @* Exposing an Object Hierarchy to the Host Environment.
  823. \noindent While QtScript does a generally acceptable job of exposing
  824. information about objects that are available through the meta-object system,
  825. some methods require special handling in order to make them fully available to
  826. the host environment. Several functions are provided which provide a
  827. |QScriptValue| with these additional properties. The functions providing these
  828. properties also call other functions providing the properties of any base
  829. classes. In this way, any additional functionality provided to the host
  830. environment for a base class is also provided for any class that inherits that
  831. base class.
  832. For example, a |QBoxLayout| created in a script will have properties from
  833. |QLayout| which in turn brings in properties from |QObject| and |QLayoutItem|.
  834. A |QMainWindow| would bring in properties from |QWidget| which would bring in
  835. properties from |QObject|.
  836. Neither all methods nor all Qt classes are available from the host environment.
  837. When adding functionality to the host environment, there is a priority on
  838. classes and methods that are useful for \pn{}'s intended purpose.
  839. @* Base Classes.
  840. \noindent There are a few classes that are base classes of classes exposed to
  841. the scripting engine. There is no need for the host environment to allow the
  842. creation of these base classes and there may not be methods that must be added
  843. as properties in derived classes, however stub functions are provided so that
  844. in the event that a method from one of these base classes is needed later, it
  845. can be added once for all derived classes.
  846. The first of these is |QObject|.
  847. @<Function prototypes for scripting@>=
  848. void setQObjectProperties(QScriptValue value, QScriptEngine *engine);
  849. @ As there are no properties that need to be set for this class and as this
  850. class does not inherit any other class, nothing needs to be done in this method.
  851. It will, however, be called by subclasses in case this changes in the future.
  852. @<Functions for scripting@>=
  853. void setQObjectProperties(QScriptValue, QScriptEngine *)
  854. {
  855. /* Nothing needs to be done here. */
  856. }
  857. @ The same can be done for |QPaintDevice| and |QLayoutItem|.
  858. @<Function prototypes for scripting@>=
  859. void setQPaintDeviceProperties(QScriptValue value, QScriptEngine *engine);
  860. void setQLayoutItemProperties(QScriptValue value, QScriptEngine *engine);
  861. @ The implementations are similarly empty.
  862. @<Functions for scripting@>=
  863. void setQPaintDeviceProperties(QScriptValue, QScriptEngine *)
  864. {
  865. /* Nothing needs to be done here. */
  866. }
  867. void setQLayoutItemProperties(QScriptValue, QScriptEngine *)
  868. {
  869. /* Nothing needs to be done here. */
  870. }
  871. @* Scripting QWidget.
  872. \noindent The first interesting class in this hierarchy is |QWidget|. This is
  873. mainly used as a base class for other widgets and in such a role it is not
  874. particularly interesting. It is, however, possible to apply a layout to a
  875. |QWidget| and use that to manage the size and position of one or more child
  876. widgets. A few functions are used to accomplish this.
  877. @<Function prototypes for scripting@>=
  878. void setQWidgetProperties(QScriptValue value, QScriptEngine *engine);
  879. QScriptValue constructQWidget(QScriptContext *context, QScriptEngine *engine);
  880. QScriptValue QWidget_setLayout(QScriptContext *context, QScriptEngine *engine);
  881. QScriptValue QWidget_activateWindow(QScriptContext *context,
  882. QScriptEngine *engine);
  883. @ The script constructor must be passed to the scripting engine.
  884. @<Set up the scripting engine@>=
  885. constructor = engine->newFunction(constructQWidget);
  886. value = engine->newQMetaObject(&QWidget::staticMetaObject, constructor);
  887. engine->globalObject().setProperty("QWidget", value);
  888. @ The constructor creates a script value, but uses another function to add
  889. properties that wrap methods we want to make available to subclasses. Note that
  890. properties of the base classes are added before properties of this class. This
  891. procedure ensures that properties added from base classes can be be replaced in
  892. subclasses.
  893. @<Functions for scripting@>=
  894. QScriptValue constructQWidget(QScriptContext *, QScriptEngine *engine)
  895. {
  896. QScriptValue object = engine->newQObject(new QWidget);
  897. setQWidgetProperties(object, engine);
  898. return object;
  899. }
  900. void setQWidgetProperties(QScriptValue value, QScriptEngine *engine)
  901. {
  902. setQObjectProperties(value, engine);
  903. setQPaintDeviceProperties(value, engine);
  904. value.setProperty("setLayout", engine->newFunction(QWidget_setLayout));
  905. value.setProperty("activateWindow",
  906. engine->newFunction(QWidget_activateWindow));
  907. }
  908. @ This just leaves the property implementations. |QWidget::setLayout()| takes
  909. one argument, a |QLayout| and returns |void|. This wrapper duplicates this
  910. interface. |QWidget::activateWindow()| takes no arguments and returns nothing
  911. meaningful.
  912. @<Functions for scripting@>=
  913. QScriptValue QWidget_setLayout(QScriptContext *context, QScriptEngine *)
  914. {
  915. if(context->argumentCount() == 1)
  916. {
  917. QWidget *self = getself<QWidget *>(context);
  918. QLayout *layout = argument<QLayout *>(0, context);
  919. if(layout)
  920. {
  921. self->setLayout(layout);
  922. }
  923. else
  924. {
  925. context->throwError("Incorrect argument type passed to "@|
  926. "QWidget::setLayout(). This method requires "@|
  927. "a QLayout.");
  928. }
  929. }
  930. else
  931. {
  932. context->throwError("Incorrect number of arguments passed to "@|
  933. "QWidget::setLayout(). This method takes one "@|
  934. "QLayout as an argument.");
  935. }
  936. return QScriptValue();
  937. }
  938. QScriptValue QWidget_activateWindow(QScriptContext *context,
  939. QScriptEngine *)
  940. {
  941. QWidget *self = getself<QWidget *>(context);
  942. self->activateWindow();
  943. return QScriptValue();
  944. }
  945. @* Scripting QMainWindow.
  946. \noindent Rather than directly exposing |QMainWindow| to the scripting engine,
  947. we expose a class derived from |QMainWindow| with a minor change allowing the
  948. script to be notified when the window is about to be closed.
  949. This allows us to save settings for objects populating the window. Close
  950. handlers can be established by connecting to the |aboutToClose()| signal which
  951. is emitted in the |closeEvent()| handler. The close event is always accepted
  952. after the script has had a chance to respond, so this cannot be used to present
  953. an, ``Are you sure?'' message without additional modification.
  954. Slots are also provided for saving the size and position of the window to
  955. settings and restoring the window geometry from these settings.
  956. As of version 1.4 window geometry management is provided for all windows. The
  957. |restoreSizeAndPosition()| and |saveSizeAndPosition()| methods should be
  958. considered depreciated.
  959. @<Class declarations@>=
  960. class ScriptQMainWindow : public QMainWindow@/
  961. {@t\1@>@/
  962. Q_OBJECT@;@/
  963. public:@/
  964. ScriptQMainWindow();@/
  965. @t\4@>public slots@t\kern-3pt@>:@/
  966. void show();
  967. void saveSizeAndPosition(const QString &key);
  968. void restoreSizeAndPosition(const QString &key);
  969. void displayStatus(const QString &message = QString());@/
  970. protected:@/
  971. void closeEvent(QCloseEvent *event);
  972. void showEvent(QShowEvent *event);@/
  973. signals:@/
  974. void aboutToClose(void);@t\2@>@/
  975. }@t\kern-3pt@>;
  976. @ The implementation of these functions is simple.
  977. @<Functions for scripting@>=
  978. ScriptQMainWindow::ScriptQMainWindow()@+: QMainWindow(NULL)@/
  979. {
  980. /* Nothing needs to be done here. */
  981. }
  982. void ScriptQMainWindow::saveSizeAndPosition(const QString &key)
  983. {
  984. QSettings settings;
  985. settings.beginGroup(key);
  986. settings.setValue("pos", pos());
  987. settings.setValue("size", size());
  988. settings.endGroup();
  989. }
  990. void ScriptQMainWindow::restoreSizeAndPosition(const QString &key)
  991. {
  992. QSettings settings;
  993. settings.beginGroup(key);
  994. if(settings.contains("size"))
  995. {
  996. resize(settings.value("size").toSize());
  997. }
  998. if(settings.contains("pos"))
  999. {
  1000. move(settings.value("pos").toPoint());
  1001. }
  1002. settings.endGroup();
  1003. }
  1004. void ScriptQMainWindow::displayStatus(const QString &message)
  1005. {
  1006. statusBar()->showMessage(message);
  1007. }
  1008. void ScriptQMainWindow::showEvent(QShowEvent *event)
  1009. {
  1010. if(!event->spontaneous())
  1011. {
  1012. @<Restore window geometry@>@;
  1013. event->accept();
  1014. }
  1015. else
  1016. {
  1017. event->ignore();
  1018. }
  1019. }
  1020. void ScriptQMainWindow::show()
  1021. {
  1022. QMainWindow::show();
  1023. }
  1024. void ScriptQMainWindow::closeEvent(QCloseEvent *event)
  1025. {
  1026. emit aboutToClose();
  1027. @<Save window geometry@>@;
  1028. event->accept();
  1029. }
  1030. @ Window geometry management from version 1.4 on makes use of the window ID to
  1031. produce an appropriate QSettings key. This decision relies on the ID being set
  1032. before any show or close events are received and it relies on every distinct
  1033. type of window having a unique ID. If this is not the case then other things
  1034. are likely very broken. Note that with this approach multiple instances of the
  1035. same type of window will use the same key. This may not be ideal in all cases,
  1036. but further refinements can be produced if necessary.
  1037. @<Save window geometry@>=
  1038. QSettings settings;
  1039. settings.setValue(QString("geometries/%1").arg(objectName()), saveGeometry());
  1040. @ Restoring saved geometry is performed similarly to saving it.
  1041. @<Restore window geometry@>=
  1042. QSettings settings;
  1043. restoreGeometry(settings.value(QString("geometries/%1").arg(objectName())).
  1044. toByteArray());
  1045. @ Three functions are required to obtain the required functionality from a
  1046. script. A fourth adds properties for the object hierarchy.
  1047. @<Function prototypes for scripting@>=
  1048. QScriptValue constructQMainWindow(QScriptContext *context,
  1049. QScriptEngine *engine);
  1050. QScriptValue QMainWindow_setCentralWidget(QScriptContext *context,@|
  1051. QScriptEngine *engine);
  1052. QScriptValue QMainWindow_menuBar(QScriptContext *context,
  1053. QScriptEngine *engine);
  1054. void setQMainWindowProperties(QScriptValue value, QScriptEngine *engine);
  1055. @ Of these, the engine only needs to be informed of the constructor initially.
  1056. @<Set up the scripting engine@>=
  1057. constructor = engine->newFunction(constructQMainWindow);
  1058. value = engine->newQMetaObject(&ScriptQMainWindow::staticMetaObject,
  1059. constructor);
  1060. engine->globalObject().setProperty("QMainWindow", value);
  1061. @ The constructor calls a function to add the additional properties to the
  1062. newly created value.
  1063. @<Functions for scripting@>=
  1064. QScriptValue constructQMainWindow(QScriptContext *, QScriptEngine *engine)
  1065. {
  1066. QScriptValue object = engine->newQObject(new ScriptQMainWindow);
  1067. setQMainWindowProperties(object, engine);
  1068. return object;
  1069. }
  1070. void setQMainWindowProperties(QScriptValue value, QScriptEngine *engine)
  1071. {
  1072. setQWidgetProperties(value, engine);
  1073. value.setProperty("setCentralWidget",
  1074. engine->newFunction(QMainWindow_setCentralWidget));
  1075. value.setProperty("menuBar", engine->newFunction(QMainWindow_menuBar));
  1076. }
  1077. @ The |"setCentralWidget"| property is used for setting a widget in the main
  1078. area of the window. In \pn{} this will usually be a |QSplitter| object, but it
  1079. could also be a bare |QWidget| with a layout managing multiple widgets or a
  1080. custom widget defined in a local change. This is a simple wrapper around
  1081. |QMainWindow::setCentralWidget()|.
  1082. @<Functions for scripting@>=
  1083. QScriptValue QMainWindow_setCentralWidget(QScriptContext *context,
  1084. QScriptEngine *)
  1085. {
  1086. if(context->argumentCount() == 1)
  1087. {
  1088. QMainWindow *self = getself<QMainWindow *>(context);
  1089. QWidget *widget = argument<QWidget *>(0, context);
  1090. if(widget)
  1091. {
  1092. self->setCentralWidget(widget);
  1093. }
  1094. else
  1095. {
  1096. context->throwError("Incorrect argument type passed to "@|
  1097. "QMainWindow::setCentralWidget(). This "@|
  1098. "method requires a QWidget.");
  1099. }
  1100. }
  1101. else
  1102. {
  1103. context->throwError("Incorrect number of arguments passed to "@|
  1104. "QMainWindow::setCentralWidget(). This method "@|
  1105. "takes one QWidget as an argument.");
  1106. }
  1107. return QScriptValue();
  1108. }
  1109. @ The |"menuBar"| property requires that we expose |QMenuBar| to the scripting
  1110. environment in a limited fashion. We don't need to allow scripts to create a
  1111. new menu bar as it can be obtained from the window, however to add the menus to
  1112. the menu bar, we need to add a property to the |QMenuBar| object before passing
  1113. it back.
  1114. @<Functions for scripting@>=
  1115. QScriptValue QMainWindow_menuBar(QScriptContext *context, QScriptEngine *engine)
  1116. {
  1117. QScriptValue object;
  1118. if(context->argumentCount() == 0)
  1119. {
  1120. QMainWindow *self = getself<@[QMainWindow *@]>(context);
  1121. QMenuBar *bar = self->menuBar();
  1122. object = engine->newQObject(bar);
  1123. setQMenuBarProperties(object, engine);
  1124. }
  1125. else
  1126. {
  1127. context->throwError("Incorrect number of arguments passed to "@|
  1128. "QMainWindow::menuBar(). This method takes no "@|
  1129. "arguments.");
  1130. }
  1131. return object;
  1132. }
  1133. @ The previous function is the only place a new |QMenuBar| is created through
  1134. the host environment. Two functions are used in handling this object creation.
  1135. @<Function prototypes for scripting@>=
  1136. void setQMenuBarProperties(QScriptValue value, QScriptEngine *engine);
  1137. QScriptValue QMenuBar_addMenu(QScriptContext *context, QScriptEngine *engine);
  1138. @ The first of these adds the appropriate properties to the newly created
  1139. object.
  1140. @<Functions for scripting@>=
  1141. void setQMenuBarProperties(QScriptValue value, QScriptEngine *engine)
  1142. {
  1143. setQWidgetProperties(value, engine);
  1144. value.setProperty("addMenu", engine->newFunction(QMenuBar_addMenu));
  1145. }
  1146. @ This function can be used to add new menus to a menu bar. In order to do
  1147. anything with the newly created menus, two properties are added to the |QMenu|
  1148. objects which allow actions to be added as menu items and allow separators to be
  1149. placed between groups of menu items.
  1150. At the time of this writing, there are three |QMenuBar::addMenu()| methods. This
  1151. function wraps |QMenu* QMenuBar::addMenu(const QString &title)|.
  1152. @<Functions for scripting@>=
  1153. QScriptValue QMenuBar_addMenu(QScriptContext *context, QScriptEngine *engine)
  1154. {
  1155. QScriptValue object;
  1156. if(context->argumentCount() == 1)
  1157. {
  1158. QMenuBar *self = getself<@[QMenuBar *@]>(context);
  1159. QString title = argument<QString>(0, context);
  1160. object = engine->newQObject(self->addMenu(title));
  1161. setQMenuProperties(object, engine);
  1162. }
  1163. else
  1164. {
  1165. context->throwError("Incorrect number of arguments passed to "@|
  1166. "QMenuBar::addMenu(). This method takes one "@|
  1167. "string as an argument.");
  1168. }
  1169. return object;
  1170. }
  1171. @ These three functions allow adding items to the menu and adding separators
  1172. between groups of items.
  1173. @<Function prototypes for scripting@>=
  1174. void setQMenuProperties(QScriptValue value, QScriptEngine *engine);
  1175. QScriptValue QMenu_addAction(QScriptContext *context, QScriptEngine *engine);
  1176. QScriptValue QMenu_addSeparator(QScriptContext *context, QScriptEngine *engine);
  1177. @ The first of these add properties to newly created |QMenu| objects.
  1178. @<Functions for scripting@>=
  1179. void setQMenuProperties(QScriptValue value, QScriptEngine *engine)
  1180. {
  1181. setQWidgetProperties(value, engine);
  1182. value.setProperty("addAction", engine->newFunction(QMenu_addAction));
  1183. value.setProperty("addSeparator", engine->newFunction(QMenu_addSeparator));
  1184. }
  1185. @ These functions are simple wrappers around |QMenu| methods.
  1186. @<Functions for scripting@>=
  1187. QScriptValue QMenu_addAction(QScriptContext *context, QScriptEngine *)
  1188. {
  1189. if(context->argumentCount() == 1)
  1190. {
  1191. QMenu *self = getself<@[QMenu *@]>(context);
  1192. QAction *action = argument<QAction *>(0, context);
  1193. if(action)
  1194. {
  1195. self->addAction(action);
  1196. }
  1197. else
  1198. {
  1199. context->throwError("Incorrect argument type passed to "@|
  1200. "QMenu::addAction(). This method requires a "@|
  1201. "QAction.");
  1202. }
  1203. }
  1204. else
  1205. {
  1206. context->throwError("Incorrect number of arguments passed to "@|
  1207. "QMenu::addAction(). This method takes one "@|
  1208. "QAction as an argument.");
  1209. }
  1210. return QScriptValue();
  1211. }
  1212. QScriptValue QMenu_addSeparator(QScriptContext *context, QScriptEngine *)
  1213. {
  1214. if(context->argumentCount() == 0)
  1215. {
  1216. QMenu *self = getself<@[QMenu *@]>(context);
  1217. self->addSeparator();
  1218. }
  1219. else
  1220. {
  1221. context->throwError("Incorrect number of arguments passed to "@|
  1222. "QMenu::addSeparator(). This method takes no "@|
  1223. "arguments.");
  1224. }
  1225. return QScriptValue();
  1226. }
  1227. @* Scripting QFrame.
  1228. \noindent |QFrame| is another class for which little needs to be done. It exists
  1229. as a subclass of |QWidget| and a superclass for |QSplitter|, |QLCDNumber|, and
  1230. |QAbstractScrollArea| among other classes.
  1231. @<Function prototypes for scripting@>=
  1232. void setQFrameProperties(QScriptValue value, QScriptEngine *engine);
  1233. QScriptValue constructQFrame(QScriptContext *context, QScriptEngine *engine);
  1234. @ The constructor must be passed to the scripting engine.
  1235. @<Set up the scripting engine@>=
  1236. constructor = engine->newFunction(constructQFrame);
  1237. value = engine->newQMetaObject(&QFrame::staticMetaObject, constructor);
  1238. engine->globalObject().setProperty("QFrame", value);
  1239. @ The implementation of these functions should seem familiar.
  1240. @<Functions for scripting@>=
  1241. QScriptValue constructQFrame(QScriptContext *, QScriptEngine *engine)
  1242. {
  1243. QScriptValue object = engine->newQObject(new QFrame);
  1244. setQFrameProperties(object, engine);
  1245. return object;
  1246. }
  1247. void setQFrameProperties(QScriptValue value, QScriptEngine *engine)
  1248. {
  1249. setQWidgetProperties(value, engine);
  1250. }
  1251. @* Scripting QLabel.
  1252. \noindent When constructing an interface wholly or partially through dynamic
  1253. means rather than entirely through the XML configuration document it can
  1254. sometimes be desirable to construct |QLabel| instances. This is usually used
  1255. to provide a very small amount of text.
  1256. @<Function prototypes for scripting@>=
  1257. void setQLabelProperties(QScriptValue value, QScriptEngine *engine);
  1258. QScriptValue constructQLabel(QScriptContext *context, QScriptEngine *engine);
  1259. @ The constructor must be passed to the scripting engine.
  1260. @<Set up the scripting engine@>=
  1261. constructor = engine->newFunction(constructQLabel);
  1262. value = engine->newQMetaObject(&QLabel::staticMetaObject, constructor);
  1263. engine->globalObject().setProperty("QLabel", value);
  1264. @ In the constructor we allow an optional argument to specify the text of the
  1265. label.
  1266. @<Functions for scripting@>=
  1267. QScriptValue constructQLabel(QScriptContext *context, QScriptEngine *engine)
  1268. {
  1269. QString text;
  1270. if(context->argumentCount() == 1)
  1271. {
  1272. text = argument<QString>(0, context);
  1273. }
  1274. QScriptValue object = engine->newQObject(new QLabel(text));
  1275. setQLabelProperties(object, engine);
  1276. return object;
  1277. }
  1278. void setQLabelProperties(QScriptValue value, QScriptEngine *engine)
  1279. {
  1280. setQFrameProperties(value, engine);
  1281. }
  1282. @* Scripting QSplitter.
  1283. \noindent The |QSplitter| class is one of the main classes used for user
  1284. interface object layout in \pn{}. To provide this class to the scripting engine,
  1285. we provide five functions: a constructor, a method for adding widgets to the
  1286. splitter, a method for saving the size of each widget in the splitter, a
  1287. method for restoring these saved sizes, and a function for adding these methods
  1288. as properties of newly created |QSplitter| objects.
  1289. @<Function prototypes for scripting@>=
  1290. QScriptValue constructQSplitter(QScriptContext *context, QScriptEngine *engine);
  1291. QScriptValue QSplitter_addWidget(QScriptContext *context,
  1292. QScriptEngine *engine);
  1293. QScriptValue QSplitter_saveState(QScriptContext *context,
  1294. QScriptEngine *engine);
  1295. QScriptValue QSplitter_restoreState(QScriptContext *context,
  1296. QScriptEngine *engine);
  1297. void setQSplitterProperties(QScriptValue value, QScriptEngine *engine);
  1298. @ Of these, the scripting engine must be informed of the constructor.
  1299. @<Set up the scripting engine@>=
  1300. constructor = engine->newFunction(constructQSplitter);
  1301. value = engine->newQMetaObject(&QSplitter::staticMetaObject, constructor);
  1302. engine->globalObject().setProperty("QSplitter", value);
  1303. @ The constructor creates the object and adds the required properties to it.
  1304. @<Functions for scripting@>=
  1305. QScriptValue constructQSplitter(QScriptContext *, QScriptEngine *engine)
  1306. {
  1307. QScriptValue object = engine->newQObject(new QSplitter);
  1308. setQSplitterProperties(object, engine);
  1309. return object;
  1310. }
  1311. void setQSplitterProperties(QScriptValue value, QScriptEngine *engine)
  1312. {
  1313. setQFrameProperties(value, engine);
  1314. value.setProperty("addWidget", engine->newFunction(QSplitter_addWidget));
  1315. value.setProperty("saveState", engine->newFunction(QSplitter_saveState));
  1316. value.setProperty("restoreState",
  1317. engine->newFunction(QSplitter_restoreState));
  1318. }
  1319. @ The |"addWidget"| property is a simple wrapper around
  1320. |QSplitter::addWidget()|.
  1321. @<Functions for scripting@>=
  1322. QScriptValue QSplitter_addWidget(QScriptContext *context, QScriptEngine *)
  1323. {
  1324. if(context->argumentCount() == 1)
  1325. {
  1326. QSplitter *self = getself<QSplitter *>(context);
  1327. QWidget *widget = argument<QWidget *>(0, context);
  1328. if(widget)
  1329. {
  1330. self->addWidget(widget);
  1331. }
  1332. else
  1333. {
  1334. context->throwError("Incorrect argument type passed to "@|
  1335. "QSplitter::addWidget(). This method "@|
  1336. "requires a QWidget.");
  1337. }
  1338. }
  1339. else
  1340. {
  1341. context->throwError("Incorrect number of arguments passed to "@|
  1342. "QSplitter::addWidget(). This method takes one "@|
  1343. "QWidget as an argument.");
  1344. }
  1345. return QScriptValue();
  1346. }
  1347. @ When saving and restoring the state of a splitter, we always want to do this
  1348. through a |QSettings| object. For this, we take an extra argument specifying the
  1349. settings key to read from or write to. Unlike the equivalent functions called
  1350. from native code, neither of these functions called from a script will return
  1351. the data being saved.
  1352. @<Functions for scripting@>=
  1353. QScriptValue QSplitter_saveState(QScriptContext *context, QScriptEngine *)
  1354. {
  1355. if(context->argumentCount() == 1)
  1356. {
  1357. QSplitter *self = getself<QSplitter *>(context);
  1358. QString key = argument<QString>(0, context);
  1359. QSettings settings;
  1360. settings.setValue(key, self->saveState());
  1361. }
  1362. else
  1363. {
  1364. context->throwError("Incorrect number of arguments passed to "@|
  1365. "QSplitter::saveState(). This method takes one "@|
  1366. "string as an argument.");
  1367. }
  1368. return QScriptValue();
  1369. }
  1370. QScriptValue QSplitter_restoreState(QScriptContext *context, QScriptEngine *)
  1371. {
  1372. if(context->argumentCount() == 1)
  1373. {
  1374. QSplitter *self = getself<QSplitter *>(context);
  1375. QString key = argument<QString>(0, context);
  1376. QSettings settings;
  1377. self->restoreState(settings.value(key).toByteArray());
  1378. }
  1379. else
  1380. {
  1381. context->throwError("Incorrect number of arguments passed to "@|
  1382. "QSplitter::restoreState(). This method takes "@|
  1383. "one string as an argument.");
  1384. }
  1385. return QScriptValue();
  1386. }
  1387. @* Scripting Layout classes.
  1388. \noindent Layout classes simplify managing the size and position of widgets in a
  1389. user interface. Qt provides several such classes, including |QBoxLayout| which
  1390. can be used to construct a variety of different interfaces. As widgets
  1391. containing a layout should not really need to care which layout is being used,
  1392. the |QLayout| class acts as an abstract base for all layout classes. A bare
  1393. |QLayout| will never be constructed, however subclasses can make use of the
  1394. |addWidget()| property.
  1395. @<Function prototypes for scripting@>=
  1396. void setQLayoutProperties(QScriptValue value, QScriptEngine *engine);
  1397. QScriptValue QLayout_addWidget(QScriptContext *context, QScriptEngine *engine);
  1398. @ The implementation is trivial.
  1399. @<Functions for scripting@>=
  1400. void setQLayoutProperties(QScriptValue value, QScriptEngine *engine)
  1401. {
  1402. setQLayoutItemProperties(value, engine);
  1403. value.setProperty("addWidget", engine->newFunction(QLayout_addWidget));
  1404. }
  1405. QScriptValue QLayout_addWidget(QScriptContext *context, QScriptEngine *)
  1406. {
  1407. if(context->argumentCount() == 1)
  1408. {
  1409. QLayout *self = getself<QLayout *>(context);
  1410. QWidget *widget = argument<QWidget *>(0, context);
  1411. if(widget)
  1412. {
  1413. self->addWidget(widget);
  1414. }
  1415. else
  1416. {
  1417. context->throwError("Incorrect argument type passed to "@|
  1418. "QLayout::addWidget(). This method requires "@|
  1419. "a QWidget.");
  1420. }
  1421. }
  1422. else
  1423. {
  1424. context->throwError("Incorrect number of arguments passed to "@|
  1425. "QLayout::addWidget(). This method takes one "@|
  1426. "QWidget as an argument.");
  1427. }
  1428. return QScriptValue();
  1429. }
  1430. @ |QBoxLayout| is a more interesting layout class. This allows widgets to be
  1431. arranged in a single row or column and can be used, for example, to arrange a
  1432. row of buttons as in figure \secno.
  1433. \medskip
  1434. \resizebox*{6.3in}{!}{\includegraphics{boxlayoutexample}}
  1435. \smallskip
  1436. \centerline{Figure \secno: Buttons in a |QBoxLayout|.}
  1437. \medskip
  1438. This class makes use of the |addWidget()| method from |QLayout|.
  1439. @<Function prototypes for scripting@>=
  1440. QScriptValue constructQBoxLayout(QScriptContext *context,
  1441. QScriptEngine *engine);
  1442. void setQBoxLayoutProperties(QScriptValue value, QScriptEngine *engine);
  1443. QScriptValue QBoxLayout_addLayout(QScriptContext *context, QScriptEngine *engine);
  1444. QScriptValue QBoxLayout_addWidget(QScriptContext *context, QScriptEngine *engine);
  1445. @ The script constructor must be passed to the scripting engine.
  1446. @<Set up the scripting engine@>=
  1447. constructor = engine->newFunction(constructQBoxLayout);
  1448. value = engine->newQMetaObject(&QBoxLayout::staticMetaObject, constructor);
  1449. engine->globalObject().setProperty("QBoxLayout", value);
  1450. @ The implementation of these functions should seem familiar by now. Note that
  1451. while a horizontal layout is provided by default, this can be changed from the
  1452. script once the layout is created.
  1453. @<Functions for scripting@>=
  1454. QScriptValue constructQBoxLayout(QScriptContext *, QScriptEngine *engine)
  1455. {
  1456. QScriptValue object =
  1457. engine->newQObject(new QBoxLayout(QBoxLayout::LeftToRight));
  1458. setQBoxLayoutProperties(object, engine);
  1459. return object;
  1460. }
  1461. void setQBoxLayoutProperties(QScriptValue value, QScriptEngine *engine)
  1462. {
  1463. setQLayoutProperties(value, engine);
  1464. value.setProperty("addLayout", engine->newFunction(QBoxLayout_addLayout));
  1465. value.setProperty("addWidget", engine->newFunction(QBoxLayout_addWidget));
  1466. }
  1467. QScriptValue QBoxLayout_addLayout(QScriptContext *context, QScriptEngine *)
  1468. {
  1469. if(context->argumentCount() > 0 && context->argumentCount() < 3)
  1470. {
  1471. QBoxLayout *self = getself<QBoxLayout *>(context);
  1472. QLayout *layout = argument<QLayout *>(0, context);
  1473. int stretch = 0;
  1474. if(context->argumentCount() == 2)
  1475. {
  1476. stretch = argument<int>(1, context);
  1477. }
  1478. if(layout)
  1479. {
  1480. self->addLayout(layout, stretch);
  1481. }
  1482. else
  1483. {
  1484. context->throwError("Incorrect argument type passed to "@|
  1485. "QLayout::addLayout(). This method requires "@|
  1486. "a QLayout.");
  1487. }
  1488. }
  1489. else
  1490. {
  1491. context->throwError("Incorrect number of arguments passed to "@|
  1492. "QLayout::addLayout(). This method takes one "@|
  1493. "QLayout as an argument and optionally one integer.");
  1494. }
  1495. return QScriptValue();
  1496. }
  1497. @ We override the base class wrapper for |addWidget| to add two optional
  1498. arguments: one specifies the stretch factor of the widget and the other
  1499. specifies the alignment of the widget within the layout.
  1500. @<Functions for scripting@>=
  1501. QScriptValue QBoxLayout_addWidget(QScriptContext *context, QScriptEngine *)
  1502. {
  1503. if(context->argumentCount() > 0 && context->argumentCount() < 4)
  1504. {
  1505. QBoxLayout *self = getself<QBoxLayout *>(context);
  1506. QWidget *widget = argument<QWidget *>(0, context);
  1507. int stretch = 0;
  1508. Qt::Alignment alignment = 0;
  1509. if(context->argumentCount() > 1)
  1510. {
  1511. stretch = argument<int>(1, context);
  1512. }
  1513. if(context->argumentCount() > 2)
  1514. {
  1515. alignment = (Qt::Alignment)(argument<int>(2, context));
  1516. }
  1517. if(widget)
  1518. {
  1519. self->addWidget(widget, stretch, alignment);
  1520. }
  1521. else
  1522. {
  1523. context->throwError("Incorrect argument type passed to "@|
  1524. "QBoxLayout::addWidget(). This method requires "@|
  1525. "a QWidget.");
  1526. }
  1527. }
  1528. else
  1529. {
  1530. context->throwError("Incorrect number of arguments passed to "@|
  1531. "QBoxLayout::addWidget(). This method takes one "@|
  1532. "QWidget and optionally up to two integers as "@|
  1533. "arguments.");
  1534. }
  1535. return QScriptValue();
  1536. }
  1537. @* Scripting QAction.
  1538. \noindent The |QAction| class is used in \pn{} to create menu items and respond
  1539. to the selection of these items. Three functions are required for our scripting
  1540. needs with regard to this class.
  1541. @<Function prototypes for scripting@>=
  1542. QScriptValue constructQAction(QScriptContext *context, QScriptEngine *engine);
  1543. QScriptValue QAction_setShortcut(QScriptContext *context,
  1544. QScriptEngine *engine);
  1545. void setQActionProperties(QScriptValue value, QScriptEngine *engine);
  1546. @ The scripting engine must be informed of the constructor.
  1547. @<Set up the scripting engine@>=
  1548. constructor = engine->newFunction(constructQAction);
  1549. value = engine->newQMetaObject(&QAction::staticMetaObject, constructor);
  1550. engine->globalObject().setProperty("QAction", value);
  1551. @ The constructor is simple, however some might sensibly question why the
  1552. |"setShortcut"| property is needed at all. Why not have scripts simply set the
  1553. |shortcut| property of the |QAction| directly? The answer to this is that the
  1554. property expects data of the |QKeySequence| type. While this can be created from
  1555. a |QString|, passing a string to the property through the scripting engine did
  1556. not work at the time this was written.
  1557. @<Functions for scripting@>=
  1558. QScriptValue constructQAction(QScriptContext *, QScriptEngine *engine)
  1559. {
  1560. QScriptValue object = engine->newQObject(new QAction(NULL));
  1561. setQActionProperties(object, engine);
  1562. return object;
  1563. }
  1564. void setQActionProperties(QScriptValue value, QScriptEngine *engine)
  1565. {
  1566. setQObjectProperties(value, engine);
  1567. value.setProperty("setShortcut", engine->newFunction(QAction_setShortcut));
  1568. }
  1569. QScriptValue QAction_setShortcut(QScriptContext *context, QScriptEngine *)
  1570. {
  1571. if(context->argumentCount() == 1)
  1572. {
  1573. QAction *self = getself<@[QAction *@]>(context);
  1574. self->setShortcut(argument<QString>(0, context));
  1575. }
  1576. else
  1577. {
  1578. context->throwError("Incorrect number of arguments passed to "@|
  1579. "QAction::setShortcut(). This method takes one "@|
  1580. "string as an argument.");
  1581. }
  1582. return QScriptValue();
  1583. }
  1584. @* Scripting QFileDialog.
  1585. \noindent |QFileDialog| provides two static member functions which is all that
  1586. we need. The objects returned from these methods are built on the |QDialog|
  1587. abstract base class.
  1588. @<Function prototypes for scripting@>=
  1589. QScriptValue QFileDialog_getOpenFileName(QScriptContext *context,
  1590. QScriptEngine *engine);
  1591. QScriptValue QFileDialog_getSaveFileName(QScriptContext *context,
  1592. QScriptEngine *engine);
  1593. void setQFileDialogProperties(QScriptValue value, QScriptEngine *engine);
  1594. void setQDialogProperties(QScriptValue value, QScriptEngine *engine);
  1595. @ The scripting engine must be informed of the wrapper functions for the static
  1596. methods.
  1597. @<Set up the scripting engine@>=
  1598. value = engine->newQMetaObject(&QFileDialog::staticMetaObject);
  1599. value.setProperty("getOpenFileName",
  1600. engine->newFunction(QFileDialog_getOpenFileName));
  1601. value.setProperty("getSaveFileName",
  1602. engine->newFunction(QFileDialog_getSaveFileName));
  1603. engine->globalObject().setProperty("QFileDialog", value);
  1604. @ This function is just a simple wrapper around the |QFileDialog| method, but
  1605. the object returned has any properties added to the base class available.
  1606. @<Functions for scripting@>=
  1607. QScriptValue QFileDialog_getOpenFileName(QScriptContext *context,
  1608. QScriptEngine *engine)
  1609. {
  1610. QScriptValue retval;
  1611. if(context->argumentCount() == 3)
  1612. {
  1613. QWidget *widget = argument<QWidget *>(0, context);
  1614. if(widget)
  1615. {
  1616. QString caption = argument<QString>(1, context);
  1617. QString dir = argument<QString>(2, context);
  1618. retval = QScriptValue(engine,
  1619. QFileDialog::getOpenFileName(widget, caption,
  1620. dir, "", 0, 0));
  1621. setQFileDialogProperties(retval, engine);
  1622. }
  1623. else
  1624. {
  1625. context->throwError("Incorrect argument type passed to "@|
  1626. "QFileDialog::getOpenFileName(). The first "@|
  1627. "argument to this method must be a QWidget.");
  1628. }
  1629. }
  1630. else
  1631. {
  1632. context->throwError("Incorrect number of arguments passed to "@|
  1633. "QFileDialog::getOpenFileName(). This method "@|
  1634. "takes one QWidget followed by two strings for a "@|
  1635. "total of three arguments.");
  1636. }
  1637. return retval;
  1638. }
  1639. @ Similarly, this just wraps |QFileDialog::getSaveFileName()|.
  1640. @<Functions for scripting@>=
  1641. QScriptValue QFileDialog_getSaveFileName(QScriptContext *context,
  1642. QScriptEngine *engine)
  1643. {
  1644. QScriptValue retval;
  1645. if(context->argumentCount() == 3)
  1646. {
  1647. QWidget *widget = argument<QWidget *>(0, context);
  1648. if(widget)
  1649. {
  1650. QString caption = argument<QString>(1, context);
  1651. QString dir = argument<QString>(2, context);
  1652. retval = QScriptValue(engine,
  1653. QFileDialog::getSaveFileName(widget, caption,
  1654. dir, "", 0, 0));
  1655. setQFileDialogProperties(retval, engine);
  1656. }
  1657. else
  1658. {
  1659. context->throwError("Incorrect argument type passed to "@|
  1660. "QFileDialog::getSaveFileName(). The first "@|
  1661. "argument to this method must be a QWidget.");
  1662. }
  1663. }
  1664. else
  1665. {
  1666. context->throwError("Incorrect number of arguments passed to "@|
  1667. "QFileDialog::getSaveFileName(). This method "@|
  1668. "takes one QWidget followed by two strings for a "@|
  1669. "total of three arguments.");
  1670. }
  1671. return retval;
  1672. }
  1673. @ Adding object hierarchy properties to the objects created above is simple.
  1674. @<Functions for scripting@>=
  1675. void setQFileDialogProperties(QScriptValue value, QScriptEngine *engine)
  1676. {
  1677. setQDialogProperties(value, engine);
  1678. }
  1679. void setQDialogProperties(QScriptValue value, QScriptEngine *engine)
  1680. {
  1681. setQWidgetProperties(value, engine);
  1682. }
  1683. @* Scripting QFile.
  1684. \noindent When using a |QFile| in a script, we only need the constructor and two
  1685. functions for hooking it in with the rest of the object hierarchy.
  1686. @<Function prototypes for scripting@>=
  1687. QScriptValue constructQFile(QScriptContext *context, QScriptEngine *engine);
  1688. void setQFileProperties(QScriptValue value, QScriptEngine *engine);
  1689. QScriptValue QFile_remove(QScriptContext *context, QScriptEngine *engine);
  1690. void setQIODeviceProperties(QScriptValue value, QScriptEngine *engine);
  1691. QScriptValue QIODevice_open(QScriptContext *context, QScriptEngine *engine);
  1692. QScriptValue QIODevice_close(QScriptContext *context, QScriptEngine *engine);
  1693. QScriptValue QIODevice_readToString(QScriptContext *context,
  1694. QScriptEngine *engine);
  1695. @ This function is passed to the scripting engine.
  1696. @<Set up the scripting engine@>=
  1697. constructor = engine->newFunction(constructQFile);
  1698. value = engine->newQMetaObject(&QFile::staticMetaObject, constructor);
  1699. engine->globalObject().setProperty("QFile", value);
  1700. @ The implementation is trivial.
  1701. @<Functions for scripting@>=
  1702. QScriptValue constructQFile(QScriptContext *context, QScriptEngine *engine)
  1703. {
  1704. QScriptValue object =
  1705. engine->newQObject(new QFile(argument<QString>(0, context)));@/
  1706. setQFileProperties(object, engine);
  1707. return object;
  1708. }
  1709. @ |QFile| gets a wrapper around |remove()| to support deleting temporary files.
  1710. @<Functions for scripting@>=
  1711. void setQFileProperties(QScriptValue value, QScriptEngine *engine)
  1712. {
  1713. setQIODeviceProperties(value, engine);
  1714. value.setProperty("remove", engine->newFunction(QFile_remove));
  1715. }
  1716. QScriptValue QFile_remove(QScriptContext *context, QScriptEngine *engine)
  1717. {
  1718. QFile *self = getself<QFile *>(context);
  1719. bool retval = self->remove();
  1720. return QScriptValue(engine, retval);
  1721. }
  1722. @ Although we aren't going to create any instances of |QIODevice| directly,
  1723. subclasses such as |QFile| and |QBuffer| get two additional properties for
  1724. opening and closing the device.
  1725. In order to solve some class interoperability issues, a convenience method is
  1726. also added which is equivalent to creating a |QString| from the |QByteArray|
  1727. returned from the |readAll()| method.
  1728. @<Functions for scripting@>=
  1729. void setQIODeviceProperties(QScriptValue value, QScriptEngine *engine)
  1730. {
  1731. setQObjectProperties(value, engine);
  1732. value.setProperty("open", engine->newFunction(QIODevice_open));
  1733. value.setProperty("close", engine->newFunction(QIODevice_close));
  1734. value.setProperty("readToString",
  1735. engine->newFunction(QIODevice_readToString));
  1736. }
  1737. @ These are simple wrappers. In the case of the |open()| property, one argument
  1738. may be passed specifying the mode used for opening. The supported values for
  1739. this are 1 (Read Only), 2 (Write Only), and 3 (Read Write). If this argument is
  1740. not passed, it is assumed that the user wants read and write access.
  1741. @<Functions for scripting@>=
  1742. QScriptValue QIODevice_open(QScriptContext *context, QScriptEngine *)
  1743. {
  1744. QIODevice *self = getself<QIODevice *>(context);
  1745. if(context->argumentCount() == 1)
  1746. {
  1747. switch(argument<int>(0, context))
  1748. {
  1749. case 1:
  1750. self->open(QIODevice::ReadOnly);
  1751. break;
  1752. case 2:
  1753. self->open(QIODevice::WriteOnly);
  1754. break;
  1755. case 3:
  1756. self->open(QIODevice::ReadWrite);
  1757. break;
  1758. default:
  1759. break;
  1760. }
  1761. }
  1762. else
  1763. {
  1764. self->open(QIODevice::ReadWrite);
  1765. }
  1766. return QScriptValue();
  1767. }
  1768. QScriptValue QIODevice_close(QScriptContext *context, QScriptEngine *)
  1769. {
  1770. QIODevice *self = getself<QIODevice *>(context);
  1771. self->close();
  1772. return QScriptValue();
  1773. }
  1774. @ The |readToString()| method is a simple extension of |QIODevice::readAll()| to
  1775. interface with classes that expect document data in the form of a string. Most
  1776. notably, this includes |QWebView|.
  1777. @<Functions for scripting@>=
  1778. QScriptValue QIODevice_readToString(QScriptContext *context, QScriptEngine *)
  1779. {
  1780. QIODevice *self = getself<QIODevice *>(context);
  1781. self->reset();
  1782. return QScriptValue(QString(self->readAll()));
  1783. }
  1784. @* Scripting QBuffer.
  1785. \noindent Sometimes it is desirable to load a roast profile from a file. At
  1786. other times, it is more useful to load that profile from a byte array stored in
  1787. a database. The |XMLInput| class takes data from a |QIODevice| object, which
  1788. means that we can choose from a |QFile| when we want the former or a |QBuffer|
  1789. when we want the latter.
  1790. @<Function prototypes for scripting@>=
  1791. QScriptValue constructQBuffer(QScriptContext *context, QScriptEngine *engine);
  1792. void setQBufferProperties(QScriptValue value, QScriptEngine *engine);
  1793. QScriptValue QBuffer_setData(QScriptContext *context, QScriptEngine *engine);
  1794. @ The host environment needs to be aware of the constructor.
  1795. @<Set up the scripting engine@>=
  1796. constructor = engine->newFunction(constructQBuffer);
  1797. value = engine->newQMetaObject(&QBuffer::staticMetaObject, constructor);
  1798. engine->globalObject().setProperty("QBuffer", value);
  1799. @ The implementation is trivial.
  1800. @<Functions for scripting@>=
  1801. QScriptValue constructQBuffer(QScriptContext *context, QScriptEngine *engine)
  1802. {
  1803. QByteArray *array = new QByteArray(argument<QString>(0, context).toAscii());
  1804. QScriptValue object = engine->newQObject(new QBuffer(array));
  1805. setQBufferProperties(object, engine);
  1806. return object;
  1807. }
  1808. void setQBufferProperties(QScriptValue value, QScriptEngine *engine)
  1809. {
  1810. setQIODeviceProperties(value, engine);
  1811. value.setProperty("setData", engine->newFunction(QBuffer_setData));
  1812. }
  1813. QScriptValue QBuffer_setData(QScriptContext *context, QScriptEngine *)
  1814. {
  1815. QBuffer *self = getself<QBuffer *>(context);
  1816. self->setData(argument<QString>(0, context).toAscii());
  1817. return QScriptValue();
  1818. }
  1819. @* Scripting QXmlQuery.
  1820. \noindent Sometimes we have some XML data in a file or a buffer and we would
  1821. like to extract certain information from that data in the host environment.
  1822. Rather than write complicated string manipulation routines in an attempt to deal
  1823. with this sensibly, we can use the XQuery language to extract the information we
  1824. want. One common use case for this is extracting all measurements from a roast
  1825. profile that are associated with an annotation.
  1826. @<Function prototypes for scripting@>=
  1827. QScriptValue constructXQuery(QScriptContext *context, QScriptEngine *engine);
  1828. QScriptValue XQuery_bind(QScriptContext *context, QScriptEngine *engine);
  1829. QScriptValue XQuery_exec(QScriptContext *context, QScriptEngine *engine);
  1830. QScriptValue XQuery_setQuery(QScriptContext *context, QScriptEngine *engine);
  1831. void setXQueryProperties(QScriptValue value, QScriptEngine *engine);
  1832. @ The constructor must be registered with the host environment. This is done a
  1833. bit differently from most classes as |QXmlQuery| is not a |QObject|.
  1834. @<Set up the scripting engine@>=
  1835. constructor = engine->newFunction(constructXQuery);
  1836. engine->globalObject().setProperty("XQuery", constructor);
  1837. @ The constructor just needs to make sure the functions we want to make
  1838. available are applied.
  1839. @<Functions for scripting@>=
  1840. QScriptValue constructXQuery(QScriptContext *, QScriptEngine *engine)
  1841. {
  1842. QScriptValue object = engine->toScriptValue<void *>(new QXmlQuery);
  1843. setXQueryProperties(object, engine);
  1844. return object;
  1845. }
  1846. void setXQueryProperties(QScriptValue value, QScriptEngine *engine)
  1847. {
  1848. value.setProperty("bind", engine->newFunction(XQuery_bind));
  1849. value.setProperty("exec", engine->newFunction(XQuery_exec));
  1850. value.setProperty("setQuery", engine->newFunction(XQuery_setQuery));
  1851. }
  1852. @ The |bind()| property can be used to specify a |QIODevice| to be referenced by
  1853. a variable within a query.
  1854. @<Functions for scripting@>=
  1855. QScriptValue XQuery_bind(QScriptContext *context, QScriptEngine *)
  1856. {
  1857. QXmlQuery *self = getself<QXmlQuery *>(context);
  1858. QIODevice *buffer = argument<QIODevice *>(1, context);
  1859. self->bindVariable(argument<QString>(0, context), buffer);
  1860. return QScriptValue();
  1861. }
  1862. @ A method is also required for setting the query we wish to conduct.
  1863. @<Functions for scripting@>=
  1864. QScriptValue XQuery_setQuery(QScriptContext *context, QScriptEngine *)
  1865. {
  1866. QXmlQuery *self = getself<QXmlQuery *>(context);
  1867. self->setQuery(argument<QString>(0, context));
  1868. return QScriptValue();
  1869. }
  1870. @ This method runs the previously specified query.
  1871. @<Functions for scripting@>=
  1872. QScriptValue XQuery_exec(QScriptContext *context, QScriptEngine *)
  1873. {
  1874. QXmlQuery *self = getself<QXmlQuery *>(context);
  1875. QString result;
  1876. self->evaluateTo(&result);
  1877. return QScriptValue(result);
  1878. }
  1879. @* Scripting QXmlStreamWriter.
  1880. \noindent There are some cases where it may be desirable to produce XML from the
  1881. host environment. While there are several ways to accomplish this, the
  1882. |QXmlStreamWriter| class greatly simplifies generating complex XML documents.
  1883. This class is not related to |QObject|, so several functions are needed to
  1884. expose the functionality of this class to the host environment.
  1885. @<Function prototypes for scripting@>=
  1886. QScriptValue constructXmlWriter(QScriptContext *context, QScriptEngine *engine);
  1887. QScriptValue XmlWriter_setDevice(QScriptContext *context,
  1888. QScriptEngine *engine);
  1889. QScriptValue XmlWriter_writeAttribute(QScriptContext *context,
  1890. QScriptEngine *engine);
  1891. QScriptValue XmlWriter_writeCDATA(QScriptContext *context,
  1892. QScriptEngine *engine);
  1893. QScriptValue XmlWriter_writeCharacters(QScriptContext *context,
  1894. QScriptEngine *engine);
  1895. QScriptValue XmlWriter_writeDTD(QScriptContext *context, QScriptEngine *engine);
  1896. QScriptValue XmlWriter_writeEmptyElement(QScriptContext *context,
  1897. QScriptEngine *engine);
  1898. QScriptValue XmlWriter_writeEndDocument(QScriptContext *context,
  1899. QScriptEngine *engine);
  1900. QScriptValue XmlWriter_writeEndElement(QScriptContext *context,
  1901. QScriptEngine *engine);
  1902. QScriptValue XmlWriter_writeEntityReference(QScriptContext *context,
  1903. QScriptEngine *engine);
  1904. QScriptValue XmlWriter_writeProcessingInstruction(QScriptContext *context,
  1905. QScriptEngine *engine);
  1906. QScriptValue XmlWriter_writeStartDocument(QScriptContext *context,
  1907. QScriptEngine *engine);
  1908. QScriptValue XmlWriter_writeStartElement(QScriptContext *context,
  1909. QScriptEngine *engine);
  1910. QScriptValue XmlWriter_writeTextElement(QScriptContext *context,
  1911. QScriptEngine *engine);
  1912. void setXmlWriterProperties(QScriptValue value, QScriptEngine *engine);
  1913. @ The constructor must be registered with the host environment.
  1914. @<Set up the scripting engine@>=
  1915. constructor = engine->newFunction(constructXmlWriter);
  1916. engine->globalObject().setProperty("XmlWriter", constructor);
  1917. @ The constructor takes an optional argument allowing the output device to be
  1918. specified.
  1919. @<Functions for scripting@>=
  1920. QScriptValue constructXmlWriter(QScriptContext *context, QScriptEngine *engine)
  1921. {
  1922. QXmlStreamWriter *retval;
  1923. if(context->argumentCount() == 1)
  1924. {
  1925. retval = new QXmlStreamWriter(argument<QIODevice *>(0, context));
  1926. }
  1927. else
  1928. {
  1929. retval = new QXmlStreamWriter;
  1930. }
  1931. QScriptValue object = engine->toScriptValue<void *>(retval);
  1932. setXmlWriterProperties(object, engine);
  1933. return object;
  1934. }
  1935. void setXmlWriterProperties(QScriptValue value, QScriptEngine *engine)
  1936. {
  1937. value.setProperty("setDevice", engine->newFunction(XmlWriter_setDevice));
  1938. value.setProperty("writeAttribute",
  1939. engine->newFunction(XmlWriter_writeAttribute));
  1940. value.setProperty("writeCDATA", engine->newFunction(XmlWriter_writeCDATA));
  1941. value.setProperty("writeCharacters",
  1942. engine->newFunction(XmlWriter_writeCharacters));
  1943. value.setProperty("writeDTD", engine->newFunction(XmlWriter_writeDTD));
  1944. value.setProperty("writeEmptyElement",
  1945. engine->newFunction(XmlWriter_writeEmptyElement));
  1946. value.setProperty("writeEndDocument",
  1947. engine->newFunction(XmlWriter_writeEndDocument));
  1948. value.setProperty("writeEndElement",
  1949. engine->newFunction(XmlWriter_writeEndElement));
  1950. value.setProperty("writeEntityReference",
  1951. engine->newFunction(XmlWriter_writeEntityReference));
  1952. value.setProperty("writeProcessingInstruction",
  1953. engine->newFunction(XmlWriter_writeProcessingInstruction));
  1954. value.setProperty("writeStartDocument",
  1955. engine->newFunction(XmlWriter_writeStartDocument));
  1956. value.setProperty("writeStartElement",
  1957. engine->newFunction(XmlWriter_writeStartElement));
  1958. value.setProperty("writeTextElement",
  1959. engine->newFunction(XmlWriter_writeTextElement));
  1960. }
  1961. @ If the output device needs to be changed or if one is not passed to the
  1962. constructor, the |setDevice()| method can be used.
  1963. @<Functions for scripting@>=
  1964. QScriptValue XmlWriter_setDevice(QScriptContext *context, QScriptEngine *)
  1965. {
  1966. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  1967. QIODevice *device = argument<QIODevice *>(0, context);
  1968. self->setDevice(device);
  1969. return QScriptValue();
  1970. }
  1971. @ The remaining functions are simple wrappers used for writing various types of
  1972. data. After creating a writer and setting the output device, the start of the
  1973. document should be written. One argument is required containing the XML version
  1974. number. Another function handles writing the end of the document.
  1975. @<Functions for scripting@>=
  1976. QScriptValue XmlWriter_writeStartDocument(QScriptContext *context,
  1977. QScriptEngine *)
  1978. {
  1979. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  1980. self->writeStartDocument(argument<QString>(0, context));
  1981. return QScriptValue();
  1982. }
  1983. QScriptValue XmlWriter_writeEndDocument(QScriptContext *context,
  1984. QScriptEngine *)
  1985. {
  1986. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  1987. self->writeEndDocument();
  1988. return QScriptValue();
  1989. }
  1990. @ After the start of the document, a DTD is commonly needed.
  1991. @<Functions for scripting@>=
  1992. QScriptValue XmlWriter_writeDTD(QScriptContext *context, QScriptEngine *)
  1993. {
  1994. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  1995. self->writeDTD(argument<QString>(0, context));
  1996. return QScriptValue();
  1997. }
  1998. @ After this, elements need to be written. For this, we write the start
  1999. element, any attributes needed, character data, and the end element.
  2000. @<Functions for scripting@>=
  2001. QScriptValue XmlWriter_writeStartElement(QScriptContext *context,
  2002. QScriptEngine *)
  2003. {
  2004. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2005. self->writeStartElement(argument<QString>(0, context));
  2006. return QScriptValue();
  2007. }
  2008. QScriptValue XmlWriter_writeAttribute(QScriptContext *context, QScriptEngine *)
  2009. {
  2010. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2011. self->writeAttribute(argument<QString>(0, context),
  2012. argument<QString>(1, context));
  2013. return QScriptValue();
  2014. }
  2015. QScriptValue XmlWriter_writeCharacters(QScriptContext *context, QScriptEngine *)
  2016. {
  2017. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2018. self->writeCharacters(argument<QString>(0, context));
  2019. return QScriptValue();
  2020. }
  2021. QScriptValue XmlWriter_writeEndElement(QScriptContext *context, QScriptEngine *)
  2022. {
  2023. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2024. self->writeEndElement();
  2025. return QScriptValue();
  2026. }
  2027. @ For convenience, two other methods are provided for writing elements. Elements
  2028. which do not require anything between the start and end elements can be created
  2029. with |writeEmptyElement()|. Elements which do not require attributes, but do
  2030. contain text can be created with |writeTextElement()|.
  2031. @<Functions for scripting@>=
  2032. QScriptValue XmlWriter_writeEmptyElement(QScriptContext *context,
  2033. QScriptEngine *)
  2034. {
  2035. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2036. self->writeEmptyElement(argument<QString>(0, context));
  2037. return QScriptValue();
  2038. }
  2039. QScriptValue XmlWriter_writeTextElement(QScriptContext *context,
  2040. QScriptEngine *)
  2041. {
  2042. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2043. self->writeTextElement(argument<QString>(0, context),
  2044. argument<QString>(1, context));
  2045. return QScriptValue();
  2046. }
  2047. @ Less commonly needed are functions for writing CDATA sections, entity
  2048. references, and processing instructions.
  2049. @<Functions for scripting@>=
  2050. QScriptValue XmlWriter_writeCDATA(QScriptContext *context, QScriptEngine *)
  2051. {
  2052. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2053. self->writeCDATA(argument<QString>(0, context));
  2054. return QScriptValue();
  2055. }
  2056. QScriptValue XmlWriter_writeEntityReference(QScriptContext *context,
  2057. QScriptEngine *)
  2058. {
  2059. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2060. self->writeEntityReference(argument<QString>(0, context));
  2061. return QScriptValue();
  2062. }
  2063. QScriptValue XmlWriter_writeProcessingInstruction(QScriptContext *context,
  2064. QScriptEngine *)
  2065. {
  2066. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2067. self->writeProcessingInstruction(argument<QString>(0, context),
  2068. argument<QString>(1, context));
  2069. return QScriptValue();
  2070. }
  2071. @* Scripting QXmlStreamReader.
  2072. \noindent When a serializer is written using |QXmlStreamWriter|, a corresponding
  2073. deserializer should also be written. While there are several possible ways to do
  2074. this, using |QXmlStreamReader| is often the best choice. \pn{} provides a subset
  2075. of the functionality from this class which should be adequate for most purposes.
  2076. @<Function prototypes for scripting@>=
  2077. QScriptValue constructXmlReader(QScriptContext *context, QScriptEngine *engine);
  2078. QScriptValue XmlReader_atEnd(QScriptContext *context, QScriptEngine *engine);
  2079. QScriptValue XmlReader_attribute(QScriptContext *context,
  2080. QScriptEngine *engine);
  2081. QScriptValue XmlReader_hasAttribute(QScriptContext *context,
  2082. QScriptEngine *engine);
  2083. QScriptValue XmlReader_isDTD(QScriptContext *context, QScriptEngine *engine);
  2084. QScriptValue XmlReader_isStartElement(QScriptContext *context,
  2085. QScriptEngine *engine);
  2086. QScriptValue XmlReader_name(QScriptContext *context, QScriptEngine *engine);
  2087. QScriptValue XmlReader_readElementText(QScriptContext *context,
  2088. QScriptEngine *engine);
  2089. QScriptValue XmlReader_readNext(QScriptContext *context, QScriptEngine *engine);
  2090. QScriptValue XmlReader_text(QScriptContext *context, QScriptEngine *engine);
  2091. void setXmlReaderProperties(QScriptValue value, QScriptEngine *engine);
  2092. @ The constructor must be registered with the host environment.
  2093. @<Set up the scripting engine@>=
  2094. constructor = engine->newFunction(constructXmlReader);
  2095. engine->globalObject().setProperty("XmlReader", constructor);
  2096. @ The constructor requires an argument specifying the output device. This can be
  2097. any |QIODevice|. The |open()| method must be called on the device before passing
  2098. it as an argument to this function.
  2099. @<Functions for scripting@>=
  2100. QScriptValue constructXmlReader(QScriptContext *context, QScriptEngine *engine)
  2101. {
  2102. QXmlStreamReader *retval =
  2103. new QXmlStreamReader(argument<QIODevice *>(0, context));
  2104. QScriptValue object = engine->toScriptValue<void *>(retval);
  2105. setXmlReaderProperties(object, engine);
  2106. return object;
  2107. }
  2108. void setXmlReaderProperties(QScriptValue value, QScriptEngine *engine)
  2109. {
  2110. value.setProperty("atEnd", engine->newFunction(XmlReader_atEnd));
  2111. value.setProperty("attribute", engine->newFunction(XmlReader_attribute));
  2112. value.setProperty("hasAttribute",
  2113. engine->newFunction(XmlReader_hasAttribute));
  2114. value.setProperty("isDTD", engine->newFunction(XmlReader_isDTD));
  2115. value.setProperty("isStartElement",
  2116. engine->newFunction(XmlReader_isStartElement));
  2117. value.setProperty("name", engine->newFunction(XmlReader_name));
  2118. value.setProperty("readElementText",
  2119. engine->newFunction(XmlReader_readElementText));
  2120. value.setProperty("readNext",
  2121. engine->newFunction(XmlReader_readNext));
  2122. value.setProperty("text", engine->newFunction(XmlReader_text));
  2123. }
  2124. @ Most of the functions are simple member function wrappers. Two of these
  2125. properties are not. These are the |attribute()| and |hasAttribute()| properties.
  2126. @<Functions for scripting@>=
  2127. QScriptValue XmlReader_attribute(QScriptContext *context, QScriptEngine *)
  2128. {
  2129. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2130. QString retval =
  2131. self->attributes().value(argument<QString>(0, context)).toString();
  2132. return QScriptValue(retval);
  2133. }
  2134. QScriptValue XmlReader_hasAttribute(QScriptContext *context, QScriptEngine *)
  2135. {
  2136. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2137. bool retval =
  2138. self->attributes().hasAttribute(argument<QString>(0, context));
  2139. return QScriptValue(retval);
  2140. }
  2141. @ Other properties can be used for determining how to proceed with the
  2142. processing.
  2143. @<Functions for scripting@>=
  2144. QScriptValue XmlReader_atEnd(QScriptContext *context, QScriptEngine *)
  2145. {
  2146. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2147. return QScriptValue(self->atEnd());
  2148. }
  2149. QScriptValue XmlReader_isDTD(QScriptContext *context, QScriptEngine *)
  2150. {
  2151. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2152. return QScriptValue(self->isDTD());
  2153. }
  2154. QScriptValue XmlReader_isStartElement(QScriptContext *context, QScriptEngine *)
  2155. {
  2156. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2157. return QScriptValue(self->isStartElement());
  2158. }
  2159. @ We move from one element to the next with the |readNext()| property.
  2160. @<Functions for scripting@>=
  2161. QScriptValue XmlReader_readNext(QScriptContext *context, QScriptEngine *)
  2162. {
  2163. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2164. self->readNext();
  2165. return QScriptValue();
  2166. }
  2167. @ The remaining properties return the element name and text.
  2168. @<Functions for scripting@>=
  2169. QScriptValue XmlReader_name(QScriptContext *context, QScriptEngine *)
  2170. {
  2171. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2172. return QScriptValue(self->name().toString());
  2173. }
  2174. QScriptValue XmlReader_readElementText(QScriptContext *context, QScriptEngine *)
  2175. {
  2176. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2177. return QScriptValue(self->readElementText());
  2178. }
  2179. QScriptValue XmlReader_text(QScriptContext *context, QScriptEngine *)
  2180. {
  2181. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2182. return QScriptValue(self->text().toString());
  2183. }
  2184. @* Scripting QSettings.
  2185. \noindent Rather than have a script create a |QSettings| object when it needs to
  2186. save or load settings, the object is provided along with properties for getting
  2187. and setting values. Two functions are needed for this along with a third which
  2188. ensures any properties added to |QObject| are also available to |QSettings| from
  2189. the host environment.
  2190. @<Function prototypes for scripting@>=
  2191. QScriptValue QSettings_value(QScriptContext *context, QScriptEngine *engine);
  2192. QScriptValue QSettings_setValue(QScriptContext *context, QScriptEngine *engine);
  2193. void setQSettingsProperties(QScriptValue value, QScriptEngine *engine);
  2194. @ The object with properties for these functions is passed to the scripting
  2195. engine.
  2196. @<Set up the scripting engine@>=
  2197. value = engine->newQObject(&settings);
  2198. setQSettingsProperties(value, engine);
  2199. engine->globalObject().setProperty("QSettings", value);
  2200. @ Adding properties to the |QSettings| object should seem familiar.
  2201. @<Functions for scripting@>=
  2202. void setQSettingsProperties(QScriptValue value, QScriptEngine *engine)
  2203. {
  2204. setQObjectProperties(value, engine);
  2205. value.setProperty("value", engine->newFunction(QSettings_value));
  2206. value.setProperty("setValue", engine->newFunction(QSettings_setValue));
  2207. }
  2208. @ When getting a value from saved settings, there is the possibility that there
  2209. will not be a value saved for the requested key. An optional second argument can
  2210. be used to supply a default value.
  2211. @<Functions for scripting@>=
  2212. QScriptValue QSettings_value(QScriptContext *context, QScriptEngine *engine)
  2213. {
  2214. QScriptValue object;
  2215. if(context->argumentCount() == 1 || context->argumentCount() == 2)
  2216. {
  2217. QSettings settings;
  2218. QString key = argument<QString>(0, context);
  2219. QVariant value;
  2220. QVariant retval;
  2221. if(context->argumentCount() > 1)
  2222. {
  2223. value = argument<QVariant>(1, context);
  2224. retval = settings.value(key, value);
  2225. }
  2226. else
  2227. {
  2228. retval = settings.value(key);
  2229. }
  2230. object = engine->newVariant(retval);
  2231. }
  2232. else
  2233. {
  2234. context->throwError("Incorrect number of arguments passed to "@|
  2235. "QSettings::value(). This method takes one "@|
  2236. "string and one optional variant type.");
  2237. }
  2238. return object;
  2239. }
  2240. QScriptValue QSettings_setValue(QScriptContext *context, QScriptEngine *)
  2241. {
  2242. if(context->argumentCount() == 2)
  2243. {
  2244. QSettings settings;
  2245. QString key = argument<QString>(0, context);
  2246. QVariant value = argument<QVariant>(1, context);
  2247. settings.setValue(key, value);
  2248. }
  2249. else
  2250. {
  2251. context->throwError("Incorrect number of arguments passed to "@|
  2252. "QSettings::setValue(). This method takes one "@|
  2253. "string and one variant type for a total of two "@|
  2254. "arguments.");
  2255. }
  2256. return QScriptValue();
  2257. }
  2258. @* Scripting QLCDNumber.
  2259. \noindent |QLCDNumber| is used as a base class for \pn{}'s |TemperatureDisplay|
  2260. and |TimerDisplay| classes, but it can also be used on its own for the display
  2261. of mainly numeric information.
  2262. @<Function prototypes for scripting@>=
  2263. QScriptValue constructQLCDNumber(QScriptContext *context,
  2264. QScriptEngine *engine);
  2265. void setQLCDNumberProperties(QScriptValue value, QScriptEngine *engine);
  2266. @ The constructor must be passed to the scripting engine.
  2267. @<Set up the scripting engine@>=
  2268. constructor = engine->newFunction(constructQLCDNumber);
  2269. value = engine->newQMetaObject(&QLCDNumber::staticMetaObject, constructor);
  2270. engine->globalObject().setProperty("QLCDNumber", value);
  2271. @ There is nothing special about the implementation.
  2272. @<Functions for scripting@>=
  2273. QScriptValue constructQLCDNumber(QScriptContext *, QScriptEngine *engine)
  2274. {
  2275. QScriptValue object = engine->newQObject(new QLCDNumber());
  2276. setQLCDNumberProperties(object, engine);
  2277. return object;
  2278. }
  2279. void setQLCDNumberProperties(QScriptValue value, QScriptEngine *engine)
  2280. {
  2281. setQFrameProperties(value, engine);
  2282. }
  2283. @* Scripting QTime.
  2284. \noindent |QTime| is a little different from the classes examined so far. This
  2285. class can be used for synchonizing time among various objects by creating a
  2286. common base reference time. This should not be needed as ECMA-262 already
  2287. specifies a |Date| class, however this has historically been troublesome to use.
  2288. One thing that makes this class different is that it is not related to
  2289. |QObject|. This makes usefully exposing it to the scripting engine a little more
  2290. difficult.
  2291. @<Function prototypes for scripting@>=
  2292. QScriptValue constructQTime(QScriptContext *context, QScriptEngine *engine);
  2293. QScriptValue QTime_addMSecs(QScriptContext *context, QScriptEngine *engine);
  2294. QScriptValue QTime_addSecs(QScriptContext *context, QScriptEngine *engine);
  2295. QScriptValue QTime_elapsed(QScriptContext *context, QScriptEngine *engine);
  2296. QScriptValue QTime_hour(QScriptContext *context, QScriptEngine *engine);
  2297. QScriptValue QTime_isNull(QScriptContext *context, QScriptEngine *engine);
  2298. QScriptValue QTime_isValid(QScriptContext *context, QScriptEngine *engine);
  2299. QScriptValue QTime_minute(QScriptContext *context, QScriptEngine *engine);
  2300. QScriptValue QTime_msec(QScriptContext *context, QScriptEngine *engine);
  2301. QScriptValue QTime_msecsTo(QScriptContext *context, QScriptEngine *engine);
  2302. QScriptValue QTime_restart(QScriptContext *context, QScriptEngine *engine);
  2303. QScriptValue QTime_second(QScriptContext *context, QScriptEngine *engine);
  2304. QScriptValue QTime_secsTo(QScriptContext *context, QScriptEngine *engine);
  2305. QScriptValue QTime_setHMS(QScriptContext *context, QScriptEngine *engine);
  2306. QScriptValue QTime_start(QScriptContext *context, QScriptEngine *engine);
  2307. QScriptValue QTime_toString(QScriptContext *context, QScriptEngine *engine);
  2308. QScriptValue QTime_currentTime(QScriptContext *context, QScriptEngine *engine);
  2309. QScriptValue QTime_fromString(QScriptContext *context, QScriptEngine *engine);
  2310. QScriptValue QTime_valueOf(QScriptContext *context, QScriptEngine *engine);
  2311. void setQTimeProperties(QScriptValue value, QScriptEngine *engine);
  2312. @ We must tell the script engine about the constructor. This is not done in
  2313. quite the same way as is done for |QObject| derived types.
  2314. @<Set up the scripting engine@>=
  2315. constructor = engine->newFunction(constructQTime);
  2316. engine->globalObject().setProperty("QTime", constructor);
  2317. @ The constructor has a couple interesting twists. The first is the ability to
  2318. accept a variable number of integer arguments. The other is that |QTime| is not
  2319. derived from |QObject|. The lack of |break| statements in the |switch| is
  2320. intended.
  2321. @<Functions for scripting@>=
  2322. QScriptValue constructQTime(QScriptContext *context,
  2323. QScriptEngine *engine)
  2324. {
  2325. QScriptValue object;
  2326. if(context->argumentCount() == 0 ||
  2327. (context->argumentCount() >= 2 && context->argumentCount() <= 4))@/
  2328. {
  2329. int arg1 = 0;
  2330. int arg2 = 0;
  2331. int arg3 = 0;
  2332. int arg4 = 0;
  2333. switch(context->argumentCount())
  2334. {@t\1@>@/
  2335. case 4:@/
  2336. arg4 = argument<int>(3, context);
  2337. case 3:@/
  2338. arg3 = argument<int>(2, context);
  2339. case 2:@/
  2340. arg2 = argument<int>(1, context);
  2341. arg1 = argument<int>(0, context);
  2342. default:@/
  2343. break;@t\2@>@/
  2344. }
  2345. if(context->argumentCount())
  2346. {
  2347. object = engine->toScriptValue<QTime>(QTime(arg1, arg2, arg3,
  2348. arg4));
  2349. }
  2350. else
  2351. {
  2352. object = engine->toScriptValue<QTime>(QTime());
  2353. }
  2354. setQTimeProperties(object, engine);
  2355. }
  2356. else
  2357. {
  2358. context->throwError("Incorrect number of arguments passed to "@|
  2359. "QTime::QTime(). This method takes zero, two, "@|
  2360. "three, or four integer arguments.");
  2361. }
  2362. return object;
  2363. }
  2364. @ In order to use the various |QTime| methods, we must add wrapper functions as
  2365. properties of newly created script objects. The last two of these should really
  2366. be callable without starting from an existing |QTime|.
  2367. @<Functions for scripting@>=
  2368. void setQTimeProperties(QScriptValue value, QScriptEngine *engine)
  2369. {
  2370. value.setProperty("addMSecs", engine->newFunction(QTime_addMSecs));
  2371. value.setProperty("addSecs", engine->newFunction(QTime_addSecs));
  2372. value.setProperty("elapsed", engine->newFunction(QTime_elapsed));
  2373. value.setProperty("hour", engine->newFunction(QTime_hour));
  2374. value.setProperty("isNull", engine->newFunction(QTime_isNull));
  2375. value.setProperty("isValid", engine->newFunction(QTime_isValid));
  2376. value.setProperty("minute", engine->newFunction(QTime_minute));
  2377. value.setProperty("msec", engine->newFunction(QTime_msec));
  2378. value.setProperty("msecsTo", engine->newFunction(QTime_msecsTo));
  2379. value.setProperty("restart", engine->newFunction(QTime_restart));
  2380. value.setProperty("second", engine->newFunction(QTime_second));
  2381. value.setProperty("secsTo", engine->newFunction(QTime_secsTo));
  2382. value.setProperty("setHMS", engine->newFunction(QTime_setHMS));
  2383. value.setProperty("start", engine->newFunction(QTime_start));
  2384. value.setProperty("toString", engine->newFunction(QTime_toString));
  2385. value.setProperty("currentTime", engine->newFunction(QTime_currentTime));
  2386. value.setProperty("fromString", engine->newFunction(QTime_fromString));
  2387. value.setProperty("valueOf", engine->newFunction(QTime_valueOf));
  2388. }
  2389. @ The |valueOf()| method exposes a numeric representation of the time
  2390. suitable for use in comparing two time values. With this it is possible to
  2391. take two |QTime| values in script code {\tt t1} and {\tt t2} and get the
  2392. expected results from {\tt t1 == t2}, {\tt t1 < t2}, {\tt t1 > t2} and
  2393. similar comparative operations.
  2394. @<Functions for scripting@>=
  2395. QScriptValue QTime_valueOf(QScriptContext *context, QScriptEngine *engine)
  2396. {
  2397. QTime self = getself<QTime>(context);
  2398. int retval = (self.hour() * 60 * 60 * 1000) + (self.minute() * 60 * 1000) +
  2399. (self.second() * 1000) + self.msec();
  2400. return QScriptValue(retval);
  2401. }
  2402. @ These functions are effectively wrapper functions around existing |QTime|
  2403. functionality with some error checking for the scripting engine.
  2404. The |addMSecs()| and |addSecs()| methods return a new |QTime| object.
  2405. @<Functions for scripting@>=
  2406. QScriptValue QTime_addMSecs(QScriptContext *context, QScriptEngine *engine)
  2407. {
  2408. QTime time;
  2409. QScriptValue retval;
  2410. if(context->argumentCount() == 1)
  2411. {
  2412. QTime self = getself<QTime>(context);
  2413. time = self.addMSecs(argument<int>(0, context));
  2414. retval = engine->toScriptValue<QTime>(time);
  2415. setQTimeProperties(retval, engine);
  2416. }
  2417. else
  2418. {
  2419. context->throwError("Incorrect number of arguments passed to "@|
  2420. "QTime::addMSecs(). This method takes one "@|
  2421. "integer as an argument.");
  2422. }
  2423. return retval;
  2424. }
  2425. QScriptValue QTime_addSecs(QScriptContext *context, QScriptEngine *engine)
  2426. {
  2427. QTime time;
  2428. QScriptValue retval;
  2429. if(context->argumentCount() == 1)
  2430. {
  2431. QTime self = getself<QTime>(context);
  2432. time = self.addSecs(argument<int>(0, context));
  2433. retval = engine->toScriptValue<QTime>(time);
  2434. setQTimeProperties(retval, engine);
  2435. }
  2436. else
  2437. {
  2438. context->throwError("Incorrect number of arguments passed to "@|
  2439. "QTime::addSecs(). This method takes one "@|
  2440. "integer as an argument.");
  2441. }
  2442. return retval;
  2443. }
  2444. @ The |elapsed()| method returns an integer value.
  2445. @<Functions for scripting@>=
  2446. QScriptValue QTime_elapsed(QScriptContext *context, QScriptEngine *engine)
  2447. {
  2448. QScriptValue retval;
  2449. if(context->argumentCount() == 0)
  2450. {
  2451. QTime self = getself<QTime>(context);
  2452. retval = QScriptValue(engine, self.elapsed());
  2453. }
  2454. else
  2455. {
  2456. context->throwError("Incorrect number of arguments passed to "@|
  2457. "QTime::elapsed(). This method takes no "@|
  2458. "arguments.");
  2459. }
  2460. return retval;
  2461. }
  2462. @ The |hour()|, |minute()|, |second()| and |msec()| methods return an integer
  2463. with various parts of the time. The |hour()| method is typical of these methods.
  2464. @<Functions for scripting@>=
  2465. QScriptValue QTime_hour(QScriptContext *context, QScriptEngine *engine)
  2466. {
  2467. QScriptValue retval;
  2468. if(context->argumentCount() == 0)
  2469. {
  2470. QTime self = getself<QTime>(context);
  2471. retval = QScriptValue(engine, self.hour());
  2472. }
  2473. else
  2474. {
  2475. context->throwError("Incorrect number of arguments passed to "@|
  2476. "QTime::hour(). This method takes no "@|
  2477. "arguments.");
  2478. }
  2479. return retval;
  2480. }
  2481. @ The |minute()|, |second()|, and |msec()| methods are implemented similarly.
  2482. @<Functions for scripting@>=
  2483. QScriptValue QTime_minute(QScriptContext *context, QScriptEngine *engine)
  2484. {
  2485. QScriptValue retval;
  2486. if(context->argumentCount() == 0)
  2487. {
  2488. QTime self = getself<QTime>(context);
  2489. retval = QScriptValue(engine, self.minute());
  2490. }
  2491. else
  2492. {
  2493. context->throwError("Incorrect number of arguments passed to "@|
  2494. "QTime::minute(). This method takes no "@|
  2495. "arguments.");
  2496. }
  2497. return retval;
  2498. }
  2499. QScriptValue QTime_second(QScriptContext *context, QScriptEngine *engine)
  2500. {
  2501. QScriptValue retval;
  2502. if(context->argumentCount() == 0)
  2503. {
  2504. QTime self = getself<QTime>(context);
  2505. retval = QScriptValue(engine, self.second());
  2506. }
  2507. else
  2508. {
  2509. context->throwError("Incorrect number of arguments passed to "@|
  2510. "QTime::second(). This method takes no "@|
  2511. "arguments.");
  2512. }
  2513. return retval;
  2514. }
  2515. QScriptValue QTime_msec(QScriptContext *context, QScriptEngine *engine)
  2516. {
  2517. QScriptValue retval;
  2518. if(context->argumentCount() == 0)
  2519. {
  2520. QTime self = getself<QTime>(context);
  2521. retval = QScriptValue(engine, self.msec());
  2522. }
  2523. else
  2524. {
  2525. context->throwError("Incorrect number of arguments passed to "@|
  2526. "QTime::msec(). This method takes no "@|
  2527. "arguments.");
  2528. }
  2529. return retval;
  2530. }
  2531. @ The |isNull()| and |isValid()| methods return a boolean value. A |QTime| is
  2532. considered null if it was created with a constructor with no arguments. It is
  2533. considered invalid if it is null or if part of the time is out of range.
  2534. @<Functions for scripting@>=
  2535. QScriptValue QTime_isNull(QScriptContext *context, QScriptEngine *engine)
  2536. {
  2537. QScriptValue retval;
  2538. if(context->argumentCount() == 0)
  2539. {
  2540. QTime self = getself<QTime>(context);
  2541. retval = QScriptValue(engine, self.isNull());
  2542. }
  2543. else
  2544. {
  2545. context->throwError("Incorrect number of arguments passed to "@|
  2546. "QTime::isNull(). This method takes no "@|
  2547. "arguments.");
  2548. }
  2549. return retval;
  2550. }
  2551. QScriptValue QTime_isValid(QScriptContext *context, QScriptEngine *engine)
  2552. {
  2553. QScriptValue retval;
  2554. if(context->argumentCount() == 0)
  2555. {
  2556. QTime self = getself<QTime>(context);
  2557. retval = QScriptValue(engine, self.isValid());
  2558. }
  2559. else
  2560. {
  2561. context->throwError("Incorrect number of arguments passed to "@|
  2562. "QTime::isValid(). This method takes no "@|
  2563. "arguments.");
  2564. }
  2565. return retval;
  2566. }
  2567. @ The |secsTo()| and |msecsTo()| methods return an integer value indicating the
  2568. number of seconds or milliseconds until a |QTime| argument.
  2569. @<Functions for scripting@>=
  2570. QScriptValue QTime_msecsTo(QScriptContext *context, QScriptEngine *engine)
  2571. {
  2572. QScriptValue retval;
  2573. if(context->argumentCount() == 1)
  2574. {
  2575. QTime self = getself<QTime>(context);
  2576. QTime arg = argument<QVariant>(0, context).toTime();
  2577. retval = QScriptValue(engine, self.msecsTo(arg));
  2578. }
  2579. else
  2580. {
  2581. context->throwError("Incorrect number of arguments passed to "@|
  2582. "QTime::msecsTo(). This method takes one QTime.");
  2583. }
  2584. return retval;
  2585. }
  2586. QScriptValue QTime_secsTo(QScriptContext *context, QScriptEngine *engine)
  2587. {
  2588. QScriptValue retval;
  2589. if(context->argumentCount() == 1)
  2590. {
  2591. QTime self = getself<QTime>(context);
  2592. QTime arg = argument<QVariant>(0, context).toTime();
  2593. retval = QScriptValue(engine, self.secsTo(arg));
  2594. }
  2595. else
  2596. {
  2597. context->throwError("Incorrect number of arguments passed to "@|
  2598. "QTime::secsTo(). This method takes one QTime.");
  2599. }
  2600. return retval;
  2601. }
  2602. @ The |start()| and |restart()| methods each set the value of the |QTime()| to
  2603. the current time. The |restart()| method additionally returns the same value as
  2604. the |elapsed()| method.
  2605. @<Functions for scripting@>=
  2606. QScriptValue QTime_restart(QScriptContext *context, QScriptEngine *engine)
  2607. {
  2608. QScriptValue retval;
  2609. if(context->argumentCount() == 0)
  2610. {
  2611. QTime self = getself<QTime>(context);
  2612. retval = QScriptValue(engine, self.restart());
  2613. }
  2614. else
  2615. {
  2616. context->throwError("Incorrect number of arguments passed to "@|
  2617. "QTime::restart(). This method takes no "@|
  2618. "arguments.");
  2619. }
  2620. return retval;
  2621. }
  2622. QScriptValue QTime_start(QScriptContext *context, QScriptEngine *)
  2623. {
  2624. if(context->argumentCount() == 0)
  2625. {
  2626. QTime self = getself<QTime>(context);
  2627. self.start();
  2628. }
  2629. else
  2630. {
  2631. context->throwError("Incorrect number of arguments passed to "@|
  2632. "QTime::start(). This method takes no arguments.");
  2633. }
  2634. return QScriptValue();
  2635. }
  2636. @ The slightly inappropriately named |setHMS()| method changes the current value
  2637. of the time and returns a boolean to indicate if the new time value is valid.
  2638. @<Functions for scripting@>=
  2639. QScriptValue QTime_setHMS(QScriptContext *context, QScriptEngine *engine)
  2640. {
  2641. QScriptValue retval;
  2642. if(context->argumentCount() == 3 || context->argumentCount() == 4)
  2643. {
  2644. QTime self = getself<QTime>(context);
  2645. int arg1 = 0;
  2646. int arg2 = 0;
  2647. int arg3 = 0;
  2648. int arg4 = 0;
  2649. switch(context->argumentCount())@/
  2650. {@t\1@>@/
  2651. case 4:@/
  2652. arg4 = argument<int>(3, context);
  2653. case 3:@/
  2654. arg3 = argument<int>(2, context);
  2655. arg2 = argument<int>(1, context);
  2656. arg1 = argument<int>(0, context);
  2657. default:@/
  2658. break;@t\2@>@/
  2659. }
  2660. retval = QScriptValue(engine, self.setHMS(arg1, arg2, arg3, arg4));
  2661. }
  2662. else
  2663. {
  2664. context->throwError("Incorrect number of arguments passed to "@|
  2665. "QTime::setHMS(). This method takes three or "@|
  2666. "four integer arguments.");
  2667. }
  2668. return retval;
  2669. }
  2670. @ The |toString()| method returns a string representation of the time. See the
  2671. Qt documentation for instructions on creating a valid format string.
  2672. @<Functions for scripting@>=
  2673. QScriptValue QTime_toString(QScriptContext *context, QScriptEngine *engine)
  2674. {
  2675. QScriptValue retval;
  2676. if(context->argumentCount() == 1)
  2677. {
  2678. QTime self = getself<QTime>(context);
  2679. retval = QScriptValue(engine, self.toString(argument<QString>(0, context)));
  2680. }
  2681. else
  2682. {
  2683. context->throwError("Incorrect number of arguments passed to "@|
  2684. "QTime::toString(). This method takes one QString "@|
  2685. "as an argument.");
  2686. }
  2687. return retval;
  2688. }
  2689. @ The |currentTime()| and |fromString()| methods return a new |QTime| object.
  2690. These methods make no reference to the any other existing |QTime|.
  2691. @<Functions for scripting@>=
  2692. QScriptValue QTime_currentTime(QScriptContext *, QScriptEngine *engine)
  2693. {
  2694. QScriptValue object;
  2695. object = engine->toScriptValue<QTime>(QTime::currentTime());
  2696. setQTimeProperties(object, engine);
  2697. return object;
  2698. }
  2699. QScriptValue QTime_fromString(QScriptContext *context, QScriptEngine *engine)
  2700. {
  2701. QScriptValue object;
  2702. if(context->argumentCount() == 2)
  2703. {
  2704. QString time = argument<QString>(0, context);
  2705. QString format = argument<QString>(1, context);
  2706. object = engine->toScriptValue<QTime>(QTime::fromString(time, format));
  2707. setQTimeProperties(object, engine);
  2708. }
  2709. else
  2710. {
  2711. context->throwError("Incorrect number of arguments passed to "@|
  2712. "QTime::fromString(). This method takes two "@|
  2713. "string arguments.");
  2714. }
  2715. return object;
  2716. }
  2717. @* Scripting Item View Classes.
  2718. \noindent |QAbstractScrollArea| is a |QFrame| that serves as the base class for
  2719. classes such as |QGraphicsView| and |QAbstractItemView|. Objects from this class
  2720. are not created directly.
  2721. @<Function prototypes for scripting@>=
  2722. void setQAbstractScrollAreaProperties(QScriptValue value,
  2723. QScriptEngine *engine);
  2724. @ The implementation of this is simple.
  2725. @<Functions for scripting@>=
  2726. void setQAbstractScrollAreaProperties(QScriptValue value, QScriptEngine *engine)
  2727. {
  2728. setQFrameProperties(value, engine);
  2729. }
  2730. @ This class is used by the |QAbstractItemView| class. This is another class
  2731. that we do not need a script constructor for.
  2732. @<Function prototypes for scripting@>=
  2733. void setQAbstractItemViewProperties(QScriptValue value, QScriptEngine *engine);
  2734. @ This function has another simple implementation.
  2735. @<Functions for scripting@>=
  2736. void setQAbstractItemViewProperties(QScriptValue value, QScriptEngine *engine)
  2737. {
  2738. setQAbstractScrollAreaProperties(value, engine);
  2739. }
  2740. @ The |QGraphicsView| and |QTableView| classes form the base of \pn{} classes.
  2741. @<Function prototypes for scripting@>=
  2742. void setQGraphicsViewProperties(QScriptValue value, QScriptEngine *engine);
  2743. void setQTableViewProperties(QScriptValue value, QScriptEngine *engine);
  2744. @ Again, the implementations are boring.
  2745. @<Functions for scripting@>=
  2746. void setQGraphicsViewProperties(QScriptValue value, QScriptEngine *engine)
  2747. {
  2748. setQAbstractScrollAreaProperties(value, engine);
  2749. }
  2750. void setQTableViewProperties(QScriptValue value, QScriptEngine *engine)
  2751. {
  2752. setQAbstractItemViewProperties(value, engine);
  2753. }
  2754. @* Scripting Button Classes.
  2755. \noindent \pn{} provides an |AnnotationButton| class which is a special kind of
  2756. |QPushButton| which in turn comes from |QAbstractButton|. While
  2757. |AnnotationButton| can be used in exactly the same way as a |QPushButton|, if
  2758. an annotation is not needed, there is little reason not to use the base class.
  2759. @<Function prototypes for scripting@>=
  2760. void setQAbstractButtonProperties(QScriptValue value, QScriptEngine *engine);
  2761. void setQPushButtonProperties(QScriptValue value, QScriptEngine *engine);
  2762. QScriptValue constructQPushButton(QScriptContext *context,
  2763. QScriptEngine *engine);
  2764. @ The constructor for |QPushButton| should be passed to the scripting engine.
  2765. @<Set up the scripting engine@>=
  2766. constructor = engine->newFunction(constructQPushButton);
  2767. value = engine->newQMetaObject(&QPushButton::staticMetaObject, constructor);
  2768. engine->globalObject().setProperty("QPushButton", value);
  2769. @ The implementation should seem familiar.
  2770. @<Functions for scripting@>=
  2771. QScriptValue constructQPushButton(QScriptContext *, QScriptEngine *engine)
  2772. {
  2773. QScriptValue object = engine->newQObject(new QPushButton());
  2774. setQPushButtonProperties(object, engine);
  2775. return object;
  2776. }
  2777. void setQPushButtonProperties(QScriptValue value, QScriptEngine *engine)
  2778. {
  2779. setQAbstractButtonProperties(value, engine);
  2780. }
  2781. void setQAbstractButtonProperties(QScriptValue value, QScriptEngine *engine)
  2782. {
  2783. setQWidgetProperties(value, engine);
  2784. }
  2785. @* Scripting QSqlQuery.
  2786. \noindent With this class exposed to the host environment, it becomes possible
  2787. for script code to execute SQL queries and evaluate the result.
  2788. Rather than use |QSqlQuery| directly, however, we use a proxy \nfnote{Erich
  2789. Gamma, Richard Helm, Raph Johnson, and John
  2790. Vlissides,\par\indent\underbar{Design Patterns: elements of reusable
  2791. object-oriented software} (1995) pp. 207--217} class. This class obtains its own
  2792. database connection and handles properly closing and removing these connections
  2793. when the query object is destroyed.
  2794. @<Class declarations@>=
  2795. class SqlQueryConnection : public QSqlQuery@/
  2796. {
  2797. public:@/
  2798. SqlQueryConnection(const QString &query = QString());
  2799. ~SqlQueryConnection();
  2800. QSqlQuery* operator->();
  2801. private:@/
  2802. QString connection;
  2803. QSqlQuery *q;
  2804. };
  2805. @ The constructor can be somewhat simplified from the four forms of |QSqlQuery|.
  2806. We are not interested in creating an object from a |QSqlResult| or from another
  2807. |QSqlQuery|. The database connection is managed by the class itself so the
  2808. constructor only needs an optional string containing a query. This is used to
  2809. initialize a real |QSqlQuery| object.
  2810. @<SqlQueryConnection implementation@>=
  2811. SqlQueryConnection::SqlQueryConnection(const QString &query)
  2812. {
  2813. QSqlDatabase database = AppInstance->database();
  2814. database.open();
  2815. q = new QSqlQuery(query, database);
  2816. connection = database.connectionName();
  2817. }
  2818. @ The destructor handles removing the |QSqlQuery| and the database connection
  2819. associated with it. The extra brackets introduce a new scope for the
  2820. |QSqlDatabase| so that it is out of scope when the connection is removed.
  2821. @<SqlQueryConnection implementation@>=
  2822. SqlQueryConnection::~SqlQueryConnection()
  2823. {
  2824. delete q;
  2825. {
  2826. QSqlDatabase database = QSqlDatabase::database(connection);
  2827. database.close();
  2828. }
  2829. QSqlDatabase::removeDatabase(connection);
  2830. }
  2831. @ For all other functionality, we simply forward the request to our |QSqlQuery|
  2832. object.
  2833. @<SqlQueryConnection implementation@>=
  2834. QSqlQuery* SqlQueryConnection::operator->()
  2835. {
  2836. return q;
  2837. }
  2838. @ In order to use this new class in the host environment, a number of functions
  2839. are needed.
  2840. @<Function prototypes for scripting@>=
  2841. void setQSqlQueryProperties(QScriptValue value, QScriptEngine *engine);
  2842. QScriptValue constructQSqlQuery(QScriptContext *context, QScriptEngine *engine);
  2843. QScriptValue QSqlQuery_bind(QScriptContext *context, QScriptEngine *engine);
  2844. QScriptValue QSqlQuery_bindDeviceData(QScriptContext *context,
  2845. QScriptEngine *engine);
  2846. QScriptValue QSqlQuery_bindFileData(QScriptContext *context,
  2847. QScriptEngine *engine);
  2848. QScriptValue QSqlQuery_exec(QScriptContext *context,
  2849. QScriptEngine *engine);
  2850. QScriptValue QSqlQuery_executedQuery(QScriptContext *context,
  2851. QScriptEngine *engine);
  2852. QScriptValue QSqlQuery_invalidate(QScriptContext *context, QScriptEngine *engine);
  2853. QScriptValue QSqlQuery_next(QScriptContext *context, QScriptEngine *engine);
  2854. QScriptValue QSqlQuery_prepare(QScriptContext *context, QScriptEngine *engine);
  2855. QScriptValue QSqlQuery_value(QScriptContext *context, QScriptEngine *engine);
  2856. @ For conceptual convenience we simply pretend that we are working with a real
  2857. |QSqlQuery| object.
  2858. @<Set up the scripting engine@>=
  2859. constructor = engine->newFunction(constructQSqlQuery);
  2860. engine->globalObject().setProperty("QSqlQuery", constructor);
  2861. @ With connection creation no longer needed in the constructor, all that is
  2862. needed is object creation and applying the appropriate properties to the script
  2863. value.
  2864. @<Functions for scripting@>=
  2865. QScriptValue constructQSqlQuery(QScriptContext *, QScriptEngine *engine)
  2866. {
  2867. QScriptValue object =
  2868. engine->toScriptValue<void *>(new SqlQueryConnection());
  2869. setQSqlQueryProperties(object, engine);
  2870. return object;
  2871. }
  2872. @ As this class does not derive from |QObject|, we must wrap all of the methods
  2873. we might want to use.
  2874. @<Functions for scripting@>=
  2875. void setQSqlQueryProperties(QScriptValue value, QScriptEngine *engine)
  2876. {
  2877. value.setProperty("bind", engine->newFunction(QSqlQuery_bind));
  2878. value.setProperty("bindFileData",
  2879. engine->newFunction(QSqlQuery_bindFileData));
  2880. value.setProperty("bindDeviceData",
  2881. engine->newFunction(QSqlQuery_bindDeviceData));
  2882. value.setProperty("exec", engine->newFunction(QSqlQuery_exec));
  2883. value.setProperty("executedQuery", engine->newFunction(QSqlQuery_executedQuery));
  2884. value.setProperty("invalidate", engine->newFunction(QSqlQuery_invalidate));
  2885. value.setProperty("next", engine->newFunction(QSqlQuery_next));
  2886. value.setProperty("prepare", engine->newFunction(QSqlQuery_prepare));
  2887. value.setProperty("value", engine->newFunction(QSqlQuery_value));
  2888. }
  2889. @ Most of these properties are wrappers around existing |QSqlQuery| functions.
  2890. @<Functions for scripting@>=
  2891. QScriptValue QSqlQuery_exec(QScriptContext *context, QScriptEngine *engine)
  2892. {
  2893. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2894. QScriptValue retval;
  2895. if(context->argumentCount() == 1)
  2896. {
  2897. retval = QScriptValue(engine,
  2898. query->exec(argument<QString>(0, context)));
  2899. }
  2900. else
  2901. {
  2902. retval = QScriptValue(engine, query->exec());
  2903. }
  2904. if(query->lastError().isValid())
  2905. {
  2906. qDebug() << query->lastQuery();
  2907. qDebug() << query->lastError().text();
  2908. }
  2909. return retval;
  2910. }
  2911. QScriptValue QSqlQuery_executedQuery(QScriptContext *context, QScriptEngine *)
  2912. {
  2913. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2914. return QScriptValue(query->lastQuery());
  2915. }
  2916. QScriptValue QSqlQuery_next(QScriptContext *context, QScriptEngine *engine)
  2917. {
  2918. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2919. return QScriptValue(engine, query->next());
  2920. }
  2921. QScriptValue QSqlQuery_value(QScriptContext *context, QScriptEngine *engine)
  2922. {
  2923. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2924. return QScriptValue(engine,
  2925. query->value(argument<int>(0, context)).toString());
  2926. }
  2927. @ For prepared queries, we support binding variables available to the script,
  2928. data available in a named file, or data from any open |QIODevice|.
  2929. @<Functions for scripting@>=
  2930. QScriptValue QSqlQuery_prepare(QScriptContext *context, QScriptEngine *engine)
  2931. {
  2932. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2933. return QScriptValue(engine, query->prepare(argument<QString>(0, context)));
  2934. }
  2935. QScriptValue QSqlQuery_bind(QScriptContext *context, QScriptEngine *)
  2936. {
  2937. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2938. query->bindValue(argument<QString>(0, context),
  2939. argument<QVariant>(1, context));
  2940. return QScriptValue();
  2941. }
  2942. QScriptValue QSqlQuery_bindFileData(QScriptContext *context,
  2943. QScriptEngine *)
  2944. {
  2945. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2946. QString placeholder = argument<QString>(0, context);
  2947. QString filename = argument<QString>(1, context);
  2948. QFile file(filename);
  2949. QByteArray data;
  2950. if(file.open(QIODevice::ReadOnly))
  2951. {
  2952. data = file.readAll();
  2953. file.close();
  2954. }
  2955. query->bindValue(placeholder, data);
  2956. return QScriptValue();
  2957. }
  2958. QScriptValue QSqlQuery_bindDeviceData(QScriptContext *context,
  2959. QScriptEngine *)
  2960. {
  2961. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2962. QString placeholder = argument<QString>(0, context);
  2963. QIODevice *device = argument<QIODevice *>(1, context);
  2964. device->reset();
  2965. QByteArray data;
  2966. data = device->readAll();
  2967. query->bindValue(placeholder, data);
  2968. return QScriptValue();
  2969. }
  2970. @ To avoid leaking database connections, we add the |invalidate()| property
  2971. which destroys our object. The object on which this method is called must not be
  2972. used after calling this method. In script code this will typically be used as in
  2973. the following example:
  2974. {\tt query = query.invalidate();}
  2975. @<Functions for scripting@>=
  2976. QScriptValue QSqlQuery_invalidate(QScriptContext *context, QScriptEngine *)
  2977. {
  2978. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2979. delete query;
  2980. return QScriptValue::UndefinedValue;
  2981. }
  2982. @* Other scripting functions.
  2983. \noindent There are a few functions that are exposed to the scripting engine
  2984. that are not associated with any class. Two functions are used for extracting
  2985. information from file names. Another is used to construct array values from SQL
  2986. array values. There is also a function for setting the default font for the
  2987. application or some part of the application.
  2988. @<Function prototypes for scripting@>=
  2989. QScriptValue baseName(QScriptContext *context, QScriptEngine *engine);
  2990. QScriptValue dir(QScriptContext *context, QScriptEngine *engine);
  2991. QScriptValue sqlToArray(QScriptContext *context, QScriptEngine *engine);
  2992. QScriptValue setFont(QScriptContext *context, QScriptEngine *engine);
  2993. QScriptValue annotationFromRecord(QScriptContext *context,
  2994. QScriptEngine *engine);
  2995. QScriptValue setTabOrder(QScriptContext *context, QScriptEngine *engine);
  2996. @ These functions are passed to the scripting engine.
  2997. @<Set up the scripting engine@>=
  2998. engine->globalObject().setProperty("baseName", engine->newFunction(baseName));
  2999. engine->globalObject().setProperty("dir", engine->newFunction(dir));
  3000. engine->globalObject().setProperty("sqlToArray",
  3001. engine->newFunction(sqlToArray));
  3002. engine->globalObject().setProperty("setFont", engine->newFunction(setFont));
  3003. engine->globalObject().setProperty("annotationFromRecord",
  3004. engine->newFunction(annotationFromRecord));
  3005. engine->globalObject().setProperty("setTabOrder", engine->newFunction(setTabOrder));
  3006. @ These functions are not part of an object. They expect a string specifying
  3007. the path to a file and return a string with either the name of the file without
  3008. the path and extension or the path of the directory containing the file.
  3009. @<Functions for scripting@>=
  3010. QScriptValue baseName(QScriptContext *context, QScriptEngine *engine)
  3011. {
  3012. QFileInfo info(argument<QString>(0, context));
  3013. QScriptValue retval(engine, info.baseName());
  3014. return retval;
  3015. }
  3016. QScriptValue dir(QScriptContext *context, QScriptEngine *engine)
  3017. {
  3018. QFileInfo info(argument<QString>(0, context));
  3019. QDir dir = info.dir();
  3020. QScriptValue retval(engine, dir.path());
  3021. return retval;
  3022. }
  3023. @ This function takes a string representing a SQL array and returns an array
  3024. value.
  3025. @<Functions for scripting@>=
  3026. QScriptValue sqlToArray(QScriptContext *context, QScriptEngine *engine)
  3027. {
  3028. QString source = argument<QString>(0, context);
  3029. source.remove(0, 1);
  3030. source.chop(1);
  3031. QStringList elements = source.split(",");
  3032. QString element;
  3033. QScriptValue dest = engine->newArray(elements.size());
  3034. int i = 0;
  3035. foreach(element, elements)
  3036. {
  3037. if(element.startsWith("\"") && element.endsWith("\""))
  3038. {
  3039. element.chop(1);
  3040. element = element.remove(0, 1);
  3041. }
  3042. dest.setProperty(i, QScriptValue(engine, element));
  3043. i++;
  3044. }
  3045. return dest;
  3046. }
  3047. @ This function can be used to set the default font for the application or on
  3048. a per-class hierarchy basis.
  3049. @<Functions for scripting@>=
  3050. QScriptValue setFont(QScriptContext *context, QScriptEngine *)
  3051. {
  3052. QString font = argument<QString>(0, context);
  3053. QString classname;
  3054. if(context->argumentCount() > 1)
  3055. {
  3056. classname = argument<QString>(1, context);
  3057. QApplication::setFont(QFont(font), classname.toLatin1().constData());
  3058. }
  3059. else
  3060. {
  3061. QApplication::setFont(QFont(font));
  3062. }
  3063. return QScriptValue();
  3064. }
  3065. @ This function was briefly used prior to adding support for |QXmlQuery| in the
  3066. host environment. The function is now depreciated and should not be used.
  3067. @<Functions for scripting@>=
  3068. QScriptValue annotationFromRecord(QScriptContext *context, QScriptEngine *)
  3069. {
  3070. SqlQueryConnection query;
  3071. QString q = "SELECT file FROM files WHERE id = :file";
  3072. query.prepare(q);
  3073. query.bindValue(":file", argument<int>(0, context));
  3074. query.exec();
  3075. query.next();
  3076. QByteArray array = query.value(0).toByteArray();
  3077. QBuffer buffer(&array);
  3078. buffer.open(QIODevice::ReadOnly);
  3079. QXmlQuery xquery;
  3080. xquery.bindVariable("profile", &buffer);
  3081. QString xq;
  3082. xq = "for $b in doc($profile) //tuple where exists($b/annotation) return $b";
  3083. xquery.setQuery(xq);
  3084. QString result;
  3085. xquery.evaluateTo(&result);
  3086. return QScriptValue(result);
  3087. }
  3088. @ This function can be used to change the tab order for controls in Typica.
  3089. Changes to the example configuration in \pn{} 1.4 made the default handling
  3090. of tab controls in the logging window unacceptable.
  3091. @<Functions for scripting@>=
  3092. QScriptValue setTabOrder(QScriptContext *context, QScriptEngine *)
  3093. {
  3094. QWidget::setTabOrder(argument<QWidget*>(0, context),
  3095. argument<QWidget*>(1, context));
  3096. return QScriptValue();
  3097. }
  3098. @** Application Configuration.
  3099. \noindent While \pn{} is intended as a data logging application, the diversity
  3100. of equipment and supporting technology precludes the option of providing a
  3101. single interface for common tasks. It is important that the application can be
  3102. configured to work with different roasting equipment, databases, and the like.
  3103. To accomplish this, \pn{} utilizes an XML description of the desired application
  3104. configuration and provides an ECMA-262 host environment which allows application
  3105. dataflow to be configured.
  3106. The scripting environment provides access to elements of the XML file and also
  3107. allows access to most of the application classes. A selection of classes
  3108. provided by Qt is also available. See the section on The Scripting Engine for
  3109. more details.
  3110. \danger While the code is the ultimate documentation of what is possible with
  3111. this interface, additional documentation should be provided to document the
  3112. meaning of supported elements and the objects available through the scripting
  3113. engine.\endanger
  3114. The application configuration is loaded when the program is started.
  3115. Starting with version 1.4, we check for a command line option with the path to
  3116. the configuration file and load that instead of prompting for the information
  3117. if possible.
  3118. @<Load the application configuration@>=
  3119. QStringList arguments = QCoreApplication::arguments();
  3120. int position = arguments.indexOf("-c");
  3121. QString filename = QString();
  3122. if(position != -1)
  3123. {
  3124. if(arguments.size() >= position + 1)
  3125. {
  3126. filename = arguments.at(position + 1);
  3127. }
  3128. }
  3129. if(filename.isEmpty())
  3130. {
  3131. filename = QFileDialog::getOpenFileName(NULL, "Open Configuration File",
  3132. settings.value("config", "").toString());
  3133. }
  3134. QDir directory;
  3135. if(!filename.isEmpty())
  3136. {
  3137. QFile file(filename);
  3138. QFileInfo info(filename);
  3139. directory = info.dir();
  3140. settings.setValue("config", directory.path());
  3141. if(file.open(QIODevice::ReadOnly))
  3142. {
  3143. app.configuration()->setContent(&file, true);
  3144. }
  3145. }
  3146. @<Substitute included fragments@>@;
  3147. @ The {\tt <application>} element can contain an arbitrary number of
  3148. {\tt <include>} elements. These elements should not appear in the DOM. Instead,
  3149. the element should be replaced by the content of the specified document.
  3150. @<Substitute included fragments@>=
  3151. QDomElement root = app.configuration()->documentElement();
  3152. QDomNodeList children = root.childNodes();
  3153. QString replacementDoc;
  3154. QDomDocument includedDoc;
  3155. QDomDocumentFragment fragment;
  3156. for(int i = 0; i < children.size(); i++)
  3157. {
  3158. QDomNode currentNode = children.at(i);
  3159. QDomElement currentElement;
  3160. if(currentNode.nodeName() == "include")
  3161. {
  3162. currentElement = currentNode.toElement();
  3163. if(currentElement.hasAttribute("src"))
  3164. {
  3165. replacementDoc = directory.path();
  3166. replacementDoc.append('/');
  3167. replacementDoc.append(currentElement.attribute("src"));
  3168. QFile doc(replacementDoc);
  3169. if(doc.open(QIODevice::ReadOnly))
  3170. {
  3171. includedDoc.setContent(&doc, true);
  3172. fragment = includedDoc.createDocumentFragment();
  3173. fragment.appendChild(includedDoc.documentElement());
  3174. root.replaceChild(fragment, currentNode);
  3175. doc.close();
  3176. }
  3177. }
  3178. }
  3179. }
  3180. @ Simply loading the configuration document does not display a user interface or
  3181. set up any objects that allow the program to do anything. To do this, a script
  3182. obtained from the configuration document is run. The root element of the
  3183. document should be {\tt <application>}. This element should have a number of
  3184. child elements including {\tt <window>} elements which describe the various
  3185. windows that can be opened in the application and {\tt <program>} elements
  3186. containing script code. These {\tt <program>} elements can occur in a number of
  3187. different contexts including within {\tt <window>} elements which would indicate
  3188. that such scripts should be evaluated when the window being described is
  3189. created. After the configuration document is loaded, all {\tt <program>}
  3190. elements that are direct children of the {\tt <application>} element are
  3191. concatenated and the script is run.
  3192. Before the script is run and user interface elements are drawn, we also check
  3193. for {\tt <style>} elements which can be used to set up a stylesheet for the
  3194. application.
  3195. @<Find and evaluate starting script@>=
  3196. QString styleText;
  3197. QString programText;
  3198. QDomElement currentElement;
  3199. for(int i = 0; i < children.size(); i++)
  3200. {
  3201. QDomNode currentNode = children.at(i);
  3202. if(currentNode.nodeName() == "style")
  3203. {
  3204. currentElement = currentNode.toElement();
  3205. styleText.append(currentElement.text());
  3206. }
  3207. else if(currentNode.nodeName() == "program")
  3208. {
  3209. currentElement = currentNode.toElement();
  3210. programText.append(currentElement.text());
  3211. }
  3212. }
  3213. app.setStyleSheet(styleText);
  3214. QScriptValue result = engine->evaluate(programText);
  3215. @<Report scripting errors@>
  3216. @ When a script is evaluated, there is a chance that there will be some error in
  3217. the execution of that script. If this occurs, we want to report that.
  3218. @<Report scripting errors@>=
  3219. if(engine->hasUncaughtException())
  3220. {
  3221. int line = engine->uncaughtExceptionLineNumber();
  3222. qDebug() << "Uncaught excpetion at line " << line << " : " <<
  3223. result.toString();
  3224. QString trace;
  3225. foreach(trace, engine->uncaughtExceptionBacktrace())
  3226. {
  3227. qDebug() << trace;
  3228. }
  3229. }
  3230. @* Creating a window.
  3231. \noindent When a configuration document is loaded, none of the {\tt <window>}
  3232. elements are interpreted or used to create a graphical user interface. Instead,
  3233. any {\tt <program>} elements that are immediate children of the
  3234. {\tt <application>} element are interpreted. In order to convert a
  3235. {\tt <window>} element into a window displayed on screen, the script in the
  3236. {\tt <program>} elements must call a function to display a specified window.
  3237. \danger This design works, but it's not particularly good design. It was written
  3238. under severe time constraints and should be redesigned or at least cleaned up
  3239. and reorganized.\endanger
  3240. @<Function prototypes for scripting@>=
  3241. QScriptValue createWindow(QScriptContext *context, QScriptEngine *engine);
  3242. void addLayoutToWidget(QDomElement element, QStack<QWidget*> *widgetStack,
  3243. QStack<QLayout*> *layoutStack);
  3244. void addLayoutToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3245. QStack<QLayout *> *layoutStack);
  3246. void addSplitterToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3247. QStack<QLayout *> *layoutStack);
  3248. void addSplitterToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  3249. QStack<QLayout *> *layoutStack);
  3250. void populateGridLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3251. QStack<QLayout *> *layoutStack);
  3252. void populateBoxLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3253. QStack<QLayout *> *layoutStack);
  3254. void populateSplitter(QDomElement element, QStack<QWidget *> *widgetStack,@|
  3255. QStack<QLayout *> *layoutStack);
  3256. void populateWidget(QDomElement element, QStack<QWidget *> *widgetStack,@|
  3257. QStack<QLayout *> *layoutStack);
  3258. void populateStackedLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3259. QStack<QLayout *> *layoutStack);
  3260. void addTemperatureDisplayToSplitter(QDomElement element,@|
  3261. QStack<QWidget *> *widgetStack,
  3262. QStack<QLayout *> *layoutStack);
  3263. void addTemperatureDisplayToLayout(QDomElement element,@|
  3264. QStack<QWidget *> *widgetStack,
  3265. QStack<QLayout *> *layoutStack);
  3266. void addTimerDisplayToSplitter(QDomElement element,@|
  3267. QStack<QWidget *> *widgetStack,
  3268. QStack<QLayout *> *layoutStack);
  3269. void addTimerDisplayToLayout(QDomElement element,@|
  3270. QStack<QWidget *> *widgetStack,
  3271. QStack<QLayout *> *layoutStack);
  3272. void addDecorationToSplitter(QDomElement element,@|
  3273. QStack<QWidget *> *widgetStack,
  3274. QStack<QLayout *> *layoutStack);
  3275. void addDecorationToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3276. QStack<QLayout *> *layoutStack);
  3277. void addWidgetToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  3278. QStack<QLayout *> *layoutStack);
  3279. void addButtonToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3280. QStack<QLayout *> *layoutStack);
  3281. void addZoomLogToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  3282. QStack<QLayout *> *layoutStack);
  3283. void addGraphToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  3284. QStack<QLayout *> *layoutStack);
  3285. void addSqlDropToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3286. QStack<QLayout *> *layoutStack);
  3287. void addSaltToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  3288. QStack<QLayout *> *layoutStack);
  3289. void addLineToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  3290. QStack<QLayout *> *layoutStack);
  3291. void addTextToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  3292. QStack<QLayout *> *layoutStack);
  3293. void addSqlQueryViewToLayout(QDomElement element,
  3294. QStack<QWidget *> *widgetStack,
  3295. QStack<QLayout *> *layoutStack);
  3296. void addCalendarToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3297. QStack<QLayout *> *layoutStack);
  3298. void addSpinBoxToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3299. QStack<QLayout *> *layoutStack);
  3300. @ The function for creating the window must be made available to the scripting
  3301. engine.
  3302. @<Set up the scripting engine@>=
  3303. engine->globalObject().setProperty("createWindow",
  3304. engine->newFunction(createWindow));
  3305. @ This function must examine the configuration document in search of the
  3306. appropriate window element, parse the contents of that element, and create a
  3307. multitude of objects, all of which must be passed to the scripting engine.
  3308. @<Functions for scripting@>=
  3309. QScriptValue createWindow(QScriptContext *context, QScriptEngine *engine)@/
  3310. {
  3311. QString targetID = argument<QString>(0, context);
  3312. QDomNode element;
  3313. QScriptValue object;
  3314. @<Find the window element@>@;
  3315. if(!element.isNull())
  3316. {
  3317. @<Display the window@>@;
  3318. }
  3319. return object;
  3320. }
  3321. @ First we must locate the {\tt <window>} element. The most sensible way to do
  3322. this would require that each {\tt <window>} element has an ID attribute and
  3323. search the DOM tree for that ID. Unfortunately, as of this writing,
  3324. |QDomDocument::elementByID()| always returns a null element, so that won't work.
  3325. Instead, we search the tree for all {\tt <window>} elements and then examine
  3326. the resulting list to find the element with the appropriate ID.
  3327. @<Find the window element@>=
  3328. QDomNodeList windows =
  3329. AppInstance->configuration()->documentElement().elementsByTagName("window");
  3330. QDomNode nullNode;
  3331. int i = 0;
  3332. element = nullNode;
  3333. while(i < windows.count())
  3334. {
  3335. element = windows.at(i);
  3336. QDomNamedNodeMap attributes = element.attributes();
  3337. if(attributes.contains("id"))
  3338. {
  3339. if(attributes.namedItem("id").toAttr().value() == targetID)
  3340. {
  3341. break;
  3342. }
  3343. }
  3344. element = nullNode;
  3345. i++;
  3346. }
  3347. @ In order to display a window, we start by creating a new |ScriptQMainWindow|
  3348. and set the central widget of that window to a new |QWidget|. After this, we see
  3349. if the window element has any children and proceed to populate the window.
  3350. When creating child elements, care must be taken that all objects are descended
  3351. from the window. If an object is descended from the window and has an object
  3352. name, it will be possible for script code to recover the created object.
  3353. As of version 1.4, the window itself is given the value of its {\tt id}
  3354. attribute as an object name to facilitate automatic window geometry management.
  3355. @<Display the window@>=
  3356. ScriptQMainWindow *window = new ScriptQMainWindow;
  3357. window->setObjectName(targetID);
  3358. object = engine->newQObject(window);
  3359. setQMainWindowProperties(object, engine);
  3360. QWidget *central = new(QWidget);
  3361. central->setParent(window);
  3362. central->setObjectName("centralWidget");
  3363. window->setCentralWidget(central);
  3364. if(element.hasChildNodes())
  3365. {
  3366. @<Process window children@>@;
  3367. }
  3368. if(window)
  3369. {
  3370. window->show();
  3371. }
  3372. else
  3373. {
  3374. qDebug() << "Error! Window invalidated";
  3375. }
  3376. @ Three element types make sense as top level children of a {\tt <window>}
  3377. element. An element representing a layout element can be used to apply that
  3378. layout to the central widget. An element representing a menu can be used to add
  3379. a menu to the window. A {\tt <program>} element can be used to specify a script
  3380. to be run after the window has been assembled.
  3381. \danger As the window comes with a blank central widget, elements representing
  3382. a widget to be used as the central widget of the window cannot be used directly
  3383. here. If only one widget is needed in the window, there is a need to create a
  3384. layout element and place that widget in the layout. Also note that there is not
  3385. enough error checking in the following code. Provide invalid input at your
  3386. peril.\endanger
  3387. Program fragments pulled from the window description are executed with the
  3388. newly created window available as {\tt this}. When such a fragment is run, the
  3389. entire description of the window will have already been evaluated and any
  3390. necessary objects created. Obtaining a child object of the window can be done
  3391. by calling |findChildObject()|.
  3392. @<Process window children@>=
  3393. QStack<QWidget*> widgetStack;
  3394. QStack<QLayout*> layoutStack;
  3395. QString windowScript;
  3396. widgetStack.push(central);
  3397. QDomNodeList windowChildren = element.childNodes();
  3398. int i = 0;
  3399. while(i < windowChildren.count())
  3400. {
  3401. QDomNode current;
  3402. QDomElement element;
  3403. current = windowChildren.at(i);
  3404. if(current.isElement())
  3405. {
  3406. element = current.toElement();
  3407. if(element.tagName() == "program")
  3408. {
  3409. windowScript.append(element.text());
  3410. }
  3411. else if(element.tagName() == "layout")
  3412. {
  3413. addLayoutToWidget(element, &widgetStack, &layoutStack);
  3414. }
  3415. else if(element.tagName() == "menu")
  3416. {
  3417. @<Process menus@>@;
  3418. }
  3419. }
  3420. i++;
  3421. }
  3422. QScriptValue oldThis = context->thisObject();
  3423. context->setThisObject(object);
  3424. QScriptValue result = engine->evaluate(windowScript);
  3425. @<Report scripting errors@>@;
  3426. context->setThisObject(oldThis);
  3427. @ Elements representing menus may provide a number of child elements
  3428. representing the items in that menu. The XML portion of the configuration will
  3429. not provide any information on what these menu items do. The contents of the
  3430. {\tt <program>} element for the window will need to request the |QAction|
  3431. objects and connect a signal from that object to the desired functionality.
  3432. One special consideration is the Reports menu. This menu will populate itself
  3433. according to its own logic and will have a {\tt type} property of
  3434. {\tt "reports"} and a {\tt src} property indicating the directory where reports
  3435. can be found.
  3436. @<Process menus@>=
  3437. QMenuBar *bar = window->menuBar();
  3438. bar->setParent(window);
  3439. bar->setObjectName("menuBar");
  3440. if(element.hasAttribute("name"))
  3441. {
  3442. QMenu *menu = bar->addMenu(element.attribute("name"));
  3443. menu->setParent(bar);
  3444. if(element.hasAttribute("type"))
  3445. {
  3446. if(element.attribute("type") == "reports")
  3447. {
  3448. if(element.hasAttribute("src"))
  3449. {
  3450. @<Populate reports menu@>@;
  3451. }
  3452. }
  3453. }
  3454. if(element.hasChildNodes())
  3455. {
  3456. @<Process menu items@>@;
  3457. }
  3458. }
  3459. @ To add items to a menu, we check for {\tt <item>} elements under the
  3460. {\tt <menu>} element and create a |QAction| for each item.
  3461. @<Process menu items@>=
  3462. QDomNodeList menuItems = element.childNodes();
  3463. int j = 0;
  3464. while(j < menuItems.count())
  3465. {
  3466. QDomNode item = menuItems.at(j);
  3467. if(item.isElement())
  3468. {
  3469. QDomElement itemElement = item.toElement();
  3470. if(itemElement.tagName() == "item")
  3471. {
  3472. QAction *itemAction = new QAction(itemElement.text(), menu);
  3473. if(itemElement.hasAttribute("id"))
  3474. {
  3475. itemAction->setObjectName(itemElement.attribute("id"));
  3476. }
  3477. if(itemElement.hasAttribute("shortcut"))
  3478. {
  3479. itemAction->setShortcut(itemElement.attribute("shortcut"));
  3480. }
  3481. menu->addAction(itemAction);
  3482. }
  3483. else if(itemElement.tagName() == "separator")
  3484. {
  3485. menu->addSeparator();
  3486. }
  3487. }
  3488. j++;
  3489. }
  3490. @ A layout can contain a number of different elements including a variety of
  3491. widget types and other layouts. This function is responsible for applying any
  3492. layout class to the widget currently being populated and processing children of
  3493. the {\tt <layout>} element to populate that layout. External stacks are used to
  3494. keep track of which widgets and layouts are currently being populated. The
  3495. {\tt type} attribute is used to determine what sort of layout should be created.
  3496. Currently, {\tt horizontal}, {\tt vertical}, {\tt grid}, and {\tt stack} types
  3497. are supported. The first two resolve to |QBoxLayout| layouts, {\tt grid}
  3498. resolves to a |QGridLayout|, and {\tt stack} resolves to a |QStackedLayout|.
  3499. @<Functions for scripting@>=
  3500. void addLayoutToWidget(QDomElement element, QStack<QWidget*> *widgetStack,
  3501. QStack<QLayout*> *layoutStack)
  3502. {
  3503. if(element.hasAttribute("type"))
  3504. {
  3505. @<Create and populate layout@>@;
  3506. QWidget *widget = widgetStack->top();
  3507. if(layout)
  3508. {
  3509. widget->setLayout(layout);
  3510. }
  3511. layoutStack->pop();
  3512. }
  3513. }
  3514. @ As there are multiple places where a {\tt <layout>} element is parsed with
  3515. slightly different semantics, the code for creating and populating the layout is
  3516. broken out so that code written to support additional layout types only needs to
  3517. be written once.
  3518. @<Create and populate layout@>=
  3519. QLayout *layout;
  3520. QString layoutType = element.attribute("type");
  3521. if(layoutType == "horizontal")
  3522. {
  3523. layout = new QHBoxLayout;
  3524. layoutStack->push(layout);
  3525. populateBoxLayout(element, widgetStack, layoutStack);
  3526. }
  3527. else if(layoutType == "vertical")
  3528. {
  3529. layout = new QVBoxLayout;
  3530. layoutStack->push(layout);
  3531. populateBoxLayout(element, widgetStack, layoutStack);
  3532. }
  3533. else if(layoutType == "grid")
  3534. {
  3535. layout = new QGridLayout;
  3536. layoutStack->push(layout);
  3537. populateGridLayout(element, widgetStack, layoutStack);
  3538. }
  3539. else if(layoutType == "stack")
  3540. {
  3541. layout = new QStackedLayout;
  3542. layoutStack->push(layout);
  3543. populateStackedLayout(element, widgetStack, layoutStack);
  3544. }
  3545. if(element.hasAttribute("id"))
  3546. {
  3547. layout->setObjectName(element.attribute("id"));
  3548. }
  3549. @ Stacked layouts are a bit different from the other types. A stacked layout has
  3550. an arbitrary number of {\tt <page>} children which are just a |QWidget| which
  3551. can have the same child elements as {\tt <widget>} elements elsewhere. Only the
  3552. first page will be visible initially, however it is possible to use script code
  3553. to set the currently visible page provided that an ID is set for the layout.
  3554. @<Functions for scripting@>=
  3555. void populateStackedLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3556. QStack<QLayout *> *layoutStack)
  3557. {
  3558. QDomNodeList children = element.childNodes();
  3559. QStackedLayout *layout = qobject_cast<QStackedLayout *>(layoutStack->top());
  3560. for(int i = 0; i < children.count(); i++)
  3561. {
  3562. QDomNode current;
  3563. QDomElement currentElement;
  3564. current = children.at(i);
  3565. if(current.isElement())
  3566. {
  3567. currentElement = current.toElement();
  3568. if(currentElement.tagName() == "page")
  3569. {
  3570. QWidget *widget = new QWidget;
  3571. layout->addWidget(widget);
  3572. widgetStack->push(widget);
  3573. populateWidget(currentElement, widgetStack, layoutStack);
  3574. widgetStack->pop();
  3575. }
  3576. }
  3577. }
  3578. }
  3579. @ Using a grid layout is a bit different from using a box layout. Child elements
  3580. with various attributes are required to take full advantage of this layout type.
  3581. All direct children of a grid layout element should be {\tt <row>} elements
  3582. which may have optional {\tt height} and {\tt stretch} attributes which apply to
  3583. that row.
  3584. @<Functions for scripting@>=
  3585. void populateGridLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3586. QStack<QLayout *> *layoutStack)
  3587. {
  3588. QDomNodeList children = element.childNodes();
  3589. int row = -1;
  3590. QGridLayout *layout = qobject_cast<QGridLayout *>(layoutStack->top());
  3591. for(int i = 0; i < children.count(); i++)
  3592. {
  3593. QDomNode current;
  3594. QDomElement currentElement;
  3595. current = children.at(i);
  3596. if(current.isElement())
  3597. {
  3598. currentElement = current.toElement();
  3599. if(currentElement.tagName() == "row")
  3600. {
  3601. row++;
  3602. if(currentElement.hasAttribute("height"))
  3603. {
  3604. layout->setRowMinimumHeight(row,
  3605. currentElement.attribute("height").toInt());
  3606. }
  3607. if(currentElement.hasAttribute("stretch"))
  3608. {
  3609. layout->setRowStretch(row,
  3610. currentElement.attribute("stretch").toInt());
  3611. }
  3612. @<Populate grid layout row@>@;
  3613. }
  3614. }
  3615. }
  3616. }
  3617. @ Each {\tt <row>} may have arbitrarily many {\tt <column>} children. A row with
  3618. nothing in it or that is entirely populated by spanning cells from previous rows
  3619. might have no children.
  3620. The {\tt <column>} element supports several optional attributes. The
  3621. {\tt column} attribute can be used to specify which column the element refers
  3622. to. Sibling {\tt <column>} elements will refer to columns farther right unless
  3623. a lower column number is specified. This does mean that it is possible to
  3624. specify the same column more than once, however actually doing so is not
  3625. recommended. The {\tt width} attribute specifies the minimum width of the
  3626. column. If multiple cells in a column specify this attribute, the last one takes
  3627. priority. Similarly, the {\tt stretch} attribute specifies the column stretch.
  3628. The {\tt rowspan} and {\tt colspan} attributes can be used for cells that span
  3629. more than one row or column. A value of |-1| can be used to have the cell span
  3630. to the last row or column in the layout.
  3631. Once the attributes of the cell are known, a |QHBoxLayout| is added to the
  3632. layout at the appropriate location in the grid and it is this layout which is
  3633. further populated by child elements. Anything that can be placed under a
  3634. {\tt <layout>} element with {\tt "horizontal"} or {\tt "vertical"} {\tt type}
  3635. attribute can be a child of a {\tt <column>} element in this context.
  3636. @<Populate grid layout row@>=
  3637. int column = -1;
  3638. QDomNodeList rowChildren = currentElement.childNodes();
  3639. for(int j = 0; j < rowChildren.count(); j++)
  3640. {
  3641. QDomNode columnNode;
  3642. QDomElement columnElement;
  3643. columnNode = rowChildren.at(j);
  3644. if(columnNode.isElement())
  3645. {
  3646. columnElement = columnNode.toElement();
  3647. if(columnElement.tagName() == "column")
  3648. {
  3649. column++;
  3650. if(columnElement.hasAttribute("column"))
  3651. {
  3652. column = columnElement.attribute("column").toInt();
  3653. }
  3654. if(columnElement.hasAttribute("width"))
  3655. {
  3656. layout->setColumnMinimumWidth(column,
  3657. columnElement.attribute("width").toInt());
  3658. }
  3659. if(columnElement.hasAttribute("stretch"))
  3660. {
  3661. layout->setColumnStretch(column,
  3662. columnElement.attribute("stretch").toInt());
  3663. }
  3664. int hspan = 1;
  3665. int vspan = 1;
  3666. if(columnElement.hasAttribute("rowspan"))
  3667. {
  3668. vspan = columnElement.attribute("rowspan").toInt();
  3669. }
  3670. if(columnElement.hasAttribute("colspan"))
  3671. {
  3672. hspan = columnElement.attribute("colspan").toInt();
  3673. }
  3674. QHBoxLayout *cell = new QHBoxLayout;
  3675. layout->addLayout(cell, row, column, vspan, hspan);
  3676. layoutStack->push(cell);
  3677. populateBoxLayout(columnElement, widgetStack, layoutStack);
  3678. layoutStack->pop();
  3679. }
  3680. }
  3681. }
  3682. @ Box layouts are populated by checking for child elements representing
  3683. supported widget types and layouts and adding these to the current layout.
  3684. @<Functions for scripting@>=
  3685. void populateBoxLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3686. QStack<QLayout *> *layoutStack)
  3687. {
  3688. QDomNodeList children = element.childNodes();
  3689. for(int i = 0; i < children.count(); i++)
  3690. {
  3691. QDomNode current;
  3692. QDomElement currentElement;
  3693. current = children.at(i);
  3694. if(current.isElement())
  3695. {
  3696. currentElement = current.toElement();
  3697. if(currentElement.tagName() == "button")
  3698. {
  3699. addButtonToLayout(currentElement, widgetStack, layoutStack);
  3700. }
  3701. else if(currentElement.tagName() == "calendar")
  3702. {
  3703. addCalendarToLayout(currentElement, widgetStack, layoutStack);
  3704. }
  3705. else if(currentElement.tagName() == "decoration")
  3706. {
  3707. addDecorationToLayout(currentElement, widgetStack,
  3708. layoutStack);
  3709. }
  3710. else if(currentElement.tagName() == "layout")
  3711. {
  3712. addLayoutToLayout(currentElement, widgetStack, layoutStack);
  3713. }
  3714. else if(currentElement.tagName() == "splitter")
  3715. {
  3716. addSplitterToLayout(currentElement, widgetStack, layoutStack);
  3717. }
  3718. else if(currentElement.tagName() == "label")
  3719. {
  3720. QBoxLayout *layout =
  3721. qobject_cast<QBoxLayout *>(layoutStack->top());
  3722. QLabel *label = new QLabel(currentElement.text());
  3723. layout->addWidget(label);
  3724. }
  3725. else if(currentElement.tagName() == "lcdtemperature")
  3726. {
  3727. addTemperatureDisplayToLayout(currentElement, widgetStack,
  3728. layoutStack);
  3729. }
  3730. else if(currentElement.tagName() == "lcdtimer")
  3731. {
  3732. addTimerDisplayToLayout(currentElement, widgetStack,
  3733. layoutStack);
  3734. }
  3735. else if(currentElement.tagName() == "line")
  3736. {
  3737. addLineToLayout(currentElement, widgetStack, layoutStack);
  3738. }
  3739. else if(currentElement.tagName() == "report")
  3740. {
  3741. addReportToLayout(currentElement, widgetStack, layoutStack);
  3742. }
  3743. else if(currentElement.tagName() == "sqldrop")
  3744. {
  3745. addSqlDropToLayout(currentElement, widgetStack, layoutStack);
  3746. }
  3747. else if(currentElement.tagName() == "sqltablearray")
  3748. {
  3749. addSaltToLayout(currentElement, widgetStack, layoutStack);
  3750. }
  3751. else if(currentElement.tagName() == "sqlview")
  3752. {
  3753. addSqlQueryViewToLayout(currentElement, widgetStack,
  3754. layoutStack);
  3755. }
  3756. else if(currentElement.tagName() == "textarea")
  3757. {
  3758. addTextToLayout(currentElement, widgetStack, layoutStack);
  3759. }
  3760. else if(currentElement.tagName() == "spinbox")
  3761. {
  3762. addSpinBoxToLayout(currentElement, widgetStack, layoutStack);
  3763. }
  3764. else if(currentElement.tagName() == "formarray")
  3765. {
  3766. addFormArrayToLayout(currentElement, widgetStack, layoutStack);
  3767. }
  3768. else if(currentElement.tagName() =="hscale")
  3769. {
  3770. addScaleControlToLayout(currentElement, widgetStack,
  3771. layoutStack);
  3772. }
  3773. else if(currentElement.tagName() == "vscale")
  3774. {
  3775. addIntensityControlToLayout(currentElement, widgetStack,
  3776. layoutStack);
  3777. }
  3778. else if(currentElement.tagName() == "webview")
  3779. {
  3780. addWebViewToLayout(currentElement, widgetStack, layoutStack);
  3781. }
  3782. else if(currentElement.tagName() == "stretch")
  3783. {
  3784. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  3785. layout->addStretch();
  3786. }
  3787. }
  3788. }
  3789. }
  3790. @ Box layouts support adding additional layouts to the layout. The form of the
  3791. function is very similar to |addLayoutToWidget()|.
  3792. @<Functions for scripting@>=
  3793. void addLayoutToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3794. QStack<QLayout *> *layoutStack)
  3795. {
  3796. QLayout *targetLayout = layoutStack->pop();
  3797. QBoxLayout *boxLayout = qobject_cast<QBoxLayout *>(targetLayout);
  3798. if(element.hasAttribute("type"))
  3799. {
  3800. @<Create and populate layout@>@;
  3801. boxLayout->addLayout(layout);
  3802. layoutStack->pop();
  3803. }
  3804. layoutStack->push(targetLayout);
  3805. }
  3806. @ A splitter is similar to a layout in that it manages the size and position of
  3807. one or more widgets, however it is not a layout and therefore needs to be
  3808. handled separately.
  3809. @<Functions for scripting@>=
  3810. void addSplitterToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3811. QStack<QLayout *> *layoutStack)
  3812. {
  3813. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  3814. QSplitter *splitter = new(QSplitter);
  3815. layout->addWidget(splitter);
  3816. @<Set up splitter@>@;
  3817. }
  3818. @ As there are multiple places where a splitter element must be examined, the
  3819. common code is set aside.
  3820. @<Set up splitter@>=
  3821. QString orientation = element.attribute("type");
  3822. if(orientation == "horizontal")
  3823. {
  3824. splitter->setOrientation(Qt::Horizontal);
  3825. }
  3826. else if(orientation == "vertical")
  3827. {
  3828. splitter->setOrientation(Qt::Vertical);
  3829. }
  3830. QString id = element.attribute("id");
  3831. if(!id.isEmpty())
  3832. {
  3833. splitter->setObjectName(id);
  3834. }
  3835. if(element.hasChildNodes())
  3836. {
  3837. widgetStack->push(splitter);
  3838. populateSplitter(element, widgetStack, layoutStack);
  3839. widgetStack->pop();
  3840. }
  3841. @ When populating a splitter, it is important to note that only widgets can be
  3842. added. If a layout is needed, this can be handled by adding a |QWidget| and
  3843. applying the layout to that widget.
  3844. @<Functions for scripting@>=
  3845. void populateSplitter(QDomElement element, QStack<QWidget *> *widgetStack,@|
  3846. QStack<QLayout *> *layoutStack)
  3847. {
  3848. QDomNodeList children = element.childNodes();
  3849. for(int i = 0; i < children.count(); i++)
  3850. {
  3851. QDomNode current;
  3852. QDomElement currentElement;
  3853. current = children.at(i);
  3854. if(current.isElement())
  3855. {
  3856. currentElement = current.toElement();
  3857. if(currentElement.tagName() == "decoration")
  3858. {
  3859. addDecorationToSplitter(currentElement, widgetStack,
  3860. layoutStack);
  3861. }
  3862. else if(currentElement.tagName() == "graph")
  3863. {
  3864. addGraphToSplitter(currentElement, widgetStack, layoutStack);
  3865. }
  3866. else if(currentElement.tagName() == "splitter")
  3867. {
  3868. addSplitterToSplitter(currentElement, widgetStack, layoutStack);
  3869. }
  3870. else if(currentElement.tagName() == "lcdtemperature")
  3871. {
  3872. addTemperatureDisplayToSplitter(currentElement, widgetStack,
  3873. layoutStack);
  3874. }
  3875. else if(currentElement.tagName() == "lcdtimer")
  3876. {
  3877. addTimerDisplayToSplitter(currentElement, widgetStack,
  3878. layoutStack);
  3879. }
  3880. else if(currentElement.tagName() == "measurementtable")
  3881. {
  3882. addZoomLogToSplitter(currentElement, widgetStack, layoutStack);
  3883. }
  3884. else if(currentElement.tagName() == "widget")
  3885. {
  3886. addWidgetToSplitter(currentElement, widgetStack, layoutStack);
  3887. }
  3888. }
  3889. }
  3890. }
  3891. @ Adding a splitter to a splitter is similar to adding it to a layout.
  3892. @<Functions for scripting@>=
  3893. void addSplitterToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  3894. QStack<QLayout *> *layoutStack)
  3895. {
  3896. QSplitter *parent = qobject_cast<QSplitter *>(widgetStack->top());
  3897. QSplitter *splitter = new(QSplitter);
  3898. splitter->setParent(parent);
  3899. parent->addWidget(splitter);
  3900. @<Set up splitter@>@;
  3901. }
  3902. @ Temperature displays are useful to have in an application such as this. At
  3903. present, this code only supports the {\tt id} attribute. It may be useful in the
  3904. future to allow other attributes for changing default attributes of the
  3905. indicator rather than needing to pull the object from script code and set
  3906. changes there.
  3907. @<Functions for scripting@>=
  3908. void addTemperatureDisplayToSplitter(QDomElement element,@|
  3909. QStack<QWidget *> *widgetStack,
  3910. QStack<QLayout *> *)
  3911. {
  3912. TemperatureDisplay *display = new(TemperatureDisplay);
  3913. if(element.hasAttribute("id"))
  3914. {
  3915. display->setObjectName(element.attribute("id"));
  3916. }
  3917. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  3918. splitter->addWidget(display);
  3919. }
  3920. void addTemperatureDisplayToLayout(QDomElement element,@|
  3921. QStack<QWidget *> *,
  3922. QStack<QLayout *> *layoutStack)
  3923. {
  3924. TemperatureDisplay *display = new(TemperatureDisplay);
  3925. if(element.hasAttribute("id"))
  3926. {
  3927. display->setObjectName(element.attribute("id"));
  3928. }
  3929. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  3930. layout->addWidget(display);
  3931. }
  3932. @ Timer displays are similarly useful to have. The default format for a timer
  3933. display is {\tt hh:mm:ss}, but this can be changed through the {\tt format}
  3934. attribute of an {\tt <lcdtimer>} element.
  3935. @<Functions for scripting@>=
  3936. void addTimerDisplayToSplitter(QDomElement element,@|
  3937. QStack<QWidget *> *widgetStack,
  3938. QStack<QLayout *> *)
  3939. {
  3940. TimerDisplay *display = new(TimerDisplay);
  3941. if(element.hasAttribute("id"))
  3942. {
  3943. display->setObjectName(element.attribute("id"));
  3944. }
  3945. if(element.hasAttribute("format"))
  3946. {
  3947. display->setDisplayFormat(element.attribute("format"));
  3948. }
  3949. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  3950. splitter->addWidget(display);
  3951. }
  3952. void addTimerDisplayToLayout(QDomElement element,@|
  3953. QStack<QWidget *> *,
  3954. QStack<QLayout *> *layoutStack)
  3955. {
  3956. TimerDisplay *display = new(TimerDisplay);
  3957. if(element.hasAttribute("id"))
  3958. {
  3959. display->setObjectName(element.attribute("id"));
  3960. }
  3961. if(element.hasAttribute("format"))
  3962. {
  3963. display->setDisplayFormat(element.attribute("format"));
  3964. }
  3965. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  3966. layout->addWidget(display);
  3967. }
  3968. @ When multiple timer or temperature displays are required, it can be useful to
  3969. provide a label to indicate just what is being measured.
  3970. @<Functions for scripting@>=
  3971. void addDecorationToLayout(QDomElement element, QStack<QWidget *> *,@|
  3972. QStack<QLayout *> *layoutStack)
  3973. {
  3974. @<Set up decoration@>@;
  3975. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  3976. layout->addWidget(decoration);
  3977. }
  3978. void addDecorationToSplitter(QDomElement element,
  3979. QStack<QWidget *> *widgetStack,
  3980. QStack<QLayout *> *)
  3981. {
  3982. @<Set up decoration@>@;
  3983. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  3984. splitter->addWidget(decoration);
  3985. }
  3986. @ The decoration needs a label text, an orientation, and the widget to be
  3987. labeled.
  3988. @<Set up decoration@>=
  3989. QString labelText = element.attribute("name");
  3990. Qt::Orientations@, orientation = Qt::Horizontal;
  3991. if(element.hasAttribute("type"))
  3992. {
  3993. if(element.attribute("type") == "horizontal")
  3994. {
  3995. orientation = Qt::Horizontal;
  3996. }
  3997. else if(element.attribute("type") == "vertical")
  3998. {
  3999. orientation = Qt::Vertical;
  4000. }
  4001. }
  4002. @<Find widget to decorate@>@;
  4003. WidgetDecorator *decoration = new WidgetDecorator(theWidget, labelText,
  4004. orientation);
  4005. if(element.hasAttribute("id"))
  4006. {
  4007. decoration->setObjectName(element.attribute("id"));
  4008. }
  4009. @ The widget to decorate should be found as a child of the {\tt <decoration>}
  4010. element.
  4011. @<Find widget to decorate@>=
  4012. QWidget *theWidget = NULL;
  4013. QDomNodeList children = element.childNodes();
  4014. for(int i = 0; i < children.count(); i++)
  4015. {
  4016. QDomNode item = children.at(i);
  4017. if(item.isElement())
  4018. {
  4019. QDomElement itemElement = item.toElement();
  4020. if(itemElement.tagName() == "lcdtemperature")
  4021. {
  4022. TemperatureDisplay *display = new TemperatureDisplay;
  4023. if(itemElement.hasAttribute("id"))
  4024. {
  4025. display->setObjectName(itemElement.attribute("id"));
  4026. }
  4027. theWidget = display;
  4028. }
  4029. else if(itemElement.tagName() == "lcdtimer")
  4030. {
  4031. TimerDisplay *display = new TimerDisplay;
  4032. if(itemElement.hasAttribute("id"))
  4033. {
  4034. display->setObjectName(itemElement.attribute("id"));
  4035. }
  4036. if(itemElement.hasAttribute("format"))
  4037. {
  4038. display->setDisplayFormat(itemElement.attribute("format"));
  4039. }
  4040. theWidget = display;
  4041. }
  4042. }
  4043. }
  4044. @ As splitters cannot contain layouts directly, there is a need to allow
  4045. otherwise empty widgets to be included in a splitter for cases where a splitter
  4046. should manage several widgets together as a group. A row of annotation buttons
  4047. is an example of such a layout.
  4048. @<Functions for scripting@>=
  4049. void addWidgetToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4050. QStack<QLayout *> *layoutStack)
  4051. {
  4052. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4053. QWidget *widget = new QWidget;
  4054. if(element.hasAttribute("id"))
  4055. {
  4056. widget->setObjectName(element.attribute("id"));
  4057. }
  4058. splitter->addWidget(widget);
  4059. if(element.hasChildNodes())
  4060. {
  4061. widgetStack->push(widget);
  4062. populateWidget(element, widgetStack, layoutStack);
  4063. widgetStack->pop();
  4064. }
  4065. }
  4066. void populateWidget(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4067. QStack<QLayout *> *layoutStack)
  4068. {
  4069. QDomNodeList children = element.childNodes();
  4070. for(int i = 0; i < children.count(); i++)
  4071. {
  4072. QDomNode current;
  4073. QDomElement currentElement;
  4074. current = children.at(i);
  4075. if(current.isElement())
  4076. {
  4077. currentElement = current.toElement();
  4078. if(currentElement.tagName() == "layout")
  4079. {
  4080. addLayoutToWidget(currentElement, widgetStack, layoutStack);
  4081. }
  4082. }
  4083. }
  4084. }
  4085. @ There are two types of buttons that can be added to a layout. There are normal
  4086. push buttons and there are annotation buttons. Other button types may be added
  4087. in the future.
  4088. @<Functions for scripting@>=
  4089. void addButtonToLayout(QDomElement element, QStack<QWidget *> *,@|
  4090. QStack<QLayout *> *layoutStack)
  4091. {
  4092. QAbstractButton *button = NULL;
  4093. QString text = element.attribute("name");
  4094. if(element.hasAttribute("type"))
  4095. {
  4096. QString type = element.attribute("type");
  4097. if(type == "annotation")
  4098. {
  4099. AnnotationButton *abutton = new AnnotationButton(text);
  4100. if(element.hasAttribute("annotation"))
  4101. {
  4102. abutton->setAnnotation(element.attribute("annotation"));
  4103. }
  4104. if(element.hasAttribute("series"))
  4105. {
  4106. abutton->setTemperatureColumn(element.attribute("series").
  4107. toInt());
  4108. }
  4109. if(element.hasAttribute("column"))
  4110. {
  4111. abutton->setAnnotationColumn(element.attribute("column").
  4112. toInt());
  4113. }
  4114. button = abutton;
  4115. }
  4116. else if(type == "check")
  4117. {
  4118. button = new QCheckBox(text);
  4119. }
  4120. else if(type == "push")
  4121. {
  4122. button = new QPushButton(text);
  4123. }
  4124. }
  4125. if(element.hasAttribute("id"))
  4126. {
  4127. button->setObjectName(element.attribute("id"));
  4128. }
  4129. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4130. layout->addWidget(button);
  4131. }
  4132. @ While annotation buttons are useful for many batch notes, a spin box is
  4133. sometimes a better input choice. There are several attributes that can be set on
  4134. a spin box. These include text to be included in the annotation before and after
  4135. the value of the spin box, the temperature and annotation columns, the range of
  4136. values available in the spin box, the precision of allowed values, and the
  4137. amount by which increment and decrement operations change the value.
  4138. @<Functions for scripting@>=
  4139. void addSpinBoxToLayout(QDomElement element, QStack<QWidget *> *,@|
  4140. QStack<QLayout *> *layoutStack)
  4141. {
  4142. AnnotationSpinBox *box = new AnnotationSpinBox("", "", NULL);
  4143. if(element.hasAttribute("pretext"))
  4144. {
  4145. box->setPretext(element.attribute("pretext"));
  4146. }
  4147. if(element.hasAttribute("posttext"))
  4148. {
  4149. box->setPosttext(element.attribute("posttext"));
  4150. }
  4151. if(element.hasAttribute("series"))
  4152. {
  4153. box->setTemperatureColumn(element.attribute("series").toInt());
  4154. }
  4155. if(element.hasAttribute("column"))
  4156. {
  4157. box->setAnnotationColumn(element.attribute("column").toInt());
  4158. }
  4159. if(element.hasAttribute("min"))
  4160. {
  4161. box->setMinimum(element.attribute("min").toDouble());
  4162. }
  4163. if(element.hasAttribute("max"))
  4164. {
  4165. box->setMaximum(element.attribute("max").toDouble());
  4166. }
  4167. if(element.hasAttribute("decimals"))
  4168. {
  4169. box->setDecimals(element.attribute("decimals").toInt());
  4170. }
  4171. if(element.hasAttribute("step"))
  4172. {
  4173. box->setSingleStep(element.attribute("step").toDouble());
  4174. }
  4175. if(element.hasAttribute("id"))
  4176. {
  4177. box->setObjectName(element.attribute("id"));
  4178. }
  4179. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4180. layout->addWidget(box);
  4181. }
  4182. @ Previously, in order to change a |ZoomLog| from the default set of columns,
  4183. script code would need to alter the column set. While this works fine on a Mac,
  4184. this did not work very well under Windows. For the current version, I would like
  4185. to remove the need to deal with table columns from the host environment. The
  4186. first step for this is allowing column descriptions in XML. After this, I'd like
  4187. to remove the default column set from the widget code and provide some better
  4188. functionality for dealing with additional data sets.
  4189. When creating the |ZoomLog| here, we check for {\tt <column>} child elements
  4190. which specify the names of the columns.
  4191. @<Functions for scripting@>=
  4192. void addZoomLogToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4193. QStack<QLayout *> *)
  4194. {
  4195. ZoomLog *widget = new ZoomLog;
  4196. if(!widget)
  4197. {
  4198. qDebug() << "Error constructing widget!";
  4199. }
  4200. if(element.hasAttribute("id"))
  4201. {
  4202. widget->setObjectName(element.attribute("id"));
  4203. }
  4204. if(element.hasChildNodes())
  4205. {
  4206. QDomNodeList children = element.childNodes();
  4207. int column = 0;
  4208. for(int i = 0; i < children.count(); i++)
  4209. {
  4210. QDomNode current;
  4211. QDomElement currentElement;
  4212. current = children.at(i);
  4213. if(current.isElement())
  4214. {
  4215. currentElement = current.toElement();
  4216. if(currentElement.tagName() == "column")
  4217. {
  4218. QString text = currentElement.text();
  4219. widget->setHeaderData(column, text);
  4220. column++;
  4221. }
  4222. }
  4223. }
  4224. }
  4225. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4226. if(splitter)
  4227. {
  4228. splitter->addWidget(widget);
  4229. }
  4230. else
  4231. {
  4232. qDebug() << "Splitter not found at top of widget stack!";
  4233. }
  4234. }
  4235. @ The last of the widgets needed to duplicate the window provided in previous
  4236. versions of \pn{} is the |GraphView|.
  4237. @<Functions for scripting@>=
  4238. void addGraphToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4239. QStack<QLayout *> *)
  4240. {
  4241. GraphView *view = new GraphView;
  4242. if(element.hasAttribute("id"))
  4243. {
  4244. view->setObjectName(element.attribute("id"));
  4245. }
  4246. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4247. splitter->addWidget(view);
  4248. }
  4249. @ When interacting with a database, it can be useful to provide a combo box
  4250. populated by the results of a database query. One way to do this is through a
  4251. |SqlComboBox| widget.
  4252. @<Functions for scripting@>=
  4253. void addSqlDropToLayout(QDomElement element, QStack<QWidget *> *,@|
  4254. QStack<QLayout *> *layoutStack)
  4255. {
  4256. SqlComboBox *box = new SqlComboBox();
  4257. if(element.hasAttribute("data"))
  4258. {
  4259. box->setDataColumn(element.attribute("data").toInt());
  4260. }
  4261. if(element.hasAttribute("display"))
  4262. {
  4263. box->setDisplayColumn(element.attribute("display").toInt());
  4264. }
  4265. if(element.hasAttribute("showdata"))
  4266. {
  4267. if(element.attribute("showdata") == "true")
  4268. {
  4269. box->showData(true);
  4270. }
  4271. }
  4272. if(element.hasAttribute("editable"))
  4273. {
  4274. if(element.attribute("editable") == "true")
  4275. {
  4276. box->setEditable(true);
  4277. }
  4278. }
  4279. if(element.hasChildNodes())
  4280. {
  4281. QDomNodeList children = element.childNodes();
  4282. for(int i = 0; i < children.count(); i++)
  4283. {
  4284. QDomNode current;
  4285. QDomElement currentElement;
  4286. current = children.at(i);
  4287. if(current.isElement())
  4288. {
  4289. currentElement = current.toElement();
  4290. if(currentElement.tagName() == "null")
  4291. {
  4292. box->addNullOption();
  4293. }
  4294. else if(currentElement.tagName() == "query")
  4295. {
  4296. box->addSqlOptions(currentElement.text());
  4297. }
  4298. }
  4299. }
  4300. }
  4301. if(element.hasAttribute("id"))
  4302. {
  4303. box->setObjectName(element.attribute("id"));
  4304. }
  4305. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4306. layout->addWidget(box);
  4307. }
  4308. @ The next database aware widget that can be useful to have in \pn{} is a
  4309. {\bf S}QL {\bf A}rray {\bf L}iteral {\bf T}able. As might be apparent from the
  4310. name, this is a table view with an associated model and delegates appropriate
  4311. for creating ordered arrays to pass into a database. Each column represents an
  4312. array of values. The most common use of this is in cases where it is important
  4313. to produce multiple arrays of the same size in which each element of one array
  4314. is related to the element in the same position of another array. For example,
  4315. when roasting coffee there are times when some may want to add more than one
  4316. coffee to the roaster at a time. In order to correctly track the green coffee
  4317. inventory and so that the roasting log may have an accurate record of what is
  4318. really happening, insertions on the roasting log provide two arrays, one
  4319. representing all of the coffees being added to the roaster, the other the amount
  4320. of each of these coffees. The database can then use a trigger function to
  4321. examine these arrays and produce the necessary entries in the use table which in
  4322. turn update the record containing the amount of each green coffee currently in
  4323. stock.
  4324. While a generic |QTableView| is used here, there is a need to add functionality
  4325. specific to using this table with a |SaltModel| when obtaining this widget from
  4326. the host environment. In order to accomodate this, we add a dynamic property to
  4327. the view to identify the type of table in the absense of a unique class name.
  4328. @<Functions for scripting@>=
  4329. void addSaltToLayout(QDomElement element, QStack<QWidget *> *,@|
  4330. QStack<QLayout *> *layoutStack)
  4331. {
  4332. QTableView *view = new QTableView;
  4333. view->setProperty("tabletype", QVariant(QString("SaltTable")));
  4334. SaltModel *model = new SaltModel(element.childNodes().count());
  4335. if(element.hasAttribute("id"))
  4336. {
  4337. view->setObjectName(element.attribute("id"));
  4338. }
  4339. if(element.hasChildNodes())
  4340. {
  4341. QDomNodeList children = element.childNodes();
  4342. int currentColumn = 0;
  4343. for(int i = 0; i < children.count(); i++)
  4344. {
  4345. QDomNode current;
  4346. QDomElement currentElement;
  4347. current = children.at(i);
  4348. if(current.isElement())
  4349. {
  4350. currentElement = current.toElement();
  4351. if(currentElement.tagName() == "column")
  4352. {
  4353. if(currentElement.hasAttribute("name"))
  4354. {
  4355. model->setHeaderData(currentColumn, Qt::Horizontal,
  4356. currentElement.attribute("name"));
  4357. }
  4358. if(currentElement.hasAttribute("delegate"))
  4359. {
  4360. @<Set column delegate from XML attribute@>@;
  4361. }
  4362. currentColumn++;
  4363. }
  4364. }
  4365. }
  4366. }
  4367. view->setModel(model);
  4368. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4369. layout->addWidget(view);
  4370. }
  4371. @ It is often desirable to restrict the allowed values in an entry to either a
  4372. set of specific values or to a particular type of value. Delegates can be set
  4373. on a column to enforce such restrictions.
  4374. @<Set column delegate from XML attribute@>=
  4375. if(currentElement.attribute("delegate") == "sql")
  4376. {
  4377. @<Assign column delegate from SQL@>@;
  4378. }
  4379. else if(currentElement.attribute("delegate") == "numeric")
  4380. {
  4381. @<Assign numeric column delegate@>@;
  4382. }
  4383. @ When using a |SaltModel|, there are times where the array values being
  4384. inserted are identification numbers representing some record that already exists
  4385. in the database. For example, the id number representing a green coffee in the
  4386. table of items. In such a case, it is beneficial to provide a delegate capable
  4387. of presenting a human readable list of choices.
  4388. @<Assign column delegate from SQL@>=
  4389. SqlComboBoxDelegate *delegate = new SqlComboBoxDelegate;
  4390. SqlComboBox *widget = new SqlComboBox();
  4391. if(currentElement.hasAttribute("null"))
  4392. {
  4393. if(currentElement.attribute("null") == "true")
  4394. {
  4395. widget->addNullOption();
  4396. }
  4397. }
  4398. if(currentElement.hasAttribute("showdata"))
  4399. {
  4400. if(currentElement.attribute("showdata") == "true")
  4401. {
  4402. widget->showData(true);
  4403. }
  4404. }
  4405. if(currentElement.hasAttribute("data"))
  4406. {
  4407. widget->setDataColumn(currentElement.attribute("data").toInt());
  4408. }
  4409. if(currentElement.hasAttribute("display"))
  4410. {
  4411. widget->setDisplayColumn(currentElement.attribute("display").toInt());
  4412. }
  4413. widget->addSqlOptions(currentElement.text());
  4414. delegate->setWidget(widget);
  4415. view->setItemDelegateForColumn(currentColumn, delegate);
  4416. @ Another common use is allowing numeric values. At present this only
  4417. restricts input to numbers, however it may be useful to provide other options
  4418. such as restricting the range of allowed values in the future.
  4419. @<Assign numeric column delegate@>=
  4420. NumericDelegate *delegate = new NumericDelegate;
  4421. view->setItemDelegateForColumn(currentColumn, delegate);
  4422. @ The |NumericDelegate| will only set the display value to a number, but it
  4423. will perform mathematical calculations that are entered into the editor as
  4424. well. This allows a person to type something like $13.26+5.06$ with the result
  4425. of the expression ($18.32$) appearing in the table.
  4426. @<Class declarations@>=
  4427. class NumericDelegate : public QItemDelegate@/
  4428. {
  4429. @[Q_OBJECT@]@;
  4430. public:@/
  4431. NumericDelegate(QObject *parent = NULL);
  4432. QWidget *createEditor(QWidget *parent,
  4433. const QStyleOptionViewItem &option,@|
  4434. const QModelIndex &index) const;
  4435. void setEditorData(QWidget *editor, const QModelIndex &index) const;
  4436. void setModelData(QWidget *editor, QAbstractItemModel *model,@|
  4437. const QModelIndex &index) const;
  4438. void updateEditorGeometry(QWidget *editor,
  4439. const QStyleOptionViewItem &option,@|
  4440. const QModelIndex &index) const;
  4441. };
  4442. @ There is nothing special about the constructor.
  4443. @<NumericDelegate implementation@>=
  4444. NumericDelegate::NumericDelegate(QObject *parent) :
  4445. QItemDelegate(parent)
  4446. {
  4447. /* Nothing needs to be done here. */
  4448. }
  4449. @ Two roles are used by this delegate. The edit role should contain whatever
  4450. text has been entered in the editor while the display role contain the numeric
  4451. result of any expression that has been entered. Our editor only requires the
  4452. first of these.
  4453. @<NumericDelegate implementation@>=
  4454. void NumericDelegate::setEditorData(QWidget *editor,
  4455. const QModelIndex &index) const
  4456. {
  4457. QString value = index.model()->data(index, Qt::EditRole).toString();
  4458. QLineEdit *line = static_cast<QLineEdit*>(editor);
  4459. line->setText(value);
  4460. }
  4461. @ When editing is finished, the expression text must be saved back to the
  4462. model and the expression should be evaluated to set the display role. We make
  4463. use of the existing scripting engine to evaluate the expression, but only
  4464. preserve the result in the display role if the result of that expression is
  4465. numeric.
  4466. @<NumericDelegate implementation@>=
  4467. void NumericDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
  4468. const QModelIndex &index) const
  4469. {
  4470. QLineEdit *line = static_cast<QLineEdit*>(editor);
  4471. model->setData(index, line->text(), Qt::EditRole);
  4472. QScriptEngine *engine = AppInstance->engine;
  4473. engine->pushContext();
  4474. QString script = QString("Number(%1)").arg(line->text());
  4475. QScriptValue result = engine->evaluate(line->text());
  4476. if(result.isNumber())
  4477. {
  4478. model->setData(index, result.toVariant(), Qt::DisplayRole);
  4479. }
  4480. else
  4481. {
  4482. model->setData(index, QVariant(), Qt::DisplayRole);
  4483. }
  4484. engine->popContext();
  4485. }
  4486. @ There is nothing special about the line edit used for this.
  4487. @<NumericDelegate implementation@>=
  4488. QWidget* NumericDelegate::createEditor(QWidget *parent,
  4489. const QStyleOptionViewItem &,
  4490. const QModelIndex &) const
  4491. {
  4492. return (new QLineEdit(parent));
  4493. }
  4494. @ To ensure that the editor is displayed appropriately, we must pass the
  4495. geometry data to our editor.
  4496. @<NumericDelegate implementation@>=
  4497. void NumericDelegate::updateEditorGeometry(QWidget *editor,
  4498. const QStyleOptionViewItem &option,
  4499. const QModelIndex &) const
  4500. {
  4501. editor->setGeometry(option.rect);
  4502. }
  4503. @ Line edits are useful when the user is expected to enter text without a
  4504. predetermined set of values.
  4505. Several attributes are supported on line edits. In addition to the usual
  4506. {\tt id} attribute, there is also a {\tt writable} attribute which, if
  4507. {\tt false}, can be used to create read only text areas which can only be edited
  4508. from script code. A {\tt validator} attribute allows entered text to be
  4509. restricted. This can take one of three values. If the value is {\tt "numeric"},
  4510. input is restricted to numeric values. If the value is {\tt "integer"}, input is
  4511. restricted to integer values. Finally, if the value is {\tt "expression"}, input
  4512. is restricted to text which matches a regular expression specified as the value
  4513. of the {\tt expression} attribute.
  4514. @<Functions for scripting@>=
  4515. void addLineToLayout(QDomElement element, QStack<QWidget *> *,@|
  4516. QStack<QLayout *> *layoutStack)
  4517. {
  4518. QLineEdit *widget = new QLineEdit(element.text());
  4519. if(element.hasAttribute("id"))
  4520. {
  4521. widget->setObjectName(element.attribute("id"));
  4522. }
  4523. if(element.hasAttribute("writable"))
  4524. {
  4525. if(element.attribute("writable") == "false")
  4526. {
  4527. widget->setReadOnly(true);
  4528. }
  4529. }
  4530. if(element.hasAttribute("validator"))
  4531. {
  4532. if(element.attribute("validator") == "numeric")
  4533. {
  4534. widget->setValidator(new QDoubleValidator(NULL));
  4535. }
  4536. else if(element.attribute("validator") == "integer")
  4537. {
  4538. widget->setValidator(new QIntValidator(NULL));
  4539. }
  4540. else if(element.attribute("validator") == "expression" &&
  4541. element.hasAttribute("expression"))
  4542. {
  4543. widget->setValidator(new QRegExpValidator(
  4544. QRegExp(element.attribute("expression")),
  4545. NULL));
  4546. }
  4547. }
  4548. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4549. layout->addWidget(widget);
  4550. }
  4551. @ It is natural for certain database fields to enter potentially large amounts
  4552. of free form text, for example, notes and annotations.
  4553. @<Functions for scripting@>=
  4554. void addTextToLayout(QDomElement element, QStack<QWidget *> *,@|
  4555. QStack<QLayout *> *layoutStack)
  4556. {
  4557. QTextEdit *widget = new QTextEdit;
  4558. if(element.hasAttribute("id"))
  4559. {
  4560. widget->setObjectName(element.attribute("id"));
  4561. }
  4562. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4563. layout->addWidget(widget);
  4564. }
  4565. @ The common use of |SqlQueryView| calls for the possibility of changing the
  4566. query during use. As such, there is little reason to accept attributes other
  4567. than an id for obtaining the view in a script.
  4568. @<Functions for scripting@>=
  4569. void addSqlQueryViewToLayout(QDomElement element,
  4570. QStack<QWidget *> *,@|
  4571. QStack<QLayout *> *layoutStack)
  4572. {
  4573. SqlQueryView *view = new SqlQueryView;
  4574. if(element.hasAttribute("id"))
  4575. {
  4576. view->setObjectName(element.attribute("id"));
  4577. }
  4578. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4579. layout->addWidget(view);
  4580. }
  4581. @ When the user is expected to enter a date, it is appropriate to use a date
  4582. editor. This one provides a calendar.
  4583. @<Functions for scripting@>=
  4584. void addCalendarToLayout(QDomElement element, QStack<QWidget *> *,@|
  4585. QStack<QLayout *> *layoutStack)
  4586. {
  4587. QDateEdit *widget = new QDateEdit;
  4588. widget->setCalendarPopup(true);
  4589. if(element.hasAttribute("id"))
  4590. {
  4591. widget->setObjectName(element.attribute("id"));
  4592. }
  4593. widget->setDate(QDate::currentDate());
  4594. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4595. layout->addWidget(widget);
  4596. }
  4597. @ Some additional properties are added to this object when it is retrieved by
  4598. the host environment.
  4599. @<Functions for scripting@>=
  4600. void setQDateEditProperties(QScriptValue value, QScriptEngine *engine)
  4601. {
  4602. setQDateTimeEditProperties(value, engine);
  4603. }
  4604. void setQDateTimeEditProperties(QScriptValue value, QScriptEngine *engine)
  4605. {
  4606. setQAbstractSpinBoxProperties(value, engine);
  4607. value.setProperty("setDate", engine->newFunction(QDateTimeEdit_setDate));
  4608. value.setProperty("day", engine->newFunction(QDateTimeEdit_day));
  4609. value.setProperty("month", engine->newFunction(QDateTimeEdit_month));
  4610. value.setProperty("year", engine->newFunction(QDateTimeEdit_year));
  4611. }
  4612. @ Certain operations on a |QDateEdit| are easier with a few convenience
  4613. properties that bypass the need to use the built in |date| property. For
  4614. example, an editor that should be set to 1 January of the current year can
  4615. obtain the year and set the date without directly using a |QDate| object.
  4616. @<Functions for scripting@>=
  4617. QScriptValue QDateTimeEdit_setDate(QScriptContext *context, QScriptEngine *)
  4618. {
  4619. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  4620. if(context->argumentCount() == 3)
  4621. {
  4622. self->setDate(QDate(argument<int>(0, context),
  4623. argument<int>(1, context),
  4624. argument<int>(2, context)));
  4625. }
  4626. else
  4627. {
  4628. context->throwError("Incorrect number of arguments passed to "
  4629. "QDateTimeEdit::setDate(). This method takes three integer arguments "
  4630. "specifying the year, month, and day.");
  4631. }
  4632. return QScriptValue();
  4633. }
  4634. QScriptValue QDateTimeEdit_day(QScriptContext *context, QScriptEngine *)
  4635. {
  4636. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  4637. return QScriptValue(self->date().day());
  4638. }
  4639. QScriptValue QDateTimeEdit_month(QScriptContext *context, QScriptEngine *)
  4640. {
  4641. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  4642. return QScriptValue(self->date().month());
  4643. }
  4644. QScriptValue QDateTimeEdit_year(QScriptContext *context, QScriptEngine *)
  4645. {
  4646. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  4647. return QScriptValue(self->date().year());
  4648. }
  4649. @ A few function prototypes are needed for this.
  4650. @<Function prototypes for scripting@>=
  4651. void setQDateEditProperties(QScriptValue value, QScriptEngine *engine);
  4652. void setQDateTimeEditProperties(QScriptValue value, QScriptEngine *engine);
  4653. QScriptValue QDateTimeEdit_setDate(QScriptContext *context,
  4654. QScriptEngine *engine);
  4655. QScriptValue QDateTimeEdit_day(QScriptContext *context, QScriptEngine *engine);
  4656. QScriptValue QDateTimeEdit_month(QScriptContext *context,
  4657. QScriptEngine *engine);
  4658. QScriptValue QDateTimeEdit_year(QScriptContext *context, QScriptEngine *engine);
  4659. @ In order to get to objects created from the XML description, it is necessary
  4660. to provide a function that can be called to retrieve children of a given widget.
  4661. When providing such an object to the script, it is necessary to determine the
  4662. type of that object and add the appropriate properties.
  4663. @<Function prototypes for scripting@>=
  4664. QScriptValue findChildObject(QScriptContext *context, QScriptEngine *engine);
  4665. @ This function must be made available to the scripting engine.
  4666. @<Set up the scripting engine@>=
  4667. engine->globalObject().setProperty("findChildObject",
  4668. engine->newFunction(findChildObject));
  4669. @ This function takes a script value representing some object which may have
  4670. been created from an XML description and a string containing the name of the
  4671. requested child element.
  4672. @<Functions for scripting@>=
  4673. QScriptValue findChildObject(QScriptContext *context, QScriptEngine *engine)
  4674. {
  4675. QObject *parent = argument<QObject *>(0, context);
  4676. QString name = argument<QString>(1, context);
  4677. QObject *object = parent->findChild<QObject *>(name);
  4678. QScriptValue value;
  4679. if(object)
  4680. {
  4681. value = engine->newQObject(object);
  4682. QString className = object->metaObject()->className();
  4683. @<Set object properties based on class name@>@;
  4684. }
  4685. return value;
  4686. }
  4687. @ Properties are added for a large number of class types.
  4688. @<Set object properties based on class name@>=
  4689. if(className == "TemperatureDisplay")
  4690. {
  4691. setTemperatureDisplayProperties(value, engine);
  4692. }
  4693. else if(className == "TimerDisplay")
  4694. {
  4695. setTimerDisplayProperties(value, engine);
  4696. }
  4697. else if(className == "QAction")
  4698. {
  4699. setQActionProperties(value, engine);
  4700. }
  4701. else if(className == "QBoxLayout")
  4702. {
  4703. setQBoxLayoutProperties(value, engine);
  4704. }
  4705. else if(className == "QDateEdit")
  4706. {
  4707. setQDateEditProperties(value, engine);
  4708. }
  4709. else if(className == "QFrame")
  4710. {
  4711. setQFrameProperties(value, engine);
  4712. }
  4713. else if(className == "QHBoxLayout")
  4714. {
  4715. setQBoxLayoutProperties(value, engine);
  4716. }
  4717. else if(className == "QLCDNumber")
  4718. {
  4719. setQLCDNumberProperties(value, engine);
  4720. }
  4721. else if(className == "QMenu")
  4722. {
  4723. setQMenuProperties(value, engine);
  4724. }
  4725. else if(className == "QMenuBar")
  4726. {
  4727. setQMenuBarProperties(value, engine);
  4728. }
  4729. else if(className == "QPushButton")
  4730. {
  4731. setQPushButtonProperties(value, engine);
  4732. }
  4733. else if(className == "QSplitter")
  4734. {
  4735. setQSplitterProperties(value, engine);
  4736. }
  4737. else if(className == "QTableView")
  4738. {
  4739. if(object->property("tabletype").isValid())
  4740. {
  4741. if(object->property("tabletype").toString() == "SaltTable")
  4742. {
  4743. setSaltTableProperties(value, engine);
  4744. }
  4745. }
  4746. }
  4747. else if(className == "QVBoxLayout")
  4748. {
  4749. setQBoxLayoutProperties(value, engine);
  4750. }
  4751. else if(className == "QWidget")
  4752. {
  4753. setQWidgetProperties(value, engine);
  4754. }
  4755. else if(className == "ScriptQMainWindow")
  4756. {
  4757. setQMainWindowProperties(value, engine);
  4758. }
  4759. else if(className == "SqlComboBox")
  4760. {
  4761. setSqlComboBoxProperties(value, engine);
  4762. }
  4763. else if(className == "SqlQueryView")
  4764. {
  4765. setSqlQueryViewProperties(value, engine);
  4766. }
  4767. else if(className == "ZoomLog")
  4768. {
  4769. setZoomLogProperties(value, engine);
  4770. }
  4771. else if(className == "QTextEdit")
  4772. {
  4773. setQTextEditProperties(value, engine);
  4774. }
  4775. else if(className == "QWebView")
  4776. {
  4777. setQWebViewProperties(value, engine);
  4778. }
  4779. @ In the list of classes, the SaltTable entry is for a class which does not
  4780. strictly exist on its own. It is, however, useful to provide some custom
  4781. properties when passing such an object to the host environment.
  4782. @<Function prototypes for scripting@>=
  4783. void setSaltTableProperties(QScriptValue value, QScriptEngine *engine);
  4784. QScriptValue SaltTable_bindableColumnArray(QScriptContext *context,
  4785. QScriptEngine *engine);
  4786. QScriptValue SaltTable_bindableQuotedColumnArray(QScriptContext *context,
  4787. QScriptEngine *engine);
  4788. QScriptValue SaltTable_columnSum(QScriptContext *context,
  4789. QScriptEngine *engine);
  4790. QScriptValue SaltTable_columnArray(QScriptContext *context,
  4791. QScriptEngine *engine);
  4792. QScriptValue SaltTable_data(QScriptContext *context, QScriptEngine *engine);
  4793. QScriptValue SaltTable_model(QScriptContext *context, QScriptEngine *engine);
  4794. QScriptValue SaltTable_quotedColumnArray(QScriptContext *context,
  4795. QScriptEngine *engine);
  4796. QScriptValue SaltTable_setData(QScriptContext *context, QScriptEngine *engine);
  4797. @ There are times when it is useful to obtain the sum of values in a column of
  4798. a SaltTable object. For example, when a column represents the weight of the
  4799. green coffee used in a batch, a sum of that column provides the total weight of
  4800. the batch which, when presented to the user, can be used to catch errors in
  4801. measuring batches or entering data.
  4802. @<Functions for scripting@>=
  4803. QScriptValue SaltTable_columnSum(QScriptContext *context, QScriptEngine *engine)
  4804. {
  4805. QTableView *self = getself<QTableView *>(context);
  4806. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  4807. QString datum;
  4808. double total = 0.0;
  4809. int column = argument<int>(0, context);
  4810. int role = argument<int>(1, context);
  4811. for(int i = 0; i < model->rowCount(); i++)
  4812. {
  4813. datum = model->data(model->index(i, column), role).toString();
  4814. if(!datum.isEmpty())
  4815. {
  4816. total += datum.toDouble();
  4817. }
  4818. }
  4819. return QScriptValue(engine, total);
  4820. }
  4821. @ Another common use of the SaltTable is producing the text for an array literal
  4822. to pass into a SQL query. The |SaltModel| used by this table makes this simple.
  4823. There are four functions for this functionality for different use cases.
  4824. @<Functions for scripting@>=
  4825. QScriptValue SaltTable_columnArray(QScriptContext *context,
  4826. QScriptEngine *engine)
  4827. {
  4828. QTableView *self = getself<QTableView *>(context);
  4829. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  4830. int column = argument<int>(0, context);
  4831. int role = argument<int>(1, context);
  4832. QString literal = model->arrayLiteral(column, role);
  4833. return QScriptValue(engine, literal);
  4834. }
  4835. QScriptValue SaltTable_quotedColumnArray(QScriptContext *context,
  4836. QScriptEngine *engine)
  4837. {
  4838. QTableView *self = getself<QTableView *>(context);
  4839. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  4840. int column = argument<int>(0, context);
  4841. int role = argument<int>(1, context);
  4842. QString literal = model->quotedArrayLiteral(column, role);
  4843. return QScriptValue(engine, literal);
  4844. }
  4845. QScriptValue SaltTable_bindableColumnArray(QScriptContext *context,
  4846. QScriptEngine *engine)
  4847. {
  4848. QTableView *self = getself<QTableView *>(context);
  4849. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  4850. int column = argument<int>(0, context);
  4851. int role = argument<int>(1, context);
  4852. QString literal = model->arrayLiteral(column, role);
  4853. literal.chop(1);
  4854. literal = literal.remove(0, 1);
  4855. return QScriptValue(engine, literal);
  4856. }
  4857. QScriptValue SaltTable_bindableQuotedColumnArray(QScriptContext *context,
  4858. QScriptEngine *engine)
  4859. {
  4860. QTableView *self = getself<QTableView *>(context);
  4861. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  4862. int column = argument<int>(0, context);
  4863. int role = argument<int>(1, context);
  4864. QString literal = model->quotedArrayLiteral(column, role);
  4865. literal.chop(1);
  4866. literal = literal.remove(0, 1);
  4867. return QScriptValue(engine, literal);
  4868. }
  4869. @ In order to obtain signals related to changes in the model, we need a way to
  4870. get to the model from the host environment.
  4871. @<Functions for scripting@>=
  4872. QScriptValue SaltTable_model(QScriptContext *context, QScriptEngine *engine)
  4873. {
  4874. QTableView *self = getself<QTableView *>(context);
  4875. QScriptValue value = engine->newQObject(self->model());
  4876. return value;
  4877. }
  4878. @ While this table was originally intended strictly for user input, there are a
  4879. few use cases in which it is useful to allow scripts to set the values in the
  4880. table. This can be done with |setData|. This method takes four arguments: the
  4881. row and column of the table being set, the value to set, and the role of the
  4882. data being set.
  4883. @<Functions for scripting@>=
  4884. QScriptValue SaltTable_setData(QScriptContext *context, QScriptEngine *)
  4885. {
  4886. QTableView *self = getself<QTableView *>(context);
  4887. int row = argument<int>(0, context);
  4888. int column = argument<int>(1, context);
  4889. QVariant value = argument<QVariant>(2, context);
  4890. int role = argument<int>(3, context);
  4891. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  4892. QModelIndex cell = model->index(row, column);
  4893. model->setData(cell, value, role);
  4894. self->update(cell);
  4895. return QScriptValue();
  4896. }
  4897. @ It is sometimes useful to obtain the data from a single cell of the table.
  4898. This can be done with the |data()| property.
  4899. @<Functions for scripting@>=
  4900. QScriptValue SaltTable_data(QScriptContext *context, QScriptEngine *engine)
  4901. {
  4902. QTableView *self = getself<QTableView *>(context);
  4903. int row = argument<int>(0, context);
  4904. int column = argument<int>(1, context);
  4905. int role = argument<int>(2, context);
  4906. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  4907. QModelIndex cell = model->index(row, column);
  4908. QVariant value = model->data(cell, role);
  4909. QScriptValue retval = engine->newVariant(value);
  4910. retval.setProperty("value", QScriptValue(value.toString()));
  4911. return retval;
  4912. }
  4913. @ These functions need to be added as properties of the table when it is passed
  4914. to the host environment.
  4915. @<Functions for scripting@>=
  4916. void setSaltTableProperties(QScriptValue value, QScriptEngine *engine)
  4917. {
  4918. setQWidgetProperties(value, engine);
  4919. value.setProperty("columnArray",
  4920. engine->newFunction(SaltTable_columnArray));
  4921. value.setProperty("quotedColumnArray",
  4922. engine->newFunction(SaltTable_quotedColumnArray));
  4923. value.setProperty("bindableColumnArray",
  4924. engine->newFunction(SaltTable_bindableColumnArray));
  4925. value.setProperty("bindableQuotedColumnArray",
  4926. engine->newFunction(SaltTable_bindableQuotedColumnArray));
  4927. value.setProperty("columnSum", engine->newFunction(SaltTable_columnSum));
  4928. value.setProperty("data", engine->newFunction(SaltTable_data));
  4929. value.setProperty("model", engine->newFunction(SaltTable_model));
  4930. value.setProperty("setData", engine->newFunction(SaltTable_setData));
  4931. }
  4932. @ The |SqlComboBox| is another class that is not constructed from scripts but is
  4933. useful to access from them. A property is added to obtain the current user data
  4934. from the widget.
  4935. @<Function prototypes for scripting@>=
  4936. void setSqlComboBoxProperties(QScriptValue value, QScriptEngine *engine);
  4937. void setQComboBoxProperties(QScriptValue value, QScriptEngine *engine);
  4938. QScriptValue QComboBox_currentData(QScriptContext *context,
  4939. QScriptEngine *engine);
  4940. QScriptValue QComboBox_addItem(QScriptContext *context, QScriptEngine *engine);
  4941. QScriptValue QComboBox_setModel(QScriptContext *context, QScriptEngine *engine);
  4942. QScriptValue QComboBox_findText(QScriptContext *context, QScriptEngine *engine);
  4943. @ These functions should seem familiar by now.
  4944. @<Functions for scripting@>=
  4945. void setSqlComboBoxProperties(QScriptValue value, QScriptEngine *engine)
  4946. {
  4947. setQComboBoxProperties(value, engine);
  4948. }
  4949. void setQComboBoxProperties(QScriptValue value, QScriptEngine *engine)
  4950. {
  4951. setQWidgetProperties(value, engine);
  4952. value.setProperty("currentData",
  4953. engine->newFunction(QComboBox_currentData));
  4954. value.setProperty("addItem", engine->newFunction(QComboBox_addItem));
  4955. value.setProperty("setModel", engine->newFunction(QComboBox_setModel));
  4956. value.setProperty("findText", engine->newFunction(QComboBox_findText));
  4957. }
  4958. QScriptValue QComboBox_currentData(QScriptContext *context,
  4959. QScriptEngine *engine)
  4960. {
  4961. QComboBox *self = getself<QComboBox *>(context);
  4962. return QScriptValue(engine,
  4963. self->itemData(self->currentIndex()).toString());
  4964. }
  4965. QScriptValue QComboBox_addItem(QScriptContext *context, QScriptEngine *)
  4966. {
  4967. QComboBox *self = getself<QComboBox *>(context);
  4968. self->addItem(argument<QString>(0, context));
  4969. return QScriptValue();
  4970. }
  4971. QScriptValue QComboBox_setModel(QScriptContext *context, QScriptEngine *)
  4972. {
  4973. QComboBox *self = getself<QComboBox *>(context);
  4974. self->setModel(argument<QAbstractItemModel *>(0, context));
  4975. return QScriptValue();
  4976. }
  4977. QScriptValue QComboBox_findText(QScriptContext *context, QScriptEngine *engine)
  4978. {
  4979. QComboBox *self = getself<QComboBox *>(context);
  4980. return QScriptValue(engine, self->findText(argument<QString>(0, context)));
  4981. }
  4982. @** A representation of temperature measurements.
  4983. \noindent Most of the information in a roast log will be temperature
  4984. measurements. These measurements are made of two components: the measured
  4985. temperature and the time at which that measurement was taken.
  4986. Measurement times are represented as instances of |QTime|.
  4987. The declaration of |Measurement| is reasonably straightforward. Measurements
  4988. will often be passed around to a number of different objects through the signals
  4989. and slots mechanism of Qt. The simplest way to make this work is to provide a
  4990. copy constructor and an assignment operator.
  4991. Starting with version 1.1.2 the |Measurement| class contains an indication of
  4992. the measurement unit and methods for converting a measurement from one unit to
  4993. another. The units are represented by the same constants as the |DAQ| class.
  4994. This can almost certainly be handled better.
  4995. @<Class declarations@>=
  4996. class Measurement@/
  4997. {
  4998. public:@/
  4999. enum TemperatureUnits
  5000. {
  5001. Fahrenheit = 10144,
  5002. Celsius = 10143,
  5003. Kelvin = 10325,
  5004. Rankine = 10145
  5005. };
  5006. private:@/
  5007. double theTemperature;
  5008. QTime theTime;
  5009. TemperatureUnits unit;
  5010. public:@;
  5011. Measurement(double temperature = 0, QTime time = QTime(),@|
  5012. TemperatureUnits sc = Fahrenheit);
  5013. Measurement(double temperature);
  5014. Measurement(const Measurement &x);
  5015. Measurement& operator=(Measurement &x);
  5016. ~Measurement();
  5017. double temperature() const;
  5018. QTime time() const;
  5019. void setTemperature(double temperature);
  5020. void setTime(QTime time);
  5021. void setUnit(TemperatureUnits scale);
  5022. TemperatureUnits scale();
  5023. Measurement toFahrenheit();
  5024. Measurement toCelsius();
  5025. Measurement toKelvin();
  5026. Measurement toRankine();
  5027. };
  5028. @ There are two constructors that can create |Measurement| objects. The
  5029. constructor that takes both a temperature and a time is declared as a default
  5030. constructor because one is needed to pass objects through |QMetaType|. The
  5031. constructor that only takes a temperature uses the measured temperature and the
  5032. current time.
  5033. @<Measurement implementation@>=
  5034. Measurement::Measurement(double temperature, QTime time,
  5035. TemperatureUnits sc) :@;
  5036. @t\kern2em@>theTemperature(temperature), theTime(time), unit(sc)@;
  5037. {
  5038. /* Nothing has to be done here. */
  5039. }@;
  5040. Measurement::Measurement(double temperature) :@;
  5041. @t\kern2em@>theTemperature(temperature), theTime(QTime::currentTime()),
  5042. unit(Fahrenheit)@;
  5043. {
  5044. /* Nothing has to be done here. */
  5045. }@;
  5046. @ Qt uses |QMetaType| in queued signals and slots connections such as those
  5047. between objects in different execution threads. To pass |Measurement| objects
  5048. through this mechanism we must register it with that class. This only needs to
  5049. be done once and can be done in the |main()| function during program
  5050. initialization.
  5051. @<Register meta-types@>=
  5052. qRegisterMetaType<Measurement>("Measurement");@/
  5053. @ To successfully register a class with |QMetaType| it must have a public
  5054. default constructor (already defined above), a public copy constructor, and a
  5055. public destructor.
  5056. @<Measurement implementation@>=
  5057. Measurement::Measurement(const Measurement &x) :@;
  5058. @t\kern2em@>theTemperature(x.temperature()), theTime(x.time()),
  5059. unit(x.unit)
  5060. {
  5061. /* Nothing has to be done here. */
  5062. }@;
  5063. Measurement::~Measurement()
  5064. {
  5065. /* Nothing has to be done here. */
  5066. }
  5067. @ Once the assignment operator is implemented it is possible to get measurements
  5068. to all of the objects that need them.
  5069. @<Measurement implementation@>=
  5070. Measurement&@,@, Measurement::operator=(Measurement &x)
  5071. {
  5072. theTemperature = x.temperature();
  5073. theTime = x.time();
  5074. unit = x.unit;
  5075. return *this;
  5076. }
  5077. @ Four member functions are used to get and set the time and temperature data of
  5078. a measurement. A measurement might need to be modified to convert from one
  5079. temperature unit to another or to convert a measurement time from system time to
  5080. a time relative to the start of a batch.
  5081. @<Measurement implementation@>=
  5082. double Measurement::temperature() const
  5083. {
  5084. return theTemperature;
  5085. }
  5086. QTime Measurement::time() const
  5087. {
  5088. return theTime;
  5089. }
  5090. void Measurement::setTemperature(double temperature)
  5091. {
  5092. theTemperature = temperature;
  5093. }
  5094. void Measurement::setTime(QTime time)
  5095. {
  5096. theTime = time;
  5097. }
  5098. @ This method changes the scale of the measurement. Note that this does not
  5099. alter the number holding the measurement. To convert a measurement from one
  5100. unit to another, use the appropriate |to[Fahrenheit||Celsius||Kelvin||Rankine]|
  5101. method.
  5102. @<Measurement implementation@>=
  5103. void Measurement::setUnit(TemperatureUnits scale)
  5104. {
  5105. unit = scale;
  5106. }
  5107. Measurement::TemperatureUnits Measurement::scale()
  5108. {
  5109. return unit;
  5110. }
  5111. @ Four methods create a new |Measurement| from the object the method is called
  5112. on representing the same measurement expressed in different units. The
  5113. conversion formul\ae{} come from Wikipedia.\nfnote{%
  5114. \pdfURL{Temperature Conversion}{%
  5115. http://en.wikipedia.org/%
  5116. w/index.php?title=Temperature_conversion&oldid=226047163}}
  5117. The |toFahrenheit()| method converts a measurement to Fahrenheit.
  5118. @<Measurement implementation@>=
  5119. Measurement Measurement::toFahrenheit()
  5120. {
  5121. switch(unit)
  5122. {
  5123. case Celsius:
  5124. return Measurement(this->temperature() * 9 / 5 + 32, this->time(),
  5125. Fahrenheit);
  5126. break;
  5127. case Kelvin:
  5128. return Measurement(this->temperature() * 5 / 9 - 459.67,
  5129. this->time(), Fahrenheit);
  5130. break;
  5131. case Rankine:
  5132. return Measurement(this->temperature() - 459.67, this->time(),
  5133. Fahrenheit);
  5134. break;
  5135. default:
  5136. return Measurement(this->temperature(), this->time(), Fahrenheit);
  5137. break;
  5138. }
  5139. }
  5140. @ Similarly, the following converts to Celsius.
  5141. @<Measurement implementation@>=
  5142. Measurement Measurement::toCelsius()
  5143. {
  5144. switch(unit)
  5145. {
  5146. case Fahrenheit:
  5147. return Measurement((this->temperature() - 32) * 5 / 9, this->time(),
  5148. Celsius);
  5149. break;
  5150. case Kelvin:
  5151. return Measurement(this->temperature() - 273.15, this->time(),
  5152. Celsius);
  5153. break;
  5154. case Rankine:
  5155. return Measurement((this->temperature() - 491.67) * 5 / 9,
  5156. this->time(), Celsius);
  5157. break;
  5158. default:
  5159. return Measurement(this->temperature(), this->time(), Celsius);
  5160. break;
  5161. }
  5162. }
  5163. @ For those who prefer absolute scales, a method is provided to convert to
  5164. Kelvin.
  5165. @<Measurement implementation@>=
  5166. Measurement Measurement::toKelvin()
  5167. {
  5168. switch(unit)
  5169. {
  5170. case Fahrenheit:
  5171. return Measurement((this->temperature() + 459.67) * 5 / 9,
  5172. this->time(), Kelvin);
  5173. break;
  5174. case Celsius:
  5175. return Measurement(this->temperature() + 273.15, this->time(),
  5176. Kelvin);
  5177. break;
  5178. case Rankine:
  5179. return Measurement(this->temperature() * 5 / 9, this->time(),
  5180. Kelvin);
  5181. break;
  5182. default:
  5183. return Measurement(this->temperature(), this->time(), Kelvin);
  5184. break;
  5185. }
  5186. }
  5187. @ Finally, conversion to Rankine is also allowed.
  5188. @<Measurement implementation@>=
  5189. Measurement Measurement::toRankine()
  5190. {
  5191. switch(unit)
  5192. {
  5193. case Fahrenheit:
  5194. return Measurement(this->temperature() + 459.67, this->time(),
  5195. Rankine);
  5196. break;
  5197. case Celsius:
  5198. return Measurement((this->temperature() + 273.15) * 9 / 5,
  5199. this->time(), Rankine);
  5200. break;
  5201. case Kelvin:
  5202. return Measurement(this->temperature() * 9 / 5, this->time(),
  5203. Rankine);
  5204. break;
  5205. default:
  5206. return Measurement(this->temperature(), this->time(), Rankine);
  5207. break;
  5208. }
  5209. }
  5210. @** The Main Measurement Pipeline.
  5211. \noindent Measurements are sent through \pn{} in a way similar to liquid moving
  5212. through a series of connected pipes. \pn{} is not something that you just dump
  5213. measurements on. It's not a big truck\nfnote{Senator Ted Stevens (R-Alaska) on
  5214. network neutrality, June 28, 2006\par
  5215. \hbox{\indent\pdfURL{http://media.publicknowledge.org/stevens-on-nn.mp3}%
  5216. {http://media.publicknowledge.org/stevens-on-nn.mp3}}}. In most cases the
  5217. connections between classes (represented by arrows in Figure \secno) are made
  5218. with Qt's signals and slots mechanism\nfnote{Qt 4.4.3: Signals and Slots\par
  5219. \hbox{\indent\pdfURL{http://doc.trolltech.com/4.4/signalsandslots.html}%
  5220. {http://doc.trolltech.com/4.4/signalsandslots.html}}}, but
  5221. these
  5222. connections can
  5223. also be made through direct function calls as is the case with the connection
  5224. between |ZoomLog| and |MeasurementModel|.
  5225. \medskip
  5226. \includegraphics{pipes}
  5227. \smallskip
  5228. \centerline{Figure \secno: Example Flow of Measurement objects in \pn}
  5229. \medskip
  5230. Please note that Figure \secno~is representative of a typical configuration. Now
  5231. that the flow of measurements through \pn{} is determined by a script specified
  5232. by the user, whatever pipeline is needed can be specified at run time.
  5233. @* The DAQ class.
  5234. \noindent The |DAQ| class represents a piece of hardware that allows the
  5235. computer to read measurements from one or more thermocouples. Presently this
  5236. class is only handles continuous sampling on devices from National Instruments.
  5237. It should be simple to modify this class to handle similar devices from other
  5238. vendors.
  5239. Each device is represented by a single instance of this class. Multiple channels
  5240. can be used on a device if the device supports it.
  5241. Two enumerations are declared in this class to be used as arguments to
  5242. |newChannel()|. The first is used to set the measurement unit for the channel.
  5243. As the measurements themselves do not carry this information, it is important to
  5244. keep track of this information. The values come from {\tt nidaqmxbase.h} and can
  5245. be used to select among Fahrenheit, Celsius, Kelvin, and Rankine. The
  5246. second enumeration, |ThermocoupleType|, should be used to specify the type of
  5247. thermocouple connected to the device. If this does not match reality, the
  5248. measurements will not be correct. The meanings of the values should be obvious
  5249. from the names.
  5250. \danger When this class was originally written the method of thread handling
  5251. used was considered appropriate. New functionality in |QThread| has made this
  5252. no longer the case. This class is currently planned for depreciation once a
  5253. replacement class hierarchy more suited to multiple hardware types is available
  5254. however if this is not ready soon it may be beneficial to rewrite this class to
  5255. conform to current best practices.\endanger
  5256. @<Class declarations@>=
  5257. class Channel;
  5258. class DAQImplementation;@/
  5259. class DAQ : public QObject@;@/
  5260. {@t\1@>@/
  5261. Q_OBJECT@/
  5262. Q_ENUMS(TemperatureUnits)@/
  5263. Q_ENUMS(ThermocoupleType)@;@/
  5264. DAQImplementation *imp;@/
  5265. @t\4@>private slots@t\kern-3pt@>:@/
  5266. void threadFinished();
  5267. public:@;
  5268. DAQ(QString device, const QString &driver = QString("nidaqmxbase"));
  5269. ~DAQ();@/
  5270. Channel* newChannel(int units, int thermocouple);@/
  5271. @[Q_INVOKABLE@,@, void@]@, setClockRate(double Hz);@t\2\2@>@/
  5272. @[Q_INVOKABLE@,@, void@]@, start();@t\2\2@>@/
  5273. @[Q_INVOKABLE@]@, void stop();
  5274. enum TemperatureUnits@/
  5275. {
  5276. @!Fahrenheit = 10144,
  5277. @!Celsius = 10143,
  5278. @!Kelvin = 10325,
  5279. @!Rankine = 10145
  5280. };
  5281. enum ThermocoupleType@/
  5282. {
  5283. @!TypeJ = 10072,
  5284. @!TypeK = 10073,
  5285. @!TypeN = 10077,
  5286. @!TypeR = 10082,
  5287. @!TypeS = 10085,
  5288. @!TypeT = 10086,
  5289. @!TypeB = 10047,
  5290. @!TypeE = 10055
  5291. };@t\2@>@/
  5292. }@t\kern-3pt@>;
  5293. @ The |DAQ| class has as a private member an instance of a class called
  5294. |DAQImplementation|. The two classes together create and run a new thread of
  5295. execution. This thread spends most of its time blocking while waiting for a new
  5296. measurement to become available. When a new measurement is available, that
  5297. measurement is passed to the appropriate channel which in turn passes it to any
  5298. interested object.
  5299. @<Class declarations@>=
  5300. class DAQImplementation : public QThread@;@/
  5301. {@;
  5302. Q_OBJECT@;@/
  5303. public:@;
  5304. DAQImplementation(const QString &driverinfo);
  5305. ~DAQImplementation();
  5306. void run();
  5307. void measure();
  5308. @<Library function pointers@>@;
  5309. @<DAQImplementation member data@>@;
  5310. }@+@t\kern-3pt@>;
  5311. @ In order to solve some minor problems, NI-DAQmxBase is no longer linked at
  5312. compile time. Rather, this is now linked at runtime through a |QLibrary| object.
  5313. In order to use functions from this library, these functions must be stored in
  5314. function pointers. Fortunately, all of these functions can be expressed with the
  5315. same pointer type. Unfortunately, this way of doing things offers very little
  5316. debugging information in the event that something is not quite right.
  5317. @<Library function pointers@>=
  5318. typedef int (*daqfp)(...);
  5319. daqfp read;
  5320. daqfp errorInfo;
  5321. daqfp startTask;
  5322. daqfp createTask;
  5323. daqfp createChannel;
  5324. daqfp setClock;
  5325. daqfp stopTask;
  5326. daqfp clearTask;
  5327. daqfp resetDevice;
  5328. daqfp waitForMeasurement;
  5329. @ |DAQImplementation| also maintains information about the device and the
  5330. channels the measurements are sent to.
  5331. @<DAQImplementation member data@>=
  5332. bool useBase;
  5333. QString device;
  5334. QVector<Channel*> channelMap;
  5335. unsigned int handle;@/
  5336. int error;
  5337. int channels;
  5338. bool ready;
  5339. QLibrary driver;
  5340. QVector<Measurement::TemperatureUnits> unitMap;
  5341. @ Most of the interesting work associated with the |DAQ| class is handled in
  5342. the |measure()| method of |DAQImplementation|. This function will block until a
  5343. measurement is available. Once |buffer| is filled by |DAQmxBaseReadAnalogF64()|
  5344. that function returns and new |Measurement| objects are created based on the
  5345. information in the buffer. These measurements are sent to |Channel| objects
  5346. tracked by |channelMap|.
  5347. Up until version 1.0.7 there was a bug in this code that would prevent the code
  5348. from working when more than one channel is requested. This has been corrected.
  5349. With version 1.0.9, time measurement is moved out of the loop, reducing the
  5350. number of calls in cases of more than 1 measurement and ensuring that all
  5351. simultaneously obtained measurements have the same time stamp.
  5352. @<DAQ Implementation@>=
  5353. void DAQImplementation::measure()@t\2@>@/
  5354. @t\4@>{@/
  5355. int samplesRead = 0;
  5356. double buffer[channels];
  5357. error = read((unsigned int)(handle), (signed long)(1), (double)(10.0),
  5358. (unsigned long)(0), buffer, (unsigned long)(channels),
  5359. &samplesRead, (signed long)(0));
  5360. if(error)@/
  5361. @t\1@>{@/
  5362. ready = false;@t\2@>@/
  5363. }
  5364. else@/
  5365. {
  5366. if(samplesRead)@/
  5367. {
  5368. QTime time = QTime::currentTime();@/
  5369. for(int i = 0; i < samplesRead; i++)@/
  5370. {
  5371. for(int j = 0; j < channels; j++)@/
  5372. {
  5373. Measurement measure(buffer[@,j+(i*channels)], time,
  5374. unitMap[j]);
  5375. channelMap[@,j]->input(measure);
  5376. }
  5377. }
  5378. }
  5379. }
  5380. @t\4@>}
  5381. @ It was noted that |DAQmxBaseReadAnalogF64()| blocks until it is able to fill
  5382. the |buffer| passed to it. To prevent this behavior from having adverse effects
  5383. on the rest of the program, measure is called from a loop running in its own
  5384. thread of execution. When the thread is started, it begins its execution from
  5385. the |run()| method of |DAQImplementation| which overrides the |run()| method of
  5386. |QThread|. Here the priority of the thread is set in an attempt to cut down on
  5387. the variation in time between recorded measurements.
  5388. The while loop is controlled by |ready| which is set to |false| when there is an
  5389. error in collecting a measurement or when the user wants to exit the program. It
  5390. could also be set to |false| when the |DAQ| is reconfigured.
  5391. @<DAQ Implementation@>=
  5392. void DAQImplementation::run()
  5393. {
  5394. setPriority(QThread::TimeCriticalPriority);
  5395. while(ready)
  5396. {
  5397. measure();
  5398. }
  5399. }
  5400. @ When this loop exits, |DAQImplementation| emits a finished signal to indicate
  5401. that the thread is no longer running. This could be due to perfectly normal
  5402. conditions, but there could also be a problem that the user must be informed of.
  5403. That signal is connected to a function that checks for error conditions and
  5404. reports them if needed.
  5405. @<DAQ Implementation@>=
  5406. void DAQ::threadFinished()
  5407. {
  5408. if(imp->error)
  5409. {
  5410. @<Display DAQ Error@>@;
  5411. }
  5412. }
  5413. @ Errors are displayed with a |QMessageBox|. NIDAQmxBase provides the message
  5414. strings for these errors, but this should probably change as these error strings
  5415. are generally completely unrelated to what the problem really is. For example,
  5416. ``Error: -1'' usually means that the device is not plugged in.
  5417. ``Error: -200170'' usually means that \pn{} or another program using the device
  5418. did not exit cleanly. A table of replacement warning messages should be added to
  5419. this program.
  5420. \bigskip
  5421. \settabs 5 \columns
  5422. \+Error Code & NIDAQmxBase Text & & Likely Cause\cr
  5423. \+\hrulefill & \hrulefill & \hrulefill & \hrulefill & \hrulefill & \hrulefill\cr
  5424. \+ -1 & Not implemented for this device & & The device is not plugged in.\cr
  5425. \+ & type. & \cr
  5426. \+ -200170 & Physical channel specified & & The program did not exit cleanly\cr
  5427. \+ & does not exist on this device. & & or another program is using the\cr
  5428. \+ & Refer to the documentation for & & device.\cr
  5429. \+ & channels available on this device.\cr
  5430. \+ -1073807194 & {\it{(No text)}} & & The device has been unplugged.\cr
  5431. \medskip
  5432. \centerline{Table \secno: Error codes, text, and what they really mean.}
  5433. \bigskip
  5434. There are two calls to |DAQmxBaseGetExtendedErrorInfo()| to obtain the error
  5435. messages. The first is used just to obtain the length of the error string. That
  5436. length is then used to allocate space for the error message. The second call
  5437. fills that string. This isn't allowed by ISO \CPLUSPLUS/\nfnote{%
  5438. \CPLUSPLUS/Dynamic Arrays (Crowl and Austern, May 16, 2008)\par
  5439. \hbox{\indent\pdfURL{%
  5440. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2648.html}{%
  5441. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2648.html}}} but it
  5442. works with gcc. If this is a problem, the first call can be
  5443. removed and the buffer can be set large enough to fit the largest error message
  5444. that will be produced. Heap allocation could be used, but then we need to
  5445. remember to free the memory allocated to the string. Alternately, we can get rid
  5446. of \CEE/ style strings and write our own error messages. This would be the
  5447. preferred correction.
  5448. @<Display DAQ Error@>=
  5449. imp->ready = false;
  5450. QMessageBox warning;
  5451. warning.setStandardButtons(QMessageBox::Cancel);
  5452. warning.setIcon(QMessageBox::Warning);
  5453. warning.setText(QString(tr("Error: %1")).arg(imp->error));
  5454. unsigned long bytes = imp->errorInfo(NULL, 0);
  5455. char string[bytes];
  5456. imp->errorInfo(string, bytes);
  5457. warning.setInformativeText(QString(string));
  5458. warning.setWindowTitle(QString(PROGRAM_NAME));
  5459. warning.exec();
  5460. @ Starting the thread is almost as simple as ending it. The hardware is
  5461. instructed to begin taking measurements. If there is an error, this is handled.
  5462. Otherwise, the finished signal from |DAQImplementation| is connected to
  5463. |threadFinished()| and the new thread is started. The call to |imp->start()|
  5464. starts a new thread and passes control of that thread to |imp->run()|. The main
  5465. thread of execution returns without waiting for the new thread to do anything.
  5466. The call to |DAQmxBaseStartTask()| requires some time before the first
  5467. measurement is available. This is one of the reasons we start gathering
  5468. measurements before we really need them and continue to collect them until it is
  5469. time to exit the program.
  5470. @<DAQ Implementation@>=
  5471. void DAQ::start()
  5472. {
  5473. if(imp->ready)
  5474. {
  5475. imp->error = imp->startTask(imp->handle);
  5476. if(imp->error)
  5477. {
  5478. @<Display DAQ Error@>@;
  5479. }
  5480. else
  5481. {
  5482. connect(imp, SIGNAL(finished()), this, SLOT(threadFinished()));
  5483. imp->start();
  5484. }
  5485. }
  5486. }
  5487. void DAQ::stop()
  5488. {
  5489. if(imp->useBase)
  5490. {
  5491. imp->ready = false;
  5492. imp->wait(ULONG_MAX);
  5493. imp->stopTask(imp->handle);
  5494. }
  5495. else
  5496. {
  5497. imp->ready = false;
  5498. imp->error = imp->stopTask(imp->handle);
  5499. if(imp->error)
  5500. {
  5501. @<Display DAQ Error@>@;
  5502. }
  5503. imp->error = imp->clearTask(imp->handle);
  5504. if(imp->error)
  5505. {
  5506. @<Display DAQ Error@>@;
  5507. }
  5508. }
  5509. }
  5510. @ Setting up the DAQ begins by constructing a new |DAQ| object. The constructor
  5511. takes as its argument a string indicating the name of the device and will
  5512. typically be something like |"Dev1"|. This creates a new task which is required
  5513. for the setup that follows once a new |DAQ| is created.
  5514. @<DAQ Implementation@>=
  5515. DAQ::DAQ(QString device, const QString &driver) : imp(new DAQImplementation(driver))@/
  5516. @t\4\4@>{@/
  5517. imp->device = device;
  5518. imp->error = imp->createTask(device.toAscii().data(), &(imp->handle));
  5519. if(imp->error)@/
  5520. {
  5521. @<Display DAQ Error@>@;
  5522. }
  5523. else@/
  5524. @t\1@>{@/
  5525. imp->ready = true;@t\2@>@/
  5526. }@/
  5527. @t\4\4@>}
  5528. @ Once the |DAQ| is created, one or more channels can be added to that |DAQ|.
  5529. All |Channel| objects are created by the |DAQ| class and are managed by the
  5530. |DAQ| class. When a new channel is created, a pointer is passed back allowing
  5531. other classes to connect to the channel. Measurements cannot be read from the
  5532. |DAQ| directly. They must at some point pass through a channel.
  5533. @<DAQ Implementation@>=
  5534. Channel* DAQ::newChannel(int units, int thermocouple)
  5535. {
  5536. Channel *retval = new Channel();
  5537. imp->channelMap[imp->channels] = retval;
  5538. imp->unitMap[imp->channels] = (Measurement::TemperatureUnits)units;
  5539. imp->channels++;
  5540. if(imp->ready)
  5541. {
  5542. if(imp->useBase)
  5543. {
  5544. imp->error = imp->createChannel(imp->handle,
  5545. QString("%1/ai%2").arg(imp->device).
  5546. arg(imp->channels - 1).
  5547. toAscii().data(),
  5548. "", (double)(-1.0), (double)(100.0),
  5549. (signed long)(units),
  5550. (signed long)(thermocouple),
  5551. (signed long)(10200), (double)(0),
  5552. "");
  5553. }
  5554. else
  5555. {
  5556. imp->error = imp->createChannel(imp->handle,
  5557. QString("%1/ai%2").arg(imp->device).
  5558. arg(imp->channels - 1).
  5559. toAscii().data(),
  5560. "", (double)(50.0), (double)(500.0),
  5561. (signed long)(units),
  5562. (signed long)(thermocouple),
  5563. (signed long)(10200), (double)(0),
  5564. "");
  5565. }
  5566. if(imp->error)
  5567. {
  5568. @<Display DAQ Error@>@;
  5569. }
  5570. }
  5571. return retval;
  5572. }
  5573. @ Once the channels are created, it is necessary to set the clock rate of the
  5574. DAQ. The clock rate chosen must be supported by the hardware. The clock rates
  5575. supported by the hardware may be altered by the number of channels in use.
  5576. The amount of time between measurements may vary slightly. A test configuration
  5577. at Wilson's Coffee \char'046~Tea used a 4Hz clock rate and provides measurements
  5578. every 251$\pm$1ms with 80\% of measurements spaced 251ms apart.
  5579. @<DAQ Implementation@>=
  5580. void DAQ::setClockRate(double Hz)
  5581. {
  5582. if(imp->ready)
  5583. {
  5584. imp->error = imp->setClock(imp->handle, "OnboardClock", Hz,
  5585. (signed long)(10280), (signed long)(10123),
  5586. (unsigned long long)(1));
  5587. if(imp->error)
  5588. {
  5589. @<Display DAQ Error@>@;
  5590. }
  5591. }
  5592. }
  5593. @ Before the program exits, the |DAQ| should be deleted. The destructor
  5594. instructs the measurement thread to stop, waits for it to finish, and resets the
  5595. device. If this is not done, an error would be issued the next time a program
  5596. attempted to use the device.
  5597. @<DAQ Implementation@>=
  5598. DAQ::~DAQ()@/
  5599. @t\4\4@>{@/
  5600. if(imp->useBase)
  5601. {
  5602. imp->resetDevice(imp->device.toAscii().data());
  5603. imp->clearTask(imp->handle);
  5604. }
  5605. else
  5606. {
  5607. if(imp->ready)
  5608. {
  5609. imp->ready = false;
  5610. imp->wait(ULONG_MAX);
  5611. imp->stopTask(imp->handle);
  5612. imp->resetDevice(imp->device.toAscii().data());
  5613. imp->clearTask(imp->handle);
  5614. }
  5615. }
  5616. delete imp;
  5617. @t\4\4@>}
  5618. @ This just leaves the constructor and destructor for |DAQImplementation|. The
  5619. way the program is currently written, the number of channels available on the
  5620. |DAQ| is limited to 4. If a known larger number is required, the value here can
  5621. simply be set larger, however the best long term solution would be to modify
  5622. |newChannel()| to resize |channelMap| as more channels are added.
  5623. The constructor handles loading NI-DAQmxBase and preparing function pointers for
  5624. the symbols used in \pn{}.
  5625. @<DAQ Implementation@>=
  5626. DAQImplementation::DAQImplementation(const QString &driverinfo)
  5627. : QThread(NULL), channelMap(4), handle(0), error(0), channels(0), ready(false),
  5628. unitMap(4)@/
  5629. {
  5630. if(driverinfo == "nidaqmxbase")
  5631. {
  5632. useBase = true;
  5633. }
  5634. else
  5635. {
  5636. useBase = false;
  5637. }
  5638. if(useBase)
  5639. {
  5640. driver.setFileName("nidaqmxbase.framework/nidaqmxbase");
  5641. if(!driver.load())
  5642. {
  5643. driver.setFileName("nidaqmxbase");
  5644. if(!driver.load())
  5645. {
  5646. QMessageBox::critical(NULL, tr("Typica: Driver not found"),
  5647. tr("Failed to find nidaqmxbase. Please install it."));
  5648. QApplication::quit();
  5649. }
  5650. }
  5651. }
  5652. else
  5653. {
  5654. driver.setFileName("nicaiu");
  5655. if(!driver.load())
  5656. {
  5657. QMessageBox::critical(NULL, tr("Typica: Driver not found"),
  5658. tr("Failed to find nidaqmx. Please install it."));
  5659. QApplication::quit();
  5660. }
  5661. }
  5662. if(useBase)
  5663. {
  5664. if((createTask = (daqfp) driver.resolve("DAQmxBaseCreateTask")) == 0 || @|
  5665. (startTask = (daqfp) driver.resolve("DAQmxBaseStartTask")) == 0 || @|
  5666. (stopTask = (daqfp) driver.resolve("DAQmxBaseStopTask")) == 0 || @|
  5667. (clearTask = (daqfp) driver.resolve("DAQmxBaseClearTask")) == 0 || @|
  5668. (createChannel = (daqfp) driver.resolve("DAQmxBaseCreateAIThrmcplChan"))
  5669. == 0 || @|
  5670. (setClock = (daqfp) driver.resolve("DAQmxBaseCfgSampClkTiming")) ==
  5671. 0 || @|
  5672. (read = (daqfp) driver.resolve("DAQmxBaseReadAnalogF64")) == 0 || @|
  5673. (errorInfo = (daqfp) driver.resolve("DAQmxBaseGetExtendedErrorInfo")) ==
  5674. 0 || @|
  5675. (resetDevice = (daqfp) driver.resolve("DAQmxBaseResetDevice")) == 0)@/
  5676. {
  5677. waitForMeasurement = NULL;
  5678. QMessageBox::critical(NULL, tr("Typica: Link error"),
  5679. tr("Failed to link a required symbol in NI-DAQmxBase."));
  5680. QApplication::quit();
  5681. }
  5682. }
  5683. else
  5684. {
  5685. if((createTask = (daqfp)driver.resolve("DAQmxCreateTask")) == 0 || @|
  5686. (startTask = (daqfp)driver.resolve("DAQmxStartTask")) == 0 || @|
  5687. (stopTask = (daqfp)driver.resolve("DAQmxStopTask")) == 0 || @|
  5688. (clearTask = (daqfp)driver.resolve("DAQmxClearTask")) == 0 || @|
  5689. (createChannel = (daqfp)driver.resolve("DAQmxCreateAIThrmcplChan"))
  5690. == 0 || @|
  5691. (setClock = (daqfp)driver.resolve("DAQmxCfgSampClkTiming")) == 0 || @|
  5692. (read = (daqfp)driver.resolve("DAQmxReadAnalogF64")) == 0 || @|
  5693. (errorInfo = (daqfp)driver.resolve("DAQmxGetExtendedErrorInfo")) ==
  5694. 0 || @|
  5695. (resetDevice = (daqfp)driver.resolve("DAQmxResetDevice")) == 0 ||
  5696. (waitForMeasurement = (daqfp)driver.resolve("DAQmxWaitUntilTaskDone")) == 0)
  5697. {
  5698. QMessageBox::critical(NULL, tr("Typica: Link error"),
  5699. tr("Failed to link a required symbol in NI-DAQmx."));
  5700. QApplication::quit();
  5701. }
  5702. }
  5703. }
  5704. DAQImplementation::~DAQImplementation()
  5705. {
  5706. driver.unload();
  5707. }
  5708. @ When exposing the |DAQ| class to the scripting engine, we need to provide a
  5709. constructor that can be called from a script and we need a way to call
  5710. |DAQ::newChannel()|. Other methods that are useful when called from a script are
  5711. made available automatically with the |Q_INVOKABLE| macro, however this does not
  5712. work for methods such as |newChannel()| which return a pointer to a |Channel|
  5713. object.
  5714. @<Function prototypes for scripting@>=
  5715. QScriptValue constructDAQ(QScriptContext *context, QScriptEngine *engine);
  5716. QScriptValue DAQ_newChannel(QScriptContext *context, QScriptEngine *engine);
  5717. void setDAQProperties(QScriptValue value, QScriptEngine *engine);
  5718. @ First we make these functions known to the scripting engine.
  5719. @<Set up the scripting engine@>=
  5720. constructor = engine->newFunction(constructDAQ);
  5721. value = engine->newQMetaObject(&DAQ::staticMetaObject, constructor);
  5722. engine->globalObject().setProperty("DAQ", value);
  5723. @ When creating a new |DAQ|, we make sure that it is owned by the script engine.
  5724. This is necessary to ensure that the destructor is called before \pn{} exits.
  5725. Just as the constructor requires an argument that specifies the device name, the
  5726. constructor available from a script also requires this argument.
  5727. @<Functions for scripting@>=
  5728. QScriptValue constructDAQ(QScriptContext *context, QScriptEngine *engine)
  5729. {
  5730. QScriptValue object;
  5731. if(context->argumentCount() == 1)
  5732. {
  5733. object = engine->newQObject(new DAQ(argument<QString>(0, context)),
  5734. QScriptEngine::ScriptOwnership);
  5735. setDAQProperties(object, engine);
  5736. }
  5737. else if(context->argumentCount() == 2)
  5738. {
  5739. object = engine->newQObject(new DAQ(argument<QString>(0, context),
  5740. argument<QString>(1, context)),
  5741. QScriptEngine::ScriptOwnership);
  5742. setDAQProperties(object, engine);
  5743. }
  5744. else
  5745. {
  5746. context->throwError("Incorrect number of arguments passed to DAQ"@|
  5747. "constructor. The DAQ constructor takes one"@|
  5748. "string as an argument specifying a device name."@|
  5749. "Example: Dev1");
  5750. }
  5751. return object;
  5752. }
  5753. @ As |DAQ| inherits |QObject|, we add the |newChannel()| property after adding
  5754. any |QObject| properties.
  5755. @<Functions for scripting@>=
  5756. void setDAQProperties(QScriptValue value, QScriptEngine *engine)
  5757. {
  5758. setQObjectProperties(value, engine);
  5759. value.setProperty("newChannel", engine->newFunction(DAQ_newChannel));
  5760. }
  5761. @ The |newChannel()| method method also requires that two arguments are provided
  5762. by the script.
  5763. @<Functions for scripting@>=
  5764. QScriptValue DAQ_newChannel(QScriptContext *context, QScriptEngine *engine)
  5765. {
  5766. DAQ *self = getself<@[DAQ *@]>(context);
  5767. QScriptValue object;
  5768. if(self)
  5769. {
  5770. object =
  5771. engine->newQObject(self->newChannel(argument<int>(0, context),@|
  5772. argument<int>(1, context)));
  5773. setChannelProperties(object, engine);
  5774. }
  5775. return object;
  5776. }
  5777. @ Sometimes it can be useful to test other parts of the program (for example,
  5778. when developing new scripts) when the DAQ hardware is not available. In these
  5779. cases, it is possible to temporarily use the |FakeDAQ| class. This class mimics
  5780. the |DAQ| class, but just makes up the measurements sent to the rest of the
  5781. program.
  5782. @<Class declarations@>=
  5783. class FakeDAQImplementation : public QThread@/
  5784. {@/
  5785. Q_OBJECT@;
  5786. public:@/
  5787. FakeDAQImplementation();
  5788. ~FakeDAQImplementation();
  5789. void run();
  5790. void measure();
  5791. QVector<Channel *> channelMap;
  5792. int channels;
  5793. bool ready;
  5794. double clockRate;
  5795. };@/
  5796. class FakeDAQ : public QObject@/
  5797. {@/
  5798. Q_OBJECT@;
  5799. FakeDAQImplementation *imp;
  5800. public:@/
  5801. FakeDAQ(QString device);
  5802. ~FakeDAQ();
  5803. Channel *newChannel(int units, int thermocouple);@/
  5804. @[Q_INVOKABLE@,@, void@]@, setClockRate(double Hz);@t\2\2@>@/
  5805. @[Q_INVOKABLE@,@, void@]@, start();@t\2\2@>@/
  5806. };
  5807. @ Just as in the |DAQ| class, most of the interesting stuff happens in
  5808. |measure()|. For each invokation of the method, we sleep for some amount of time
  5809. based on the clock rate then create a |Measurement| object at random for each
  5810. |Channel| that has been created.
  5811. @<FakeDAQ Implementation@>=
  5812. void FakeDAQImplementation::measure()
  5813. {
  5814. msleep((int)(1000/clockRate));
  5815. QTime time = QTime::currentTime();
  5816. for(int i = 0; i < channels; i++)
  5817. {
  5818. Measurement measure(qrand() % 500, time);
  5819. channelMap[i]->input(measure);
  5820. }
  5821. }
  5822. @ To call |measure|, we need to flesh out the rest of |FakeDAQImplementation|.
  5823. @<FakeDAQ Implementation@>=
  5824. void FakeDAQImplementation::run()
  5825. {
  5826. setPriority(QThread::TimeCriticalPriority);
  5827. while(ready)
  5828. {
  5829. measure();
  5830. }
  5831. }
  5832. FakeDAQImplementation::FakeDAQImplementation() : QThread(NULL), channelMap(4),
  5833. channels(0), ready(false), clockRate(1)@/
  5834. {
  5835. /* Nothing has to be done here. */
  5836. }
  5837. FakeDAQImplementation::~FakeDAQImplementation()
  5838. {
  5839. /* Nothing has to be done here. */
  5840. }
  5841. @ Next we need an implementation for the |FakeDAQ| class. This is simplified by
  5842. the fact that we are just using a random number generator to generate
  5843. measurements rather than special hardware for obtaining measurements.
  5844. @<FakeDAQ Implementation@>=
  5845. void FakeDAQ::start()
  5846. {
  5847. if(imp->ready)
  5848. {
  5849. imp->start();
  5850. }
  5851. }@#
  5852. FakeDAQ::FakeDAQ(QString) : imp(new FakeDAQImplementation())@t\2\2@>@/
  5853. {@t\1@>@/
  5854. imp->ready = true;@t\2@>@/
  5855. }@#
  5856. Channel* FakeDAQ::newChannel(int, int)
  5857. {
  5858. Channel *retval;
  5859. if(imp->ready)
  5860. {
  5861. retval = new Channel();
  5862. imp->channelMap[imp->channels] = retval;
  5863. imp->channels++;
  5864. }
  5865. else
  5866. {
  5867. return NULL;
  5868. }
  5869. return retval;
  5870. }
  5871. void FakeDAQ::setClockRate(double Hz)
  5872. {
  5873. if(imp->ready)
  5874. {
  5875. imp->clockRate = Hz;
  5876. }
  5877. }@#
  5878. FakeDAQ::~FakeDAQ()@t\2\2@>@/
  5879. {@t\1@>@/
  5880. imp->ready = false;
  5881. imp->wait(ULONG_MAX);
  5882. delete imp;@t\2@>@/
  5883. }
  5884. @ As the entire purpose of the |FakeDAQ| class is for testing purposes from
  5885. within the scripting engine, we need to make it available to the scripting
  5886. engine. This is done in a manner very similar to how the |DAQ| class is handled.
  5887. @<Function prototypes for scripting@>=
  5888. QScriptValue constructFakeDAQ(QScriptContext *context, QScriptEngine *engine);
  5889. QScriptValue FakeDAQ_newChannel(QScriptContext *context, QScriptEngine *engine);
  5890. void setFakeDAQProperties(QScriptValue value, QScriptEngine *engine);
  5891. @ The scripting engine is informed of the constructor.
  5892. @<Set up the scripting engine@>=
  5893. constructor = engine->newFunction(constructFakeDAQ);
  5894. value = engine->newQMetaObject(&FakeDAQ::staticMetaObject, constructor);
  5895. engine->globalObject().setProperty("FakeDAQ", value);
  5896. @ The constructor sets a property to allow calling |newChannel()| on a |FakeDAQ|
  5897. created from a script.
  5898. @<Functions for scripting@>=
  5899. QScriptValue constructFakeDAQ(QScriptContext *context,
  5900. QScriptEngine *engine)
  5901. {
  5902. QScriptValue object;
  5903. if(context->argumentCount() == 1)
  5904. {
  5905. object =
  5906. engine->newQObject(new FakeDAQ(argument<QString>(0, context)),
  5907. QScriptEngine::ScriptOwnership);
  5908. setFakeDAQProperties(object, engine);
  5909. }
  5910. else
  5911. {
  5912. context->throwError("Incorrect number of arguments passed to DAQ"@|
  5913. "constructor. The DAQ constructor takes one"@|
  5914. "string as an argument specifying a device name."@|
  5915. "Example: Dev1");
  5916. }
  5917. return object;
  5918. }
  5919. void setFakeDAQProperties(QScriptValue value, QScriptEngine *engine)
  5920. {
  5921. setQObjectProperties(value, engine);
  5922. value.setProperty("newChannel", engine->newFunction(FakeDAQ_newChannel));
  5923. }
  5924. QScriptValue FakeDAQ_newChannel(QScriptContext *context, QScriptEngine *engine)
  5925. {
  5926. FakeDAQ *self = getself<@[FakeDAQ *@]>(context);
  5927. QScriptValue object;
  5928. if(self)
  5929. {
  5930. object =
  5931. engine->newQObject(self->newChannel(argument<int>(0, context),@|
  5932. argument<int>(1, context)));
  5933. setChannelProperties(object, engine);
  5934. }
  5935. return object;
  5936. }
  5937. @* The Channel class.
  5938. \noindent |Channel| is a simple class. It is a subclass of |QObject| so it can
  5939. use Qt's signals and slots mechanism. Any object that is interested in
  5940. measurements from a channel can connect to the |newData| signal the channel
  5941. emits. Any number of objects can make this connection and each will receive a
  5942. copy of the measurement.
  5943. |Channel| objects should only be created by the |DAQ| class.
  5944. @<Class declarations@>=
  5945. class Channel : public QObject@;@/
  5946. {@t\1@>@/
  5947. Q_OBJECT@/
  5948. public:@;
  5949. Channel();
  5950. ~Channel();@/
  5951. @t\4@>public slots@t\kern-3pt@>:@;
  5952. void input(Measurement measurement);@/
  5953. signals:@;
  5954. void newData(Measurement);@t\2@>@/
  5955. };
  5956. @ The implementation of this class is trivial.
  5957. @<Channel Implementation@>=
  5958. Channel::Channel() : QObject(NULL)@/
  5959. {
  5960. /* Nothing has to be done here. */
  5961. }
  5962. Channel::~Channel()
  5963. {
  5964. /* Nothing has to be done here. */
  5965. }
  5966. void Channel::input(Measurement measurement)
  5967. {
  5968. emit newData(measurement);
  5969. }
  5970. @ A function is provided for use when a channel is created by a DAQ from a
  5971. script.
  5972. @<Function prototypes for scripting@>=
  5973. void setChannelProperties(QScriptValue value, QScriptEngine *engine);
  5974. @ The implementation is trivial.
  5975. @<Functions for scripting@>=
  5976. void setChannelProperties(QScriptValue value, QScriptEngine *engine)
  5977. {
  5978. setQObjectProperties(value, engine);
  5979. }
  5980. @* Calibration and Unit Conversion.
  5981. \noindent One of the planned features for \pn{} is support for hardware that
  5982. collects non-temperature measurements. This is frequently handled with analog
  5983. voltage signals which are proportional to some range in a meaningful unit. Some
  5984. hardware also requires calibration in software. In many cases both of these can
  5985. be handled at the same time with a single mapping in the form:
  5986. $$f(x) = L_1 + (x - L_2){U_1 - L_1\over{U_2 - L_2}}$$
  5987. \noindent where $L_1$ is the logical lower bound, $L_2$ is the measured lower
  5988. bound, $U_1$ is the logical upper bound, $U_2$ is the measured upper bound, and
  5989. $x$ is the value we wish to map from the range $\lbrack L_2, U_2 \rbrack$ to
  5990. the range $\lbrack L_1, U_1 \rbrack$.
  5991. Some use cases require a closed range but others require that this constraint
  5992. is loosened to allow extrapolation. Both are provided by this class.
  5993. @<Class declarations@>=
  5994. class LinearCalibrator : public QObject@/
  5995. {@/
  5996. @[Q_OBJECT@]@;
  5997. @[Q_PROPERTY(double measuredLower READ measuredLower
  5998. WRITE setMeasuredLower)@]@;
  5999. @[Q_PROPERTY(double measuredUpper READ measuredUpper
  6000. WRITE setMeasuredUpper)@]@;
  6001. @[Q_PROPERTY(double mappedLower READ mappedLower WRITE setMappedLower)@]@;
  6002. @[Q_PROPERTY(double mappedUpper READ mappedUpper WRITE setMappedUpper)@]@;
  6003. @[Q_PROPERTY(bool closedRange READ isClosedRange WRITE setClosedRange)@]@;
  6004. @[Q_PROPERTY(double sensitivity READ sensitivity WRITE setSensitivity)@]@;
  6005. public:@/
  6006. LinearCalibrator(QObject *parent = NULL);
  6007. double measuredLower();
  6008. double measuredUpper();
  6009. double mappedLower();
  6010. double mappedUpper();
  6011. bool isClosedRange();
  6012. double sensitivity();
  6013. @t\4@>@[public slots@t\kern-3pt@>:@]@;
  6014. void setMeasuredLower(double lower);
  6015. void setMeasuredUpper(double upper);
  6016. void setMappedLower(double lower);
  6017. void setMappedUpper(double upper);
  6018. void setClosedRange(bool closed);
  6019. void setSensitivity(double sensitivity);
  6020. void newMeasurement(Measurement measure);
  6021. @t\4@>@[signals:@]@;
  6022. void measurement(Measurement measure);
  6023. private:@/
  6024. double Lo1;
  6025. double Lo2;
  6026. double Up1;
  6027. double Up2;
  6028. double sensitivitySetting;
  6029. bool clamp;
  6030. };
  6031. @ When the measured range and the mapped range are identical and the range is
  6032. open, we have an identity mapping. This is the default state in a newly
  6033. constructed |LinearCalibrator| which should quickly be changed.
  6034. @<LinearCalibrator Implementation@>=
  6035. LinearCalibrator::LinearCalibrator(QObject *parent) :
  6036. QObject(parent), Lo1(0), Lo2(0), Up1(1), Up2(1), sensitivitySetting(0.0), clamp(false)@/
  6037. {
  6038. /* Nothing needs to be done here. */
  6039. }
  6040. @ The functional portion of the class is in the |newMeasurement()| slot. This
  6041. will receive measurements as they come in and emit a |measurement()| signal for
  6042. each with the calibration and unit adjustment performed.
  6043. This method also handles any rounding needed if there has been a call to
  6044. |setSensitivity()|.
  6045. @<LinearCalibrator Implementation@>=
  6046. void LinearCalibrator::newMeasurement(Measurement measure)
  6047. {
  6048. double outval = Lo1 + (measure.temperature() - Lo2) * (Up1 - Lo1)/(Up2 - Lo2);
  6049. if(clamp)
  6050. {
  6051. if(outval < Lo1)
  6052. {
  6053. outval = Lo1;
  6054. }
  6055. else if(outval > Up1)
  6056. {
  6057. outval = Up1;
  6058. }
  6059. }
  6060. if(sensitivitySetting >= 0.05)
  6061. {
  6062. int temp = qRound(outval/sensitivitySetting);
  6063. outval = temp * sensitivitySetting;
  6064. }
  6065. Measurement adjusted(outval, measure.time(), measure.scale());
  6066. emit measurement(adjusted);
  6067. }
  6068. @ The rest of the class consists of trivial accessor methods.
  6069. @<LinearCalibrator Implementation@>=
  6070. double LinearCalibrator::measuredLower()
  6071. {
  6072. return Lo2;
  6073. }
  6074. double LinearCalibrator::measuredUpper()
  6075. {
  6076. return Up2;
  6077. }
  6078. double LinearCalibrator::mappedLower()
  6079. {
  6080. return Lo1;
  6081. }
  6082. double LinearCalibrator::mappedUpper()
  6083. {
  6084. return Up1;
  6085. }
  6086. bool LinearCalibrator::isClosedRange()
  6087. {
  6088. return clamp;
  6089. }
  6090. void LinearCalibrator::setMeasuredLower(double lower)
  6091. {
  6092. Lo2 = lower;
  6093. }
  6094. void LinearCalibrator::setMeasuredUpper(double upper)
  6095. {
  6096. Up2 = upper;
  6097. }
  6098. void LinearCalibrator::setMappedLower(double lower)
  6099. {
  6100. Lo1 = lower;
  6101. }
  6102. void LinearCalibrator::setMappedUpper(double upper)
  6103. {
  6104. Up1 = upper;
  6105. }
  6106. void LinearCalibrator::setClosedRange(bool closed)
  6107. {
  6108. clamp = closed;
  6109. }
  6110. void LinearCalibrator::setSensitivity(double sensitivity)
  6111. {
  6112. sensitivitySetting = sensitivity;
  6113. }
  6114. double LinearCalibrator::sensitivity()
  6115. {
  6116. return sensitivitySetting;
  6117. }
  6118. @ Finally, we make this class available to the scripting engine. Two functions
  6119. are required for this.
  6120. @<Function prototypes for scripting@>=
  6121. QScriptValue constructLinearCalibrator(QScriptContext *context,
  6122. QScriptEngine *engine);
  6123. void setLinearCalibratorProperties(QScriptValue value, QScriptEngine *engine);
  6124. @ The scripting engine is informed of the constructor.
  6125. @<Set up the scripting engine@>=
  6126. constructor = engine->newFunction(constructLinearCalibrator);
  6127. value = engine->newQMetaObject(&LinearCalibrator::staticMetaObject,
  6128. constructor);
  6129. engine->globalObject().setProperty("LinearCalibrator", value);
  6130. @ The implementation of these functions is typical for this application.
  6131. @<Functions for scripting@>=
  6132. QScriptValue constructLinearCalibrator(QScriptContext *, QScriptEngine *engine)
  6133. {
  6134. QScriptValue object = engine->newQObject(new LinearCalibrator(NULL));
  6135. setLinearCalibratorProperties(object, engine);
  6136. return object;
  6137. }
  6138. void setLinearCalibratorProperties(QScriptValue value, QScriptEngine *engine)
  6139. {
  6140. setQObjectProperties(value, engine);
  6141. }
  6142. @* Linear Spline Interpolation.
  6143. \noindent While linear interpolation is adequate for many purposes, it fails
  6144. when a nonlinear mapping is required. The primary use case is to calibrate
  6145. multiple coffee roasters so that roast profiles can be shared among coffee
  6146. roasters with sufficiently similar heat transfer characteristics even if
  6147. differences in the measurement hardware result in different measured values.
  6148. By recording measured values at several points known to be equivalent due to
  6149. easily observable physical changes in the coffee it is possible to use linear
  6150. spline interpolation to produce a data series that approximates on one machine
  6151. the measurements that would have been produced at another. Acceptable results
  6152. may be available with surprisingly few data points.
  6153. It was originally suspected that cubic spline interpolation would produce a
  6154. more accurate mapping, but testing with linear spline interpolation produced
  6155. results good enough that more complex mappings were not needed. Cubic spline
  6156. interpolation may still be implemented in the future, but it is a low
  6157. priority.
  6158. @<Class declarations@>=
  6159. class LinearSplineInterpolator : public QObject
  6160. {
  6161. @[Q_OBJECT@]@/
  6162. public:@/
  6163. LinearSplineInterpolator(QObject *parent = NULL);
  6164. @[Q_INVOKABLE@]@, void add_pair(double source, double destination);
  6165. @[public slots@]:@/
  6166. void newMeasurement(Measurement measure);
  6167. @[signals@]:@/
  6168. void newData(Measurement measure);
  6169. private:@/
  6170. void make_interpolators();
  6171. QMap<double, double> *pairs;
  6172. QList<LinearCalibrator *> *interpolators;
  6173. };
  6174. @ We take advantage of the fact that iterating over a QMap always returns
  6175. entries in key order. When new measurement pairs are specified, the
  6176. interpolators are regenerated. There is significant room for performance
  6177. improvement.
  6178. @<LinearSplineInterpolator Implementation@>=
  6179. void LinearSplineInterpolator::add_pair(double source, double destination)
  6180. {
  6181. pairs->insert(source, destination);
  6182. make_interpolators();
  6183. }
  6184. void LinearSplineInterpolator::make_interpolators()
  6185. {
  6186. if(pairs->size() > 1)
  6187. {
  6188. while(interpolators->size() > 0)
  6189. {
  6190. LinearCalibrator *removed = interpolators->takeFirst();
  6191. removed->deleteLater();
  6192. }
  6193. QMap<double, double>::const_iterator i = pairs->constBegin();
  6194. QMap<double, double>::const_iterator j = i + 1;
  6195. while(j != pairs->constEnd())
  6196. {
  6197. LinearCalibrator *segment = new LinearCalibrator();
  6198. segment->setMeasuredLower(i.key());
  6199. segment->setMappedLower(i.value());
  6200. segment->setMeasuredUpper(j.key());
  6201. segment->setMappedUpper(j.value());
  6202. segment->setClosedRange(false);
  6203. interpolators->append(segment);
  6204. connect(segment, SIGNAL(measurement(Measurement)), this, SIGNAL(newData(Measurement)));
  6205. i++;
  6206. j++;
  6207. }
  6208. }
  6209. }
  6210. LinearSplineInterpolator::LinearSplineInterpolator(QObject *parent) :
  6211. QObject(parent), pairs(new QMap<double, double>),
  6212. interpolators(new QList<LinearCalibrator *>)
  6213. {
  6214. /* Nothing needs to be done here. */
  6215. }
  6216. void LinearSplineInterpolator::newMeasurement(Measurement measure)
  6217. {
  6218. QMap<double, double>::const_iterator i = pairs->constBegin();
  6219. int index = -1;
  6220. while(i != pairs->constEnd())
  6221. {
  6222. if(measure.temperature() <= i.key())
  6223. {
  6224. break;
  6225. }
  6226. i++;
  6227. index++;
  6228. }
  6229. if(index < 0)
  6230. {
  6231. index = 0;
  6232. }
  6233. if(index >= interpolators->size())
  6234. {
  6235. index = interpolators->size() - 1;
  6236. }
  6237. if(interpolators->at(index) != NULL)
  6238. {
  6239. interpolators->at(index)->newMeasurement(measure);
  6240. }
  6241. }
  6242. @ This is exposed to the scripting environment as usual.
  6243. @<Function prototypes for scripting@>=
  6244. QScriptValue constructLinearSplineInterpolator(QScriptContext *context, QScriptEngine *engine);
  6245. void setLinearSplineInterpolatorProperties(QScriptValue value, QScriptEngine *engine);
  6246. @ As usual.
  6247. @<Set up the scripting engine@>=
  6248. constructor = engine->newFunction(constructLinearSplineInterpolator);
  6249. value = engine->newQMetaObject(&LinearSplineInterpolator::staticMetaObject, constructor);
  6250. engine->globalObject().setProperty("LinearSplineInterpolator", value);
  6251. @ And again as usual.
  6252. @<Functions for scripting@>=
  6253. QScriptValue constructLinearSplineInterpolator(QScriptContext *, QScriptEngine *engine)
  6254. {
  6255. QScriptValue object = engine->newQObject(new LinearSplineInterpolator(NULL));
  6256. setLinearSplineInterpolatorProperties(object, engine);
  6257. return object;
  6258. }
  6259. void setLinearSplineInterpolatorProperties(QScriptValue value, QScriptEngine *engine)
  6260. {
  6261. setQObjectProperties(value, engine);
  6262. }
  6263. @* The TemperatureDisplay class.
  6264. Now that measurements have been generated by the |DAQ| and passed to a
  6265. |Channel|, any object that is interested in these measurements can connect to
  6266. the channel and use the measurements it sends out. So far, the time on each
  6267. measurement is the time at which it was collected. Unfortunately, this is often
  6268. not what we want. It is more useful to have the time relative to some other
  6269. point in time such as the start of the batch.
  6270. Until the measurement time is adjusted, the measurements are really only useful
  6271. to classes that do not care about the measurement time. The |TemperatureDisplay|
  6272. class is such a class. It receives measurements and displays the most recently
  6273. measured temperature.
  6274. This is a specialization of |QLCDNumber|.
  6275. @<Class declarations@>=
  6276. class TemperatureDisplay : public QLCDNumber@/
  6277. {@t\1@>@/
  6278. Q_OBJECT@;
  6279. Q_ENUMS(DisplayUnits)
  6280. int unit;
  6281. public:@/
  6282. enum DisplayUnits
  6283. {
  6284. Auto = -1,
  6285. Fahrenheit = 10144,
  6286. Celsius = 10143,
  6287. Kelvin = 10325,
  6288. Rankine = 10145
  6289. };
  6290. TemperatureDisplay(QWidget *parent = NULL);
  6291. ~TemperatureDisplay();@/
  6292. @t\4@>public slots@t\kern-3pt@>:@/
  6293. void setValue(Measurement temperature);
  6294. void invalidate();
  6295. void setDisplayUnits(DisplayUnits scale);@t\2@>@/
  6296. };
  6297. @ Displaying a temperature is a simple matter of taking the temperature
  6298. component from the measurement and converting it to a string. Presently, this
  6299. code assumes that the measurements are in degrees Fahrenheit. If the code
  6300. becomes smarter about measurement units it might be a good idea to change this.
  6301. |QLCDNumber| is capable of displaying more than just numbers, so the call to
  6302. display takes a string which in this case consists of the temperature to the
  6303. $1\over100$th of a degree and might be followed by ' which will be converted to
  6304. $^\circ$ and the letter F, C, or r to indicate the unit. This class should be
  6305. mofified to allow a user specified precision.
  6306. @<TemperatureDisplay Implementation@>=
  6307. void TemperatureDisplay::setValue(Measurement temperature)
  6308. {
  6309. QString number;
  6310. switch(unit)
  6311. {
  6312. case Auto:
  6313. switch(temperature.scale())
  6314. {
  6315. case Fahrenheit:
  6316. display(QString("%1'F").
  6317. arg(number.setNum(temperature.temperature(), 'f', 2)));
  6318. break;
  6319. case Celsius:
  6320. display(QString("%1'C").
  6321. arg(number.setNum(temperature.temperature(), 'f', 2)));
  6322. break;
  6323. case Kelvin:
  6324. display(QString("%1").
  6325. arg(number.setNum(temperature.temperature(), 'f', 2)));
  6326. break;
  6327. case Rankine:
  6328. display(QString("%1'r").
  6329. arg(number.setNum(temperature.temperature(), 'f', 2)));
  6330. break;
  6331. }
  6332. break;
  6333. case Fahrenheit:
  6334. display(QString("%1'F").
  6335. arg(number.setNum(temperature.toFahrenheit().temperature(), 'f',
  6336. 2)));
  6337. break;
  6338. case Celsius:
  6339. display(QString("%1'C").
  6340. arg(number.setNum(temperature.toCelsius().temperature(), 'f',
  6341. 2)));
  6342. break;
  6343. case Kelvin:
  6344. display(QString("%1").
  6345. arg(number.setNum(temperature.toKelvin().temperature(), 'f',
  6346. 2)));
  6347. break;
  6348. case Rankine:
  6349. display(QString("%1'r").
  6350. arg(number.setNum(temperature.toRankine().temperature(), 'f',
  6351. 2)));
  6352. break;
  6353. }
  6354. }
  6355. @ Before measurements are displayed, we set a more sensible default display
  6356. style and an initial string. These defaults can all be overridden with calls to
  6357. the usual |QLCDNumber| methods.
  6358. \medskip
  6359. \resizebox*{6.3in}{!}{\includegraphics{QLCDNumber.png}}
  6360. \smallskip
  6361. \centerline{Figure \secno: Outline (Qt default) and Filled |QLCDNumber| Example}
  6362. \medskip
  6363. @<TemperatureDisplay Implementation@>=
  6364. TemperatureDisplay::TemperatureDisplay(QWidget *parent) :
  6365. QLCDNumber(8, parent), unit(Auto)@/
  6366. {
  6367. setSegmentStyle(Filled);
  6368. display("---.--'F");
  6369. }
  6370. @ While it is not currently used, it would be good to allow an error state to
  6371. be easily discernible from a very stable temperature. Currently, if an error
  6372. occurs that results in the measurement thread exiting, no new measurements will
  6373. be generated and the temperature display will continue to read the most recent
  6374. measured value. If an error signal were emitted, it could be connected to the
  6375. following code to change the display to reflect the fact that the current
  6376. temperature is unknown.
  6377. @<TemperatureDisplay Implementation@>=
  6378. void TemperatureDisplay::invalidate()
  6379. {
  6380. display("---.--'F");
  6381. }
  6382. @ \pn{} supports the display of multiple types of unit. Typically, we use the
  6383. Auto scale which will cause |TemperatureDisplay| objects to display measurements
  6384. in whichever scale the measurement is associated with. Alternately, we can fix
  6385. the scale to a different supported scale and convert measurements to that scale
  6386. prior to display.
  6387. @<TemperatureDisplay Implementation@>=
  6388. void TemperatureDisplay::setDisplayUnits(DisplayUnits scale)
  6389. {
  6390. unit = scale;
  6391. }
  6392. @ All that is left to deal with is the empty destructor.
  6393. @<TemperatureDisplay Implementation@>=
  6394. TemperatureDisplay::~TemperatureDisplay()
  6395. {
  6396. /* Nothing has to be done here. */
  6397. }
  6398. @ To use a |TemperatureDisplay| from a script, we need a function to pass a new
  6399. object to the scripting engine.
  6400. @<Function prototypes for scripting@>=
  6401. QScriptValue constructTemperatureDisplay(QScriptContext *context,
  6402. QScriptEngine *engine);
  6403. void setTemperatureDisplayProperties(QScriptValue value, QScriptEngine *engine);
  6404. @ The scripting engine must be informed of this function.
  6405. @<Set up the scripting engine@>=
  6406. constructor = engine->newFunction(constructTemperatureDisplay);
  6407. value = engine->newQMetaObject(&TemperatureDisplay::staticMetaObject,
  6408. constructor);
  6409. engine->globalObject().setProperty("TemperatureDisplay", value);
  6410. @ The constructor is trivial.
  6411. @<Functions for scripting@>=
  6412. QScriptValue constructTemperatureDisplay(QScriptContext *,
  6413. QScriptEngine *engine)
  6414. {
  6415. QScriptValue object = engine->newQObject(new TemperatureDisplay);
  6416. setTemperatureDisplayProperties(object, engine);
  6417. return object;
  6418. }
  6419. void setTemperatureDisplayProperties(QScriptValue value, QScriptEngine *engine)
  6420. {
  6421. setQLCDNumberProperties(value, engine);
  6422. }
  6423. @* The MeasurementTimeOffset class.
  6424. When a |DAQ| object creates a |Measurement| object, the time component is a
  6425. system time. In most cases, the system time is not interesting and a more useful
  6426. time would be relative to the start of a process. This class should be used as a
  6427. filter, taking measurements with a system time stamp and producing measurements
  6428. with a relative time.
  6429. @<Class declarations@>=
  6430. class MeasurementTimeOffset : public QObject@/
  6431. {@t\1@>@/
  6432. Q_OBJECT@;
  6433. QTime epoch;
  6434. QTime previous;
  6435. bool hasPrevious;@/
  6436. public:@;
  6437. MeasurementTimeOffset(QTime zero);
  6438. QTime zeroTime();@/
  6439. @t\4@>public slots@t\kern-3pt@>:@;
  6440. void newMeasurement(Measurement measure);
  6441. void setZeroTime(QTime zero);
  6442. signals:@;
  6443. void measurement(Measurement measure);@t\2@>@/
  6444. }@t\kern-3pt@>;
  6445. @ The interesting part of this class is the function which takes a measurement
  6446. with a system time and produces a new measurement with a time relative to some
  6447. start time.
  6448. When using this class, it is possible that a measurement will arrive with a time
  6449. slightly before a newly chosen epoch. In such a case we do not want to simply
  6450. subtract the epoch from the measurement time as other classes will interpret
  6451. this incorrectly as a measurement time slightly less than 1 hour. This means
  6452. that we need to check if the measurement time is before the epoch. If it is, we
  6453. consider it to have been generated at the epoch rather than before. Aren't race
  6454. conditions fun?
  6455. Additionally, since we're only getting time of day information, some special
  6456. handling must be done for time series that cross the boundary between days. We
  6457. should never get measurements out of order, so keeping a record of the previous
  6458. measurement and verifying that the new measurement comes after it is sufficient.
  6459. @<MeasurementTimeOffset Implementation@>=
  6460. void MeasurementTimeOffset::newMeasurement(Measurement measure)@t\2\2@>@/
  6461. {@t\1@>@/
  6462. if(measure.time() < epoch)@/
  6463. {
  6464. if(hasPrevious)@/
  6465. {
  6466. QTime jitBase(epoch.hour() - 1, epoch.minute(), epoch.second(),
  6467. epoch.msec());
  6468. QTime jitComp(epoch.hour(), measure.time().minute(),
  6469. measure.time().second(), measure.time().msec());
  6470. int relTime = jitBase.msecsTo(jitComp);
  6471. @<Produce and emit relative time@>@;
  6472. }
  6473. else@/
  6474. {
  6475. Measurement rel(measure.temperature(), QTime(0, 0, 0, 0));
  6476. emit measurement(rel);
  6477. }
  6478. }
  6479. else@/
  6480. {
  6481. int relTime = epoch.msecsTo(measure.time());
  6482. @<Produce and emit relative time@>@;
  6483. }
  6484. hasPrevious = true;
  6485. previous = measure.time();@t\2@>@/
  6486. }
  6487. @ The measurement emitted has a time with the number of minutes, seconds, and
  6488. milliseconds since the start of the batch. We never generate a time greater
  6489. than 1 hour.
  6490. @<Produce and emit relative time@>=
  6491. QTime newTime(0, 0, 0, 0);
  6492. newTime = newTime.addMSecs(relTime);
  6493. if(newTime.hour() > 0)
  6494. {
  6495. newTime.setHMS(0, newTime.minute(), newTime.second(), newTime.msec());
  6496. }
  6497. Measurement rel(measure.temperature(), newTime);
  6498. emit measurement(rel);
  6499. @ The rest of the code handles updating and reporting the reference time.
  6500. @<MeasurementTimeOffset Implementation@>=
  6501. MeasurementTimeOffset::MeasurementTimeOffset(QTime zero) : epoch(zero),
  6502. previous(0, 0, 0, 0), hasPrevious(false)
  6503. {
  6504. /* Nothing has to be done here. */
  6505. }
  6506. QTime MeasurementTimeOffset::zeroTime()
  6507. {
  6508. return epoch;
  6509. }
  6510. void MeasurementTimeOffset::setZeroTime(QTime zero)
  6511. {
  6512. epoch = zero;
  6513. hasPrevious = false;
  6514. }
  6515. @ Two functions are required to make this class available to the scripting
  6516. engine.
  6517. @<Function prototypes for scripting@>=
  6518. QScriptValue constructMeasurementTimeOffset(QScriptContext *context,@|
  6519. QScriptEngine *engine);
  6520. void setMeasurementTimeOffsetProperties(QScriptValue value,
  6521. QScriptEngine *engine);
  6522. @ The scripting engine must be informed of the constructor.
  6523. @<Set up the scripting engine@>=
  6524. constructor = engine->newFunction(constructMeasurementTimeOffset);
  6525. value = engine->newQMetaObject(&MeasurementTimeOffset::staticMetaObject,
  6526. constructor);
  6527. engine->globalObject().setProperty("MeasurementTimeOffset", value);
  6528. @ Previously, another property was added to the newly created object. That
  6529. method is believed to be obsolete and has been removed. Careful testing will
  6530. need to be done to verify that this decision was sane. I was very hungry when
  6531. that change was made.
  6532. @<Functions for scripting@>=
  6533. QScriptValue constructMeasurementTimeOffset(QScriptContext *,
  6534. QScriptEngine *engine)
  6535. {
  6536. QScriptValue object =@|
  6537. engine->newQObject(new MeasurementTimeOffset(QTime::currentTime()));
  6538. setMeasurementTimeOffsetProperties(object, engine);
  6539. return object;
  6540. }
  6541. void setMeasurementTimeOffsetProperties(QScriptValue value,
  6542. QScriptEngine *engine)
  6543. {
  6544. setQObjectProperties(value, engine);
  6545. }
  6546. @* Measured value threshold detection.
  6547. \noindent There are times when one might want to detect when a measured value
  6548. from a data series has passed a given value, with the limitation that we are
  6549. only interested in the ascending or descending edge. This can be used, for
  6550. example, to translate roast profile data in a graph along the time axis such
  6551. that the bean temperature series are aligned at a given
  6552. temperature.\nfnote{More details on the reasoning behind why one might want
  6553. to do this are provided at:\par\indent\pdfURL{http://youtu.be/hS0SfzypyFQ}
  6554. {http://youtu.be/hS0SfzypyFQ}} For this we can use a |ThresholdDetector|.
  6555. If we would like to catch changes on both the ascending and descending edge, we
  6556. can use two objects, however it may be a good idea to use more than two to
  6557. allow for sane behavior in the face of hysteresis.
  6558. @<Class declarations@>=
  6559. class ThresholdDetector : public QObject@/
  6560. {
  6561. @[Q_OBJECT@]@;
  6562. @[Q_ENUMS(EdgeDirection)@]@;
  6563. public:@/
  6564. enum EdgeDirection {
  6565. Ascending, Descending
  6566. };
  6567. ThresholdDetector(double value);
  6568. @[public slots@]:@/
  6569. void newMeasurement(Measurement measure);
  6570. void setThreshold(double value);
  6571. void setEdgeDirection(EdgeDirection direction);
  6572. signals:@/
  6573. void timeForValue(double);
  6574. private:@/
  6575. double previousValue;
  6576. double threshold;
  6577. EdgeDirection currentDirection;
  6578. };
  6579. @ This class emits the time in seconds when a given measurement crosses the
  6580. threshold value in the appropriate direction.
  6581. @<ThresholdDetector Implementation@>=
  6582. void ThresholdDetector::newMeasurement(Measurement measure)
  6583. {
  6584. if((currentDirection == Ascending && previousValue < threshold &&
  6585. previousValue >= 0) || (currentDirection == Descending &&
  6586. previousValue > threshold && previousValue >= 0))
  6587. {
  6588. if((currentDirection == Ascending && measure.temperature() >= threshold) ||
  6589. (currentDirection == Descending && measure.temperature() <= threshold))
  6590. {
  6591. double offset = measure.time().hour() * 60 * 60;
  6592. offset += measure.time().minute() * 60;
  6593. offset += measure.time().second();
  6594. offset += measure.time().msec()/1000;
  6595. emit timeForValue(offset);
  6596. }
  6597. }
  6598. previousValue = measure.temperature();
  6599. }
  6600. ThresholdDetector::ThresholdDetector(double value) : QObject(NULL),
  6601. previousValue(-1), threshold(value), currentDirection(Ascending)
  6602. {
  6603. /* Nothing needs to be done here. */
  6604. }
  6605. void ThresholdDetector::setThreshold(double value)
  6606. {
  6607. threshold = value;
  6608. }
  6609. void ThresholdDetector::setEdgeDirection(EdgeDirection direction)
  6610. {
  6611. currentDirection = direction;
  6612. }
  6613. @ This is exposed to the host environment.
  6614. @<Function prototypes for scripting@>=
  6615. QScriptValue constructThresholdDetector(QScriptContext *context, QScriptEngine *engine);
  6616. void setThresholdDetectorProperties(QScriptValue value, QScriptEngine *engine);
  6617. @ Inform the engine of the constructor.
  6618. @<Set up the scripting engine@>=
  6619. constructor = engine->newFunction(constructThresholdDetector);
  6620. value = engine->newQMetaObject(&ThresholdDetector::staticMetaObject, constructor);
  6621. engine->globalObject().setProperty("ThresholdDetector", value);
  6622. @ Implementation. At present I'm not bothering to implement constructor
  6623. arguments here and am aligning on a fixed point. Another slot method was added
  6624. to restore adjustability.
  6625. @<Functions for scripting@>=
  6626. QScriptValue constructThresholdDetector(QScriptContext *, QScriptEngine *engine)
  6627. {
  6628. QScriptValue object = engine->newQObject(new ThresholdDetector(300));
  6629. return object;
  6630. }
  6631. void setThresholdDetectorProperties(QScriptValue value, QScriptEngine *engine)
  6632. {
  6633. setQObjectProperties(value, engine);
  6634. }
  6635. @* The ZeroEmitter class.
  6636. \noindent Now that it is possible to record the time a measurement was taken
  6637. relative to an arbitrary start time, there is a minor problem left for logging.
  6638. It is extremely unlikely that a measurement will be passed through at the epoch.
  6639. For this, what we want to do is save the previous measurement and make it
  6640. available at time 0 whenever the start time is reset. This is the role of the
  6641. |ZeroEmitter| class.
  6642. Another problem is that most classes that are interested in a relative time are
  6643. also interested in logging multiple sets of temperature data. To facilitate this
  6644. an integer is emitted. Different temperature measurement sources should be set
  6645. to emit different numbers. A table view would place measurements in the
  6646. indicated column. A graph view would use different colors to plot different sets
  6647. of data.
  6648. @<Class declarations@>=
  6649. class ZeroEmitter : public QObject@/
  6650. {@t\1@>@/
  6651. Q_OBJECT@;
  6652. int col;
  6653. double temp;
  6654. public:@/
  6655. ZeroEmitter(int tempcolumn);
  6656. int column();
  6657. double lastTemperature();@/
  6658. @t\4@>public slots@t\kern-3pt@>:@;
  6659. void newMeasurement(Measurement measure);
  6660. void setColumn(int column);
  6661. void emitZero();
  6662. signals:@;
  6663. void measurement(Measurement measure, int tempcolumn);@t\2@>@/
  6664. }@t\kern-3pt@>;
  6665. @ The implementation of the class is trivial.
  6666. @<ZeroEmitter Implementation@>=
  6667. ZeroEmitter::ZeroEmitter(int tempcolumn) : QObject(NULL), col(tempcolumn),
  6668. temp(0)@;
  6669. {
  6670. /* Nothing has to be done here. */
  6671. }
  6672. int ZeroEmitter::column()
  6673. {
  6674. return col;
  6675. }
  6676. double ZeroEmitter::lastTemperature()
  6677. {
  6678. return temp;
  6679. }
  6680. void ZeroEmitter::newMeasurement(Measurement measure)
  6681. {
  6682. temp = measure.temperature();
  6683. }
  6684. void ZeroEmitter::setColumn(int column)
  6685. {
  6686. col = column;
  6687. }
  6688. void ZeroEmitter::emitZero()
  6689. {
  6690. emit measurement(Measurement(temp, QTime(0, 0, 0, 0)), col);
  6691. }
  6692. @ Making this class available to scripts requires only two functions.
  6693. @<Function prototypes for scripting@>=
  6694. QScriptValue constructZeroEmitter(QScriptContext *context,
  6695. QScriptEngine *engine);
  6696. void setZeroEmitterProperties(QScriptValue value, QScriptEngine *engine);
  6697. @ To use it, we must inform the engine of the constructor.
  6698. @<Set up the scripting engine@>=
  6699. constructor = engine->newFunction(constructZeroEmitter);
  6700. value = engine->newQMetaObject(&ZeroEmitter::staticMetaObject, constructor);
  6701. engine->globalObject().setProperty("ZeroEmitter", value);
  6702. @ The implementation of the constructor is trivial.
  6703. @<Functions for scripting@>=
  6704. QScriptValue constructZeroEmitter(QScriptContext *context,
  6705. QScriptEngine *engine)
  6706. {
  6707. QScriptValue object =
  6708. engine->newQObject(new ZeroEmitter(argument<int>(0, context)));
  6709. setZeroEmitterProperties(object, engine);
  6710. return object;
  6711. }
  6712. void setZeroEmitterProperties(QScriptValue value, QScriptEngine *engine)
  6713. {
  6714. setQObjectProperties(value, engine);
  6715. }
  6716. @* The MeasurementAdapter class.
  6717. \noindent The last of the measurement filter classes is the |MeasurementAdapter|
  6718. class. This takes measurements, typically from a |MeasurementTimeOffset|, and
  6719. sends the measurement out with a number to indicate which data series the
  6720. measurement belongs to.
  6721. The measurement pipeline could probably be made simpler by introducing a series
  6722. identifier into the measurement class.
  6723. @<Class declarations@>=
  6724. class MeasurementAdapter : public QObject@/
  6725. {@t\1@>@/
  6726. Q_OBJECT@;
  6727. int col;
  6728. public:@/
  6729. MeasurementAdapter(int tempcolumn);
  6730. int column();@/
  6731. @t\4@>public slots@t\kern-3pt@>:@/
  6732. void newMeasurement(Measurement measure);
  6733. void setColumn(int column);
  6734. signals:@/
  6735. void measurement(Measurement measure, int tempcolumn);@t\2@>@/
  6736. }@t\kern-3pt@>;
  6737. @ The implementation of this filter class is trivial.
  6738. @<MeasurementAdapter Implementation@>=
  6739. MeasurementAdapter::MeasurementAdapter(int tempcolumn) : col(tempcolumn)@;
  6740. {
  6741. /* Nothing has to be done here. */
  6742. }
  6743. int MeasurementAdapter::column()
  6744. {
  6745. return col;
  6746. }
  6747. void MeasurementAdapter::newMeasurement(Measurement measure)
  6748. {
  6749. emit measurement(measure, col);
  6750. }
  6751. void MeasurementAdapter::setColumn(int column)
  6752. {
  6753. col = column;
  6754. }
  6755. @ This filter class is also available from the host environment.
  6756. @<Function prototypes for scripting@>=
  6757. QScriptValue constructMeasurementAdapter(QScriptContext *context,
  6758. QScriptEngine *engine);
  6759. void setMeasurementAdapterProperties(QScriptValue value, QScriptEngine *engine);
  6760. @ As usual, the engine must be informed of the constructor.
  6761. @<Set up the scripting engine@>=
  6762. constructor = engine->newFunction(constructMeasurementAdapter);
  6763. value = engine->newQMetaObject(&MeasurementAdapter::staticMetaObject,
  6764. constructor);
  6765. engine->globalObject().setProperty("MeasurementAdapter", value);
  6766. @ The implementation is trivial.
  6767. @<Functions for scripting@>=
  6768. QScriptValue constructMeasurementAdapter(QScriptContext *context,
  6769. QScriptEngine *engine)
  6770. {
  6771. QScriptValue object =
  6772. engine->newQObject(new MeasurementAdapter(argument<int>(0, context)));
  6773. setMeasurementAdapterProperties(object, engine);
  6774. return object;
  6775. }
  6776. void setMeasurementAdapterProperties(QScriptValue value, QScriptEngine *engine)
  6777. {
  6778. setQObjectProperties(value, engine);
  6779. }
  6780. @* A graph of temperature over time.
  6781. \noindent A useful tool when roasting is a visual depiction of the current batch
  6782. as it happens, possibly laid over a previously recorded target profile. The
  6783. |GraphView| class can take multiple sets of temperature data and produce such a
  6784. visualization.
  6785. \medskip
  6786. \centerline{\includegraphics{roast}}
  6787. \smallskip
  6788. \centerline{Figure \secno: A Typical Roast}
  6789. \medskip
  6790. This class assumes that temperature data will be passed in the correct order.
  6791. @<Class declarations@>=
  6792. class GraphView : public QGraphicsView@/
  6793. {@t\1@>@/
  6794. Q_OBJECT@;
  6795. QGraphicsScene *theScene;@/
  6796. QMap<int, QList<QGraphicsLineItem * > * > *graphLines;@/
  6797. QMap<int, QPointF> *prevPoints;
  6798. QMap<int, double> *translations;
  6799. QList<QGraphicsItem *> *gridLinesF;
  6800. QList<QGraphicsItem *> *gridLinesC;@/
  6801. public:@/
  6802. GraphView(QWidget *parent = NULL);
  6803. void removeSeries(int column);@/
  6804. protected:@/
  6805. void resizeEvent(QResizeEvent *event);@/
  6806. @t\4@>public slots@t\kern-3pt@>:@/
  6807. void newMeasurement(Measurement measure, int tempcolumn);
  6808. void setSeriesTranslation(int column, double offset);
  6809. void clear();
  6810. void showF();
  6811. void showC();@t\2@>@/
  6812. }@t\kern-3pt@>;
  6813. @ I decided that it would probably be best to keep the graph area the same even
  6814. with different roast lengths over different temperature ranges so that similar
  6815. portions between these graphs would continue to look similar rather than
  6816. constantly attempting to select the best way to display the data currently in
  6817. the view.
  6818. I have chosen to represent roasting times of up to 20 minutes and temperatures
  6819. between 0 and 500$^\circ$ Fahrenheit. This should certainly be configurable at
  6820. run time, but until that is implemented, roasters who routinely roast batches
  6821. for longer periods of time will want to change the constructor. This class
  6822. should probably be modified to allow the user to specify several characteristics
  6823. of the display.
  6824. This class must also deal with the fact that coordinates in a |QGraphicsScene|
  6825. are not quite the same as coordinates in a cartesian plane. The easiest way to
  6826. deal with this is to negate the y coordinate and translate the viewport to the
  6827. area we draw in.
  6828. A small margin area left around the edges of the graph. This should probably be
  6829. configurable for those with particularly small displays.
  6830. @<GraphView Implementation@>=
  6831. GraphView::GraphView(QWidget *parent) : QGraphicsView(parent),
  6832. theScene(new QGraphicsScene),@/
  6833. graphLines(new QMap<int, QList<QGraphicsLineItem *> *>),@/
  6834. prevPoints(new QMap<int, QPointF>),
  6835. translations(new QMap<int, double>),
  6836. gridLinesF(new QList<QGraphicsItem *>),
  6837. gridLinesC(new QList<QGraphicsItem *>)@/
  6838. {
  6839. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  6840. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  6841. setScene(theScene);
  6842. setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
  6843. @<Draw temperature axis and grid lines@>;
  6844. @<Draw time axis and ticks@>;
  6845. fitInView(theScene->sceneRect().adjusted(-50,-50,50,50));
  6846. }
  6847. @ Grid lines are drawn every 100 degrees. These lines are labeled with
  6848. |setHtml()| for convenient access to the $^\circ$ symbol. If \pn{} is modified
  6849. to allow different units, this code should also be modified.
  6850. As of version 1.3.3 it is possible to switch the graph between degrees
  6851. Fahrenheit and degrees Celcius. Celcius grid lines are drawn but initially
  6852. hidden. Both the grid lines and the labels are added to a list depending on the
  6853. unit so that when changing from one view to another all that needs to happen is
  6854. hide one list of items and show another.
  6855. @<Draw temperature axis and grid lines@>=
  6856. QGraphicsLineItem *tempaxis = new QGraphicsLineItem;
  6857. tempaxis->setLine(-10, -500, -10, 0);
  6858. theScene->addItem(tempaxis);
  6859. QGraphicsLineItem *gridLine;
  6860. QGraphicsTextItem *label;
  6861. for(int y = -100; y > -600; y -= 100)@/
  6862. {@/
  6863. gridLine = new QGraphicsLineItem;
  6864. gridLine->setLine(0, y, 1200, y);
  6865. theScene->addItem(gridLine);
  6866. label = new QGraphicsTextItem;
  6867. label->setHtml(QString("%1&deg;F").arg(-y));
  6868. label->setPos(-55, y - (label->boundingRect().height() / 2));
  6869. theScene->addItem(label);
  6870. gridLinesF->append(gridLine);
  6871. gridLinesF->append(label);
  6872. }
  6873. for(int degC = 50; degC <= 250; degC += 50)
  6874. {
  6875. gridLine = new QGraphicsLineItem;
  6876. int y = -(degC * (9.0/5.0) + 32);
  6877. gridLine->setLine(0, y, 1200, y);
  6878. gridLine->hide();
  6879. theScene->addItem(gridLine);
  6880. gridLinesC->append(gridLine);
  6881. label = new QGraphicsTextItem;
  6882. label->setHtml(QString("%1&deg;C").arg(degC));
  6883. label->setPos(-55, y - (label->boundingRect().height() / 2));
  6884. label->hide();
  6885. theScene->addItem(label);
  6886. gridLinesC->append(label);
  6887. }
  6888. @ Two slots are used to switch between the different sets of grid lines.
  6889. @<GraphView Implementation@>=
  6890. void GraphView::showF()
  6891. {
  6892. for(int i = 0; i < gridLinesF->size(); i++)
  6893. {
  6894. gridLinesF->at(i)->show();
  6895. }
  6896. for(int i = 0; i < gridLinesC->size(); i++)
  6897. {
  6898. gridLinesC->at(i)->hide();
  6899. }
  6900. }
  6901. void GraphView::showC()
  6902. {
  6903. for(int i = 0; i < gridLinesF->size(); i++)
  6904. {
  6905. gridLinesF->at(i)->hide();
  6906. }
  6907. for(int i = 0; i < gridLinesC->size(); i++)
  6908. {
  6909. gridLinesC->at(i)->show();
  6910. }
  6911. }
  6912. @ The time axis has a tick every two minutes. The use of the |?| tertiary
  6913. operator shifts the labels with two digits a little more than labels with only
  6914. one digit. If it worked, a more resilient approach would be to take the width of
  6915. the label and center it under the tick.
  6916. @<Draw time axis and ticks@>=
  6917. QGraphicsLineItem *timeaxis = new QGraphicsLineItem;
  6918. timeaxis->setLine(0, 10, 1200, 10);
  6919. theScene->addItem(timeaxis);
  6920. for(int x = 0; x < 1201; x += 120)@/
  6921. {@/
  6922. QGraphicsLineItem *tick = new QGraphicsLineItem;
  6923. tick->setLine(x, 0, x, 20);
  6924. theScene->addItem(tick);
  6925. QGraphicsTextItem *label = new QGraphicsTextItem;
  6926. label->setPlainText(QString("%1").arg(x/60));
  6927. label->setPos(x - (label->boundingRect().width() / 2), 20);
  6928. theScene->addItem(label);
  6929. }
  6930. @ Typically, the user will be able to resize the graph. When the widget is
  6931. resized, we should fit the graph to the new size of the widget. This is safe to
  6932. do as we have already turned off the scroll bars.
  6933. @<GraphView Implementation@>=
  6934. void GraphView::resizeEvent(QResizeEvent *)
  6935. {
  6936. fitInView(theScene->sceneRect().adjusted(-50,-50,50,50));
  6937. }
  6938. @ When adding a new measurement, there are three cases that should be
  6939. considered. In the case of the first measurement, no drawing occurs. A |QList|
  6940. of line items is initialized when the second measurement is taken. Subsequent
  6941. measurements are able to simply append new line segments to the list.
  6942. @<GraphView Implementation@>=
  6943. void GraphView::newMeasurement(Measurement measure, int tempcolumn)@/
  6944. {@/
  6945. double offset = 0;
  6946. if(translations->contains(tempcolumn))
  6947. {
  6948. offset = translations->value(tempcolumn);
  6949. }
  6950. if(prevPoints->contains(tempcolumn))@/
  6951. @t\1@>{@/
  6952. @<At least one measurement exists@>@;
  6953. if(graphLines->contains(tempcolumn))@/
  6954. {@t\1@>
  6955. /* More than one measurement existed. */
  6956. graphLines->value(tempcolumn)->append(segment);@t\2@>@/
  6957. }@/
  6958. else@/
  6959. {@/
  6960. /* This is the second measurement. */
  6961. QList<QGraphicsLineItem *> *newLine =
  6962. new QList<QGraphicsLineItem *>;@/
  6963. newLine->append(segment);
  6964. graphLines->insert(tempcolumn, newLine);
  6965. }@t\2@>@/
  6966. }@/
  6967. else@/
  6968. {@/
  6969. @<Handle the first measurement@>@;
  6970. }
  6971. }
  6972. @ There are some parts of the code that are correct, but seem somewhat goofy.
  6973. This is especially true surrounding the graphics view architecture as this was
  6974. not working correctly when I wrote the code that uses it. The code as it is
  6975. written works for me, but when these workarounds are no longer needed it would
  6976. be better to remove them. Handling values on the time axis is one example of
  6977. this.
  6978. Some might question the use of an integer data type, particularly when storing
  6979. the result of a division operation. While this could be a concern if high
  6980. resolution wall sized displays become common, is is expected that in most cases
  6981. with sufficiently high sample rates, many data points will map to the same pixel
  6982. even with the minor data loss below.
  6983. In the case of the first measurement,
  6984. @d FULLTIMETOINT(t) (t.msec() + (t.second() * 1000) + (t.minute() * 60 * 1000))
  6985. @<Handle the first measurement@>=
  6986. int x = FULLTIMETOINT(measure.time())/1000;
  6987. prevPoints->insert(tempcolumn, QPointF(x, measure.temperature()));
  6988. @ When at least one measurement already exists, we need to handle drawing the
  6989. line between the new measurement and the previous measurement.
  6990. \danger At present, the color chosen for these lines is based on the temperature
  6991. column passed to the graph. It would be better if colors could be passed to the
  6992. view for a specified series rather than have this hard coded. \endanger
  6993. @<At least one measurement exists@>=
  6994. QGraphicsLineItem *segment = new QGraphicsLineItem;
  6995. QPointF nextPoint(FULLTIMETOINT(measure.time())/1000, measure.temperature());
  6996. segment->setLine(prevPoints->value(tempcolumn).x() + offset,
  6997. -(prevPoints->value(tempcolumn).y()),
  6998. nextPoint.x() + offset, -(nextPoint.y()));
  6999. static QColor p[12] = {Qt::yellow, Qt::blue, Qt::cyan, Qt::red, Qt::magenta,
  7000. Qt::green, Qt::darkGreen, Qt::darkMagenta,
  7001. Qt::darkRed, Qt::darkCyan, Qt::darkBlue,
  7002. Qt::darkYellow};
  7003. segment->setPen(p[tempcolumn % 12]);
  7004. theScene->addItem(segment);
  7005. prevPoints->insert(tempcolumn, nextPoint);
  7006. @ In addition to adding data to the view, we also sometimes want to clear the
  7007. view of data.
  7008. @<GraphView Implementation@>=
  7009. void GraphView::clear()
  7010. {
  7011. int i;
  7012. foreach(i, prevPoints->keys())
  7013. {
  7014. removeSeries(i);
  7015. }
  7016. translations->clear();
  7017. }
  7018. @ Removing a set of data from the view involves removing the lines from the
  7019. scene and removing the column from a couple data structures.
  7020. @<GraphView Implementation@>=
  7021. void GraphView::removeSeries(int column)
  7022. {
  7023. if(graphLines->contains(column))
  7024. {
  7025. QList<QGraphicsLineItem *> *series = graphLines->value(column);
  7026. QGraphicsLineItem *segment;
  7027. foreach(segment, *series)
  7028. {
  7029. theScene->removeItem(segment);
  7030. }
  7031. qDeleteAll(*series);
  7032. }
  7033. graphLines->remove(column);
  7034. prevPoints->remove(column);
  7035. }
  7036. @ Second prototype for data series translation.
  7037. @<GraphView Implementation@>=
  7038. void GraphView::setSeriesTranslation(int column, double offset)
  7039. {
  7040. if(graphLines->contains(column))
  7041. {
  7042. QList<QGraphicsLineItem *> *series = graphLines->value(column);
  7043. QGraphicsLineItem *segment;
  7044. foreach(segment, *series)
  7045. {
  7046. segment->setPos(segment->pos().x()+offset, segment->pos().y());
  7047. }
  7048. }
  7049. if(translations->contains(column))
  7050. {
  7051. translations->insert(column, offset + translations->value(column));
  7052. }
  7053. else
  7054. {
  7055. translations->insert(column, offset);
  7056. }
  7057. }
  7058. @ These functions are required to create a |GraphView| object from a script.
  7059. @<Function prototypes for scripting@>=
  7060. void setGraphViewProperties(QScriptValue value, QScriptEngine *engine);
  7061. QScriptValue constructGraphView(QScriptContext *context, QScriptEngine *engine);
  7062. @ The scripting engine must be informed of the constructor.
  7063. @<Set up the scripting engine@>=
  7064. constructor = engine->newFunction(constructGraphView);
  7065. value = engine->newQMetaObject(&GraphView::staticMetaObject, constructor);
  7066. engine->globalObject().setProperty("GraphView", value);
  7067. @ The function implementation is trivial.
  7068. @<Functions for scripting@>=
  7069. QScriptValue constructGraphView(QScriptContext *, QScriptEngine *engine)
  7070. {
  7071. QScriptValue object = engine->newQObject(new GraphView);
  7072. setGraphViewProperties(object, engine);
  7073. return object;
  7074. }
  7075. void setGraphViewProperties(QScriptValue value, QScriptEngine *engine)
  7076. {
  7077. setQGraphicsViewProperties(value, engine);
  7078. }
  7079. @* A table of roasting data.
  7080. \noindent A typical roast log is a table listing temperature measurements taken
  7081. at regular intervals. The introduction of a computer brings several advantages.
  7082. A human does not need to record the measurements. Every measurement taken can be
  7083. logged, but the measurements do not all need to be displayed. The |ZoomLog|
  7084. class presents a table with time, temperature, and annotation for one or more
  7085. sets of roasting data and allows the user to select from a few different levels
  7086. of detail.
  7087. Experience has shown that one measurement every 30 or 15 seconds is most useful,
  7088. but it is also possible to view one measurement every 1, 5, 10, or 60 seconds
  7089. and there is an option to view every measurement collected. This last is what is
  7090. saved to a file.
  7091. The zooming log is implemented by keeping a measurement model with every level
  7092. of detail of interest and making sure that new measurements get to the models
  7093. they belong in. Switching the level of detail of the view then becomes a matter
  7094. of changing which model the view is using. This is very inefficient in terms of
  7095. space, but it is very fast and simple to code.
  7096. Starting in version 1.4, column sizes are persisted automatically using the
  7097. same method as described in the section on |SqlQueryView|.
  7098. @<Class declarations@>=
  7099. class MeasurementModel;@/
  7100. class ZoomLog : public QTableView@/
  7101. {@/
  7102. @[Q_OBJECT@]@;
  7103. @<ZoomLog private member data@>@;
  7104. void switchLOD(MeasurementModel *m);@/
  7105. @[private slots@]:@/
  7106. void centerOn(int row);
  7107. void persistColumnResize(int column, int oldsize, int newsize);
  7108. void restoreColumnWidths();
  7109. public:@/
  7110. ZoomLog();
  7111. QVariant data(int row, int column) const;
  7112. int rowCount();
  7113. bool saveXML(QIODevice *device);
  7114. bool saveCSV(QIODevice *device);
  7115. QString lastTime(int series);
  7116. @[Q_INVOKABLE@,@, int displayUnits()@];@t\2\2@>@/
  7117. @[public slots@]:@/
  7118. void setVisible(bool visibility);
  7119. void setHeaderData(int section, QString text);
  7120. void LOD_ms();
  7121. void LOD_1s();
  7122. void LOD_5s();
  7123. void LOD_10s();
  7124. void LOD_15s();
  7125. void LOD_30s();
  7126. void LOD_1m();
  7127. void newMeasurement(Measurement measure, int tempcolumn);
  7128. void newAnnotation(QString annotation, int tempcolumn,
  7129. int annotationcolumn);
  7130. void clear();
  7131. void addOutputTemperatureColumn(int column);
  7132. void addOutputAnnotationColumn(int column);
  7133. void clearOutputColumns();
  7134. void setDisplayUnits(int scale);
  7135. void addToCurrentColumnSet(int column);
  7136. void clearCurrentColumnSet();@/
  7137. protected:@/
  7138. virtual void showEvent(QShowEvent *event);
  7139. };
  7140. @ This class uses a different model for each level of detail and provides logic
  7141. for placing measurements and annotations in the appropriate models. A list of
  7142. each model is provided for conveniently performing operations that apply to
  7143. every model.
  7144. @<ZoomLog private member data@>=
  7145. MeasurementModel *model_ms;
  7146. MeasurementModel *model_1s;
  7147. MeasurementModel *model_5s;
  7148. MeasurementModel *model_10s;
  7149. MeasurementModel *model_15s;
  7150. MeasurementModel *model_30s;
  7151. MeasurementModel *model_1m;
  7152. QList<MeasurementModel *> modelSet;
  7153. QHash<int, Measurement> lastMeasurement;
  7154. MeasurementModel *currentModel;
  7155. QList<int> saveTempCols;
  7156. QList<int> saveNoteCols;
  7157. QList<int> currentColumnSet;
  7158. @ Most of the functionality this class provides is in getting measurements to
  7159. the right models. Every measurement goes to the full detail model. We also keep
  7160. track of the most recent measurement to detect the first measurement in a new
  7161. second and pass all of these on to the 1 second level of detail model. Some of
  7162. these are also passed to other models. Additionally, the models that store
  7163. coarser data strip the millisecond portion of the time.
  7164. A decision was made to present data promptly. With a high sample rate, some
  7165. might prefer an average of a few measurements near the reported time, but such
  7166. a feature does not exist in \pn{} currently.
  7167. The first measurement is always added to each model.
  7168. @<ZoomLog Implementation@>=
  7169. void ZoomLog::newMeasurement(Measurement measure, int tempcolumn)
  7170. {
  7171. model_ms->newMeasurement(measure, tempcolumn);
  7172. if(lastMeasurement.contains(tempcolumn))
  7173. {
  7174. if(measure.time().second() !=
  7175. lastMeasurement.value(tempcolumn).time().second())
  7176. {
  7177. Measurement adjusted(measure.temperature(),
  7178. QTime(0, measure.time().minute(),
  7179. measure.time().second(), 0));
  7180. model_1s->newMeasurement(adjusted, tempcolumn);
  7181. if(adjusted.time().second() % 5 == 0)
  7182. {
  7183. model_5s->newMeasurement(adjusted, tempcolumn);
  7184. if(adjusted.time().second() % 10 == 0)
  7185. {
  7186. model_10s->newMeasurement(adjusted, tempcolumn);
  7187. }
  7188. if(adjusted.time().second() % 15 == 0)
  7189. {
  7190. model_15s->newMeasurement(adjusted, tempcolumn);
  7191. if(adjusted.time().second() % 30 == 0)
  7192. {
  7193. model_30s->newMeasurement(adjusted, tempcolumn);
  7194. if(adjusted.time().second() == 0)
  7195. {
  7196. model_1m->newMeasurement(adjusted, tempcolumn);
  7197. }
  7198. }
  7199. }
  7200. }
  7201. }
  7202. @<Synthesize measurements for columns in set@>@;
  7203. }
  7204. else
  7205. {
  7206. @<Add the first measurement to every model@>@;
  7207. }
  7208. lastMeasurement[tempcolumn] = measure;
  7209. }
  7210. @ The first measurement in a series should be the epoch measurement. This
  7211. should exist in every level of detail.
  7212. @<Add the first measurement to every model@>=
  7213. MeasurementModel *m;
  7214. foreach(m, modelSet)
  7215. {
  7216. m->newMeasurement(measure, tempcolumn);
  7217. }
  7218. @ New to \pn{} 1.4 is the concept of a current column set. This was added to
  7219. improve support for devices where measurements on different data series may not
  7220. arrive at exactly the same time and for multi-device configurations where
  7221. measurements from different devices are unlikely to arrive at the same time.
  7222. This can cause issues with log annotations and serialization. The solution is
  7223. to group all columns that are logically part of the same data acquisition
  7224. process and as measurements come in, the most recent measurement from other
  7225. columns can be duplicated at the new time. Two methods are responsible for
  7226. managing this measurement set. One adds a column to the set and the other
  7227. removes all columns from the set.
  7228. @<ZoomLog Implementation@>=
  7229. void ZoomLog::addToCurrentColumnSet(int column)
  7230. {
  7231. currentColumnSet.append(column);
  7232. }
  7233. void ZoomLog::clearCurrentColumnSet()
  7234. {
  7235. currentColumnSet.clear();
  7236. }
  7237. @ Replicating the measurements occurs as measurements are delivered. Note
  7238. that this code will not be called for the first measurement in each column.
  7239. @<Synthesize measurements for columns in set@>=
  7240. if(currentColumnSet.contains(tempcolumn))
  7241. {
  7242. int replicationcolumn;
  7243. foreach(replicationcolumn, currentColumnSet)
  7244. {
  7245. if(replicationcolumn != tempcolumn)
  7246. {
  7247. if(lastMeasurement.contains(replicationcolumn))
  7248. {
  7249. if(measure.time() > lastMeasurement.value(replicationcolumn).time())
  7250. {
  7251. Measurement synthetic(lastMeasurement.value(replicationcolumn).temperature(),
  7252. measure.time());
  7253. model_ms->newMeasurement(synthetic, replicationcolumn);
  7254. if(synthetic.time().second() != lastMeasurement.value(replicationcolumn).time().second())
  7255. {
  7256. Measurement adjusted(synthetic.temperature(), QTime(0, synthetic.time().minute(), synthetic.time().second(), 0));
  7257. model_1s->newMeasurement(adjusted, replicationcolumn);
  7258. if(adjusted.time().second() % 5 == 0)
  7259. {
  7260. model_5s->newMeasurement(adjusted, replicationcolumn);
  7261. if(adjusted.time().second() % 10 == 0)
  7262. {
  7263. model_10s->newMeasurement(adjusted, replicationcolumn);
  7264. }
  7265. if(adjusted.time().second() % 15 == 0)
  7266. {
  7267. model_15s->newMeasurement(adjusted, replicationcolumn);
  7268. if(adjusted.time().second() % 30 == 0)
  7269. {
  7270. model_30s->newMeasurement(adjusted, replicationcolumn);
  7271. if(adjusted.time().second() == 0)
  7272. {
  7273. model_1m->newMeasurement(adjusted, replicationcolumn);
  7274. }
  7275. }
  7276. }
  7277. }
  7278. }
  7279. lastMeasurement[replicationcolumn] = synthetic;
  7280. }
  7281. }
  7282. }
  7283. }
  7284. }
  7285. @ Just as the first measurement should exist at every level of detail, so should
  7286. any annotations. The measurement models will, when presented with an annotation,
  7287. apply it to the most recently entered measurement in the specified data series.
  7288. This presents a problem for the coarser views as the data point the annotation
  7289. belongs to most likely does not exist in that view. Furthermore, the model as it
  7290. is currently written will overwrite annotations that already exist on a
  7291. measurement if it is still the most recently entered. When collecting samples
  7292. during profile development, it is common to produce several annotations in a
  7293. short amount of time. The most useful thing to do in such a case is to add the
  7294. most recent measurement to each model and then apply the annotation. This, of
  7295. course, should only be done if there is a most recent measurement. An annotation
  7296. regarding the starting condition of the roaster should apply to the yet to be
  7297. recorded time zero measurement.
  7298. Note that only the value from the temperature column specified is displayed in
  7299. the row with the annotation. It would be better to check the full detail model
  7300. to determine if there are other measurements at the annotation time and present
  7301. these as well. Another possibility in the case of data not existing in other
  7302. temperature columns would be to interpolate a value from the existing data in
  7303. these columns, however this is potentially challenging as I would want to keep
  7304. true measurements distinct from estimations.
  7305. @<ZoomLog Implementation@>=
  7306. void ZoomLog::newAnnotation(QString annotation, int tempcolumn,
  7307. int annotationcolumn)
  7308. {
  7309. model_ms->newAnnotation(annotation, tempcolumn, annotationcolumn);
  7310. MeasurementModel *m;
  7311. if(lastMeasurement.contains(tempcolumn))
  7312. {
  7313. foreach(m, modelSet)
  7314. {
  7315. m->newMeasurement(lastMeasurement.value(tempcolumn), tempcolumn);
  7316. }
  7317. }
  7318. foreach(m, modelSet)
  7319. {
  7320. m->newAnnotation(annotation, tempcolumn, annotationcolumn);
  7321. }
  7322. }
  7323. @ As measurements are added to the model, the model will emit rowChanged
  7324. signals. These signals are connected to a function here that will attempt to
  7325. scroll the view to keep the most recently entered data in the center of the
  7326. view.
  7327. @<ZoomLog Implementation@>=
  7328. void ZoomLog::centerOn(int row)
  7329. {
  7330. scrollTo(currentModel->index(row, 0), QAbstractItemView::PositionAtCenter);
  7331. }
  7332. @ Once we are done with the data in the table, we want to clear it to prepare
  7333. for new data. This also clears the lists holding the output columns to use when
  7334. saving data.
  7335. @<ZoomLog Implementation@>=
  7336. void ZoomLog::clear()
  7337. {
  7338. MeasurementModel *m;
  7339. foreach(m, modelSet)
  7340. {
  7341. m->clear();
  7342. }
  7343. lastMeasurement.clear();
  7344. saveTempCols.clear();
  7345. saveNoteCols.clear();
  7346. }
  7347. @ These are depreciated methods originally written to assist in serializing
  7348. model data prior to the introduction of the |XMLOutput| class. These methods are
  7349. likely to be removed in a future version of the program.
  7350. @<ZoomLog Implementation@>=
  7351. QVariant ZoomLog::data(int row, int column) const
  7352. {
  7353. return model_ms->data(model_ms->index(row, column, QModelIndex()),
  7354. Qt::DisplayRole);
  7355. }
  7356. int ZoomLog::rowCount()
  7357. {
  7358. return model_ms->rowCount();
  7359. }
  7360. @ This method initializes an |XMLOutput| instance, passes the columns that we
  7361. would like to save to that object, and uses it to write an XML file with the
  7362. desired data to the specified device.
  7363. Since the output format does not currently specify a unit, there is an
  7364. assumption that the XML output will always have measurements in Fahrenheit. If
  7365. the model is not currently displaying measurements in Fahrenheit, it is asked to
  7366. do so before writing the XML data. User preference is restored after the XML
  7367. data has been written. Since this change is only performed on |model_ms|, most
  7368. users will never notice this.
  7369. @<ZoomLog Implementation@>=
  7370. bool ZoomLog::saveXML(QIODevice *device)
  7371. {
  7372. int prevUnits = model_ms->displayUnits();
  7373. if(prevUnits != 10144)
  7374. {
  7375. model_ms->setDisplayUnits(10144);
  7376. }
  7377. XMLOutput writer(model_ms, device, 0);
  7378. int c;
  7379. foreach(c, saveTempCols)
  7380. {
  7381. writer.addTemperatureColumn(model_ms->headerData(c, Qt::Horizontal).
  7382. toString(), c);
  7383. }
  7384. foreach(c, saveNoteCols)
  7385. {
  7386. writer.addAnnotationColumn(model_ms->headerData(c, Qt::Horizontal).
  7387. toString(), c);
  7388. }
  7389. bool retval = writer.output();
  7390. if(prevUnits != 10144)
  7391. {
  7392. model_ms->setDisplayUnits(prevUnits);
  7393. }
  7394. return retval;
  7395. }
  7396. @ This method is similar to |saveXML()|. The main difference is that CSV data is
  7397. exported instead of XML.
  7398. @<ZoomLog Implementation@>=
  7399. bool ZoomLog::saveCSV(QIODevice *device)
  7400. {
  7401. CSVOutput writer(currentModel, device, 0);
  7402. int c;
  7403. foreach(c, saveTempCols)
  7404. {
  7405. writer.addTemperatureColumn(model_ms->headerData(c, Qt::Horizontal).
  7406. toString(), c);
  7407. }
  7408. foreach(c, saveNoteCols)
  7409. {
  7410. writer.addAnnotationColumn(model_ms->headerData(c, Qt::Horizontal).
  7411. toString(), c);
  7412. }
  7413. return writer.output();
  7414. }
  7415. @ Several little functions, all alike\nfnote{If you get the reference, you may
  7416. enjoy reading another \cweb{} program:\par\indent\pdfURL{%
  7417. http://www-cs-staff.stanford.edu/$\sim$uno/programs/advent.w.gz}
  7418. {http://www-cs-staff.stanford.edu/~uno/programs/advent.w.gz}}, are used to
  7419. switch the view from one level of detail to another.
  7420. @<ZoomLog Implementation@>=
  7421. void ZoomLog::switchLOD(MeasurementModel *m)
  7422. {
  7423. disconnect(currentModel, SIGNAL(rowChanged(int)), this, 0);
  7424. setModel(m);
  7425. currentModel = m;
  7426. connect(currentModel, SIGNAL(rowChanged(int)), this, SLOT(centerOn(int)));
  7427. }
  7428. void ZoomLog::LOD_ms()
  7429. {
  7430. switchLOD(model_ms);
  7431. }
  7432. void ZoomLog::LOD_1s()
  7433. {
  7434. switchLOD(model_1s);
  7435. }
  7436. void ZoomLog::LOD_5s()
  7437. {
  7438. switchLOD(model_5s);
  7439. }
  7440. void ZoomLog::LOD_10s()
  7441. {
  7442. switchLOD(model_10s);
  7443. }
  7444. void ZoomLog::LOD_15s()
  7445. {
  7446. switchLOD(model_15s);
  7447. }
  7448. void ZoomLog::LOD_30s()
  7449. {
  7450. switchLOD(model_30s);
  7451. }
  7452. void ZoomLog::LOD_1m()
  7453. {
  7454. switchLOD(model_1m);
  7455. }
  7456. @ It can be useful to display temperature measurements in various units. To do
  7457. so, we simply tell all of the models which unit to provide data in. It is also
  7458. possible to obtain the currently selected unit.
  7459. @<ZoomLog Implementation@>=
  7460. void ZoomLog::setDisplayUnits(int scale)
  7461. {
  7462. model_ms->setDisplayUnits(scale);
  7463. model_1s->setDisplayUnits(scale);
  7464. model_5s->setDisplayUnits(scale);
  7465. model_10s->setDisplayUnits(scale);
  7466. model_15s->setDisplayUnits(scale);
  7467. model_30s->setDisplayUnits(scale);
  7468. model_1m->setDisplayUnits(scale);
  7469. }
  7470. int ZoomLog::displayUnits()
  7471. {
  7472. return model_ms->displayUnits();
  7473. }
  7474. @ For convenience, a method is provided for returning a string containing the
  7475. time of the last inserted measurement in a given data series.
  7476. @<ZoomLog Implementation@>=
  7477. QString ZoomLog::lastTime(int series)
  7478. {
  7479. Measurement measure = lastMeasurement.value(series);
  7480. QTime time = measure.time();
  7481. return time.toString("h:mm:ss.zzz");
  7482. }
  7483. @ This just leaves the initial table setup.
  7484. @<ZoomLog Implementation@>=
  7485. ZoomLog::ZoomLog() : QTableView(NULL), model_ms(new MeasurementModel(this)),
  7486. model_1s(new MeasurementModel(this)),@/ model_5s(new MeasurementModel(this)),
  7487. model_10s(new MeasurementModel(this)),@/ model_15s(new MeasurementModel(this)),
  7488. model_30s(new MeasurementModel(this)),@/ model_1m(new MeasurementModel(this))@/
  7489. {@/
  7490. setEditTriggers(QAbstractItemView::NoEditTriggers);
  7491. setSelectionMode(QAbstractItemView::NoSelection);
  7492. modelSet << model_ms << model_1s << model_5s << model_10s << model_15s <<
  7493. model_30s << model_1m;
  7494. currentModel = model_30s;
  7495. setModel(currentModel);
  7496. connect(currentModel, SIGNAL(rowChanged(int)), this, SLOT(centerOn(int)));
  7497. connect(horizontalHeader(), SIGNAL(sectionResized(int, int, int)),
  7498. this, SLOT(persistColumnResize(int, int, int)));
  7499. connect(horizontalHeader(), SIGNAL(sectionCountChanged(int, int)),
  7500. this, SLOT(restoreColumnWidths()));
  7501. }
  7502. @ A new method was added to this class for version 1.0.7. This allows header
  7503. data to be set on the log and have it propagate to the model set. The longer
  7504. term plan involves removing the hard coding of some of the header data.
  7505. @<ZoomLog Implementation@>=
  7506. void ZoomLog::setHeaderData(int section, QString text)
  7507. {
  7508. MeasurementModel *m;
  7509. foreach(m, modelSet)
  7510. {
  7511. m->setHeaderData(section, Qt::Horizontal, QVariant(text));
  7512. }
  7513. }
  7514. @ As of version 1.2.3, these methods replace similar methods added for version
  7515. 1.0.8. The main difference is that it is now possible to save multiple data
  7516. series to the same output document.
  7517. @<ZoomLog Implementation@>=
  7518. void ZoomLog::addOutputTemperatureColumn(int column)
  7519. {
  7520. saveTempCols.append(column);
  7521. }
  7522. void ZoomLog::addOutputAnnotationColumn(int column)
  7523. {
  7524. saveNoteCols.append(column);
  7525. }
  7526. void ZoomLog::clearOutputColumns()
  7527. {
  7528. saveTempCols.clear();
  7529. saveNoteCols.clear();
  7530. }
  7531. @ Starting in version 1.4 two methods have been introduced which are used to
  7532. save and restore column widths.
  7533. @<ZoomLog Implementation@>=
  7534. void ZoomLog::persistColumnResize(int column, int, int newsize)
  7535. {
  7536. @<Save updated column size@>@;
  7537. }
  7538. void ZoomLog::restoreColumnWidths()
  7539. {
  7540. @<Restore table column widths@>@;
  7541. }
  7542. void ZoomLog::setVisible(bool visibility)
  7543. {
  7544. QTableView::setVisible(visibility);
  7545. }
  7546. void ZoomLog::showEvent(QShowEvent *)
  7547. {
  7548. @<Restore table column widths@>@;
  7549. }
  7550. @ The |ZoomLog| class is one of the more complicated classes to expose to the
  7551. scripting engine. In addition to a script constructor, we also need functions
  7552. for saving and restoring the state of the display and functions for saving data
  7553. from the log in the supported formats.
  7554. @<Function prototypes for scripting@>=
  7555. void setZoomLogProperties(QScriptValue value, QScriptEngine *engine);
  7556. QScriptValue constructZoomLog(QScriptContext *context, QScriptEngine *engine);
  7557. QScriptValue ZoomLog_saveXML(QScriptContext *context, QScriptEngine *engine);
  7558. QScriptValue ZoomLog_saveCSV(QScriptContext *context, QScriptEngine *engine);
  7559. QScriptValue ZoomLog_saveState(QScriptContext *context, QScriptEngine *engine);
  7560. QScriptValue ZoomLog_restoreState(QScriptContext *context,
  7561. QScriptEngine *engine);
  7562. QScriptValue ZoomLog_lastTime(QScriptContext *context, QScriptEngine *engine);
  7563. QScriptValue ZoomLog_saveTemporary(QScriptContext *context,
  7564. QScriptEngine *engnie);
  7565. @ Of these, the global object only needs to know about the constructor.
  7566. @<Set up the scripting engine@>=
  7567. constructor = engine->newFunction(constructZoomLog);
  7568. value = engine->newQMetaObject(&ZoomLog::staticMetaObject, constructor);
  7569. engine->globalObject().setProperty("ZoomLog", value);
  7570. @ The script constructor sets properties on the newly created object to allow
  7571. the other functions to be called.
  7572. @<Functions for scripting@>=
  7573. QScriptValue constructZoomLog(QScriptContext *, QScriptEngine *engine)@/
  7574. {@/
  7575. QScriptValue object = engine->newQObject(new ZoomLog);
  7576. setZoomLogProperties(object, engine);
  7577. return object;@/
  7578. }
  7579. void setZoomLogProperties(QScriptValue value, QScriptEngine *engine)
  7580. {
  7581. setQTableViewProperties(value, engine);
  7582. value.setProperty("saveXML", engine->newFunction(ZoomLog_saveXML));
  7583. value.setProperty("saveCSV", engine->newFunction(ZoomLog_saveCSV));
  7584. value.setProperty("saveState", engine->newFunction(ZoomLog_saveState));
  7585. value.setProperty("restoreState",
  7586. engine->newFunction(ZoomLog_restoreState));
  7587. value.setProperty("lastTime", engine->newFunction(ZoomLog_lastTime));
  7588. value.setProperty("saveTemporary",
  7589. engine->newFunction(ZoomLog_saveTemporary));
  7590. }
  7591. @ The functions for saving data are simple wrappers around the corresponding
  7592. calls in |ZoomLog|, except for a function added for saving data to a temporary
  7593. file. The last provides the name of the file saved for use in copying that data
  7594. to a database entry.
  7595. @<Functions for scripting@>=
  7596. QScriptValue ZoomLog_saveXML(QScriptContext *context, QScriptEngine *engine)
  7597. {
  7598. ZoomLog *self = getself<ZoomLog *>(context);
  7599. bool retval = self->saveXML(argument<QIODevice *>(0, context));
  7600. return QScriptValue(engine, retval);
  7601. }
  7602. QScriptValue ZoomLog_saveCSV(QScriptContext *context, QScriptEngine *engine)
  7603. {
  7604. ZoomLog *self = getself<ZoomLog *>(context);
  7605. bool retval = self->saveCSV(argument<QIODevice *>(0, context));
  7606. return QScriptValue(engine, retval);
  7607. }
  7608. QScriptValue ZoomLog_saveTemporary(QScriptContext *context,
  7609. QScriptEngine *engine)
  7610. {
  7611. ZoomLog *self = getself<ZoomLog *>(context);
  7612. QString filename = QDir::tempPath();
  7613. filename.append("/");
  7614. filename.append(QUuid::createUuid().toString());
  7615. filename.append(".xml");
  7616. QFile *file = new QFile(filename);
  7617. self->saveXML(file);
  7618. file->close();
  7619. delete file;
  7620. return QScriptValue(engine, filename);
  7621. }
  7622. @ The remaining functions are convenience functions for use with the scripting
  7623. engine. One will save the column widths to a |QSettings| object. Another will
  7624. restore the column widths from settings. Finally, there is a function for
  7625. obtaining a string representation of the most recent measurement from a data
  7626. series.
  7627. \danger There are a couple of problems with these functions. First, the body of
  7628. these functions would probably be better off as methods in the |ZoomLog| class
  7629. proper, either as slots or |Q_INVOKABLE| so the special scripting functions
  7630. could be eliminated. Second, rather than polluting the settings with separate
  7631. entries for each column, it would probably be better to store all of these
  7632. values in an array.\endanger
  7633. |ZoomLog_saveState()| was changed in version 1.2.3 to not save a new value for
  7634. the column width if that width is |0|. This was done mainly to ease debugging.
  7635. Similarly, |ZoomLog_restoreState()| picks a new default value when |0| is
  7636. encountered.
  7637. @<Functions for scripting@>=
  7638. QScriptValue ZoomLog_saveState(QScriptContext *context, QScriptEngine *)
  7639. {
  7640. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  7641. QString key = argument<QString>(0, context);
  7642. int columns = argument<int>(1, context);
  7643. QSettings settings;
  7644. for(int i = 0; i < columns; i++)
  7645. {
  7646. if(self->columnWidth(i))
  7647. {
  7648. settings.beginGroup(key);
  7649. settings.setValue(QString("%1").arg(i), self->columnWidth(i));
  7650. settings.endGroup();
  7651. }
  7652. }
  7653. return QScriptValue();
  7654. }
  7655. QScriptValue ZoomLog_restoreState(QScriptContext *context, QScriptEngine *)
  7656. {
  7657. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  7658. QString key = argument<QString>(0, context);
  7659. int columns = argument<int>(1, context);
  7660. QSettings settings;
  7661. for(int i = 0; i < columns; i++)
  7662. {
  7663. settings.beginGroup(key);
  7664. self->setColumnWidth(i,
  7665. settings.value(QString("%1").arg(i), 80).toInt());
  7666. if(settings.value(QString("%1").arg(i), 80).toInt() == 0)
  7667. {
  7668. self->setColumnWidth(i, 80);
  7669. }
  7670. settings.endGroup();
  7671. }
  7672. return QScriptValue();
  7673. }
  7674. QScriptValue ZoomLog_lastTime(QScriptContext *context, QScriptEngine *engine)
  7675. {
  7676. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  7677. return QScriptValue(engine, self->lastTime(argument<int>(0, context)));
  7678. }
  7679. @* A model for roasting data.
  7680. \noindent Qt provides a tool called the model view architecture. This provides a
  7681. uniform interface allowing different types of model classes to work with
  7682. different types of view classes without either needing to know implementation
  7683. details of the other. \pn{} provides the |MeasurementModel| as a specialization
  7684. of |QAbstractItemModel| for use in this architecture.
  7685. @<Class declarations@>=
  7686. class MeasurementList;@/
  7687. class MeasurementModel : public QAbstractItemModel@/
  7688. {@t\1@>@/
  7689. Q_OBJECT@;
  7690. Q_ENUMS(DisplayUnits);
  7691. int unit;
  7692. QList<MeasurementList *> *entries;
  7693. QStringList *hData;
  7694. int colcount;
  7695. QHash<int, int> *lastTemperature;
  7696. QList<MeasurementList *>::iterator@, lastInsertion;
  7697. public:@/
  7698. enum DisplayUnits
  7699. {
  7700. Auto = -1,
  7701. Fahrenheit = 10144,
  7702. Celsius = 10143,
  7703. Kelvin = 10325,
  7704. Rankine = 10145
  7705. };
  7706. MeasurementModel(QObject *parent = NULL);
  7707. ~MeasurementModel();
  7708. int rowCount(const QModelIndex &parent = QModelIndex()) const;
  7709. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  7710. bool setHeaderData(int section, Qt::Orientation orientation,
  7711. const QVariant &value,@|int role = Qt::DisplayRole);
  7712. QVariant data(const QModelIndex &index, int role) const;
  7713. bool setData(const QModelIndex &index, const QVariant &value,
  7714. int role = Qt::EditRole);
  7715. Qt::ItemFlags flags(const QModelIndex &index) const;
  7716. QVariant headerData(int section, Qt::Orientation orientation,
  7717. int role = Qt::DisplayRole) const;
  7718. QModelIndex index(int row, int column,
  7719. const QModelIndex &parent = QModelIndex()) const;
  7720. QModelIndex parent(const QModelIndex &index) const;
  7721. int displayUnits();@/
  7722. @t\4@>public slots@t\kern-3pt@>:@/
  7723. void newMeasurement(Measurement measure, int tempcolumn);
  7724. void newAnnotation(QString annotation, int tempcolumn,
  7725. int annotationColumn);
  7726. void clear();
  7727. void setDisplayUnits(int scale);
  7728. signals:@/
  7729. void rowChanged(int);@t\2@>@/
  7730. }@t\kern-3pt@>;
  7731. @ The measurement model stores its data in a list of measurement lists. This
  7732. allows the model to store as many sets of data as needed. In order to keep
  7733. measurements in the model sorted by time, the measurement list adds two
  7734. comparison functions.
  7735. @<Class declarations@>=
  7736. class MeasurementList : public QVariantList@/
  7737. {@t\1@>@/
  7738. @t\4@>public:@/
  7739. bool operator<(const MeasurementList &other) const;
  7740. bool operator==(const MeasurementList &other) const;@t\2@>@/
  7741. }@t\kern-3pt@>;
  7742. @ The overload of |<| checks if the time in one list (always stored in the first
  7743. column) is less than the time stored in the second. The overload of |==| is used
  7744. in an optimization that allows us to skip the search procedure on model
  7745. insertion.
  7746. @<MeasurementModel Implementation@>=
  7747. bool MeasurementList::operator<(const MeasurementList &other) const
  7748. {
  7749. return this->first().toTime() < other.first().toTime();
  7750. }
  7751. bool MeasurementList::operator==(const MeasurementList &other) const
  7752. {
  7753. return this->first().toTime() == other.first().toTime();
  7754. }
  7755. @ The |MeasurementModel| class extends the |QAbstractItemModel| class to work
  7756. better with measurements and annotations that are passed around in \pn{}. Many
  7757. of the class methods are required because of that choice. For example, the
  7758. parent function which is never used directly:
  7759. @<MeasurementModel Implementation@>=
  7760. QModelIndex MeasurementModel::parent(const QModelIndex&) const
  7761. {
  7762. return QModelIndex();
  7763. }
  7764. @ Perhaps the most complicated part of this class is the code for dealing with a
  7765. new measurement. This is complicated by the requirement to insert measurements
  7766. while keeping the model sorted by time.
  7767. @<MeasurementModel Implementation@>=
  7768. void MeasurementModel::newMeasurement(Measurement measure, int tempcolumn)
  7769. {
  7770. MeasurementList *temp;
  7771. temp = new MeasurementList;
  7772. temp->append(QVariant(measure.time()));
  7773. @<Find the insertion point@>@;
  7774. MeasurementList *newEntry;
  7775. int insertion;
  7776. if(i != entries->end())
  7777. {
  7778. insertion = entries->indexOf(*i);
  7779. if((*i)->first().toTime() == measure.time())
  7780. {
  7781. @<Insert a new measurement at an existing time@>@;
  7782. }
  7783. else
  7784. {
  7785. @<Insert a new measurement somewhere else@>@;
  7786. }
  7787. }
  7788. else
  7789. {
  7790. @<Append a measurement@>@;
  7791. }
  7792. if(tempcolumn >= colcount)
  7793. {
  7794. colcount = tempcolumn + 1;
  7795. }
  7796. emit rowChanged(insertion);
  7797. delete temp;
  7798. }
  7799. @ To find the insertion point for new measurements we use a binary search of the
  7800. existing data. The code below is a direct adaptation of Program B\nfnote{%
  7801. \underbar{The Art of Computer Programming} Volume 3 Sorting and Searching 2nd
  7802. ed. (Knuth, 1997) Section 6.2.1: Searching an Ordered Table} modified to use
  7803. list iterators and control structures more familiar to \CPLUSPLUS/programmers
  7804. rather than {\mc MIX} machine codes. When the loop exits |i| is the insertion
  7805. point.
  7806. \medskip
  7807. \centerline{\includegraphics{search}}
  7808. \smallskip
  7809. \centerline{Figure \secno: Binary Search}
  7810. \medskip
  7811. @<Find the insertion point@>=
  7812. @<Scan from most recent insertion@>@;
  7813. if(quickscan == false)
  7814. {
  7815. i = entries->begin();
  7816. QList<MeasurementList *>::iterator@, u = entries->end();
  7817. QList<MeasurementList *>::iterator@, midpoint;
  7818. int n = u - i;
  7819. int rA;
  7820. while(n > 0)@/
  7821. {
  7822. rA = n>>1; /* |rA = |~$\bigl\lfloor{n\over2}\bigr\rfloor$ */
  7823. midpoint = i + rA;
  7824. if(**midpoint < *temp)@/
  7825. {
  7826. i = midpoint + 1;
  7827. n -= rA + 1;
  7828. }
  7829. else@/
  7830. {
  7831. n = rA;
  7832. }
  7833. }
  7834. }
  7835. @ The binary search, while correct, is not a particularly optimal choice for
  7836. this application. While the average running time for this is on the order of
  7837. $\ln N$ when each insertion point is equally likely, the reality of this
  7838. application is that insertions will likely be at the beginning of the list, at
  7839. the point of the most recent insertion, or a short distance from the most recent
  7840. insertion. By first considering the possibility that the measurement should be
  7841. inserted at or near the most recent measurement, shorter, more constant running
  7842. times as $N$ increases can be obtained.
  7843. To do this, when the number of measurements in the list is above a small number
  7844. which must be greater than 1, we check first if the insertion point is at the
  7845. last insertion (the |<| comparison fails and we do an |==| comparison before
  7846. giving up), then we check a small number of rows for either the end of the list,
  7847. in which case the insertion point is at the end, or for a point at which the |<|
  7848. comparison fails. If neither condition holds for a small number of comparisons
  7849. we resort to the binary search.
  7850. Performance measurements with this modification compared with previous versions
  7851. shows that this provides a huge performance boost.
  7852. @<Scan from most recent insertion@>=
  7853. @[QList<MeasurementList *>::iterator@, i@] = lastInsertion;@/
  7854. bool quickscan = false;@/
  7855. if(entries->size() > 5)@/
  7856. {@t\1@>@/
  7857. if(**i < *temp)@/
  7858. {@t\1@>@/
  7859. i += 1;@/
  7860. for(int j = 10; j > 0; j--)@/
  7861. {@t\1@>@/
  7862. if(i != entries->end())@/
  7863. {@t\1@>@/
  7864. if(**i < *temp)@/
  7865. {
  7866. i += 1;
  7867. }@/
  7868. else@/
  7869. {@t\1@>@/
  7870. quickscan = true;
  7871. break;@t\2@>@/
  7872. }@t\2@>@/
  7873. }@/
  7874. else@/
  7875. {@t\1@>@/
  7876. quickscan = true;
  7877. break;@t\2@>@/
  7878. }@t\2@>@/
  7879. }@t\2@>@/
  7880. }@/
  7881. else@/
  7882. {@t\1@>@/
  7883. if(**i == *temp)@/
  7884. {@t\1@>@/
  7885. quickscan = true;@t\2@>@/
  7886. }@t\2@>@/
  7887. }@t\2@>@/
  7888. }
  7889. @ If the chosen insertion point is at an existing time, we don't need to worry
  7890. about inserting rows. There may be a need to increase the size of the
  7891. measurement list to accept an entry in a new data series.
  7892. @<Insert a new measurement at an existing time@>=
  7893. if((*i)->size() < tempcolumn + 1)
  7894. {
  7895. for(int j = (*i)->size() - 1; j < tempcolumn + 1; j++)
  7896. {
  7897. (*i)->append(QVariant());
  7898. }
  7899. }
  7900. (*i)->replace(tempcolumn, measure.temperature());
  7901. lastInsertion = i;
  7902. emit dataChanged(createIndex(insertion, tempcolumn),
  7903. createIndex(insertion, tempcolumn));
  7904. lastTemperature->insert(tempcolumn, insertion);
  7905. @ If the measurement is not past the end of the existing data and the insertion
  7906. point has a different time, we need to use |beginInsertRows()| and
  7907. |endInsertRows()| to notify any attached view that a new row will be added.
  7908. @<Insert a new measurement somewhere else@>=
  7909. beginInsertRows(QModelIndex(), insertion, insertion);
  7910. newEntry = new MeasurementList;
  7911. newEntry->append(QVariant(measure.time()));
  7912. for(int j = 0; j < tempcolumn + 1; j++)
  7913. {
  7914. newEntry->append(QVariant());
  7915. }
  7916. newEntry->replace(tempcolumn, measure.temperature());
  7917. lastInsertion = entries->insert(i, newEntry);
  7918. endInsertRows();
  7919. lastTemperature->insert(tempcolumn, insertion);
  7920. @ If the insertion point is past the end of the existing data, a new row should
  7921. be appended to the data. This only needs to be a separate case to prevent the
  7922. comparison with a nonexistent entry. This is very similar to the case of
  7923. inserting at a new time anywhere else.
  7924. @<Append a measurement@>=
  7925. insertion = entries->size();@/
  7926. @<Insert a new measurement somewhere else@>
  7927. @ The other bit of code that's a little bit more complicated than other parts of
  7928. the class handles adding annotations to the data. Two signals are emitted in
  7929. this method. The |dataChanged| signal is expected by view classes that can use
  7930. this model. The |rowChanged| signal is used by |ZoomLog| to scroll the view to
  7931. the row the annotation has been added to. This is mainly useful when loading a
  7932. target profile and entering the first annotation prior to starting the batch.
  7933. @<MeasurementModel Implementation@>=
  7934. void MeasurementModel::newAnnotation(QString annotation, int tempcolumn,@|
  7935. int annotationColumn)
  7936. {
  7937. int r;
  7938. if(lastTemperature->contains(tempcolumn))
  7939. {
  7940. r = lastTemperature->value(tempcolumn);
  7941. }
  7942. else
  7943. {
  7944. r = 0;
  7945. }
  7946. if(r == 0 && entries->size() == 0)
  7947. {
  7948. @<Create the first row@>@;
  7949. }
  7950. MeasurementList *row = entries->at(r);
  7951. if(row->size() <= annotationColumn)
  7952. {
  7953. for(int i = row->size() - 1; i < annotationColumn + 1; i++)
  7954. {
  7955. row->append(QVariant());
  7956. }
  7957. }
  7958. row->replace(annotationColumn, annotation);
  7959. emit dataChanged(createIndex(r, annotationColumn),
  7960. createIndex(r, annotationColumn));
  7961. emit rowChanged(r);
  7962. if(annotationColumn > colcount - 1)
  7963. {
  7964. colcount = annotationColumn + 1;
  7965. }
  7966. }
  7967. @ There is no need to further complicate the function by adding the annotation
  7968. when the first row is created.
  7969. @<Create the first row@>=
  7970. beginInsertRows(QModelIndex(), 0, 0);
  7971. MeasurementList *newEntry = new MeasurementList;
  7972. newEntry->append(QVariant(QTime(0, 0, 0, 0)));
  7973. entries->append(newEntry);
  7974. endInsertRows();
  7975. @ Clearing the model data is a simple matter of deleting every row, remembering
  7976. to let any attached views know that we are doing this, and resetting the number
  7977. of columns.
  7978. @<MeasurementModel Implementation@>=
  7979. void MeasurementModel::clear()
  7980. {
  7981. beginRemoveRows(QModelIndex(), 0, entries->size());
  7982. while(entries->size() != 0)
  7983. {
  7984. MeasurementList *row = entries->takeFirst();
  7985. delete row;
  7986. }
  7987. endRemoveRows();
  7988. colcount = hData->size();
  7989. lastTemperature->clear();
  7990. reset();
  7991. }
  7992. @ While these methods for adding measurements and annotations are fine when
  7993. recording a stream of measurements, either from the |DAQ| or when loading saved
  7994. data, there are also cases where we'd like to edit the data in the model
  7995. directly from the table view. For this, we need to reimplement |setData()|.
  7996. Very little input checking is done here. Editable views may want to place
  7997. delegates\nfnote{Qt 4.4: Delegate Classes\par\indent\hbox{%
  7998. \pdfURL{http://doc.trolltech.com/4.4/model-view-delegate.html}{%
  7999. http://doc.trolltech.com/4.4/model-view-delegate.html}}} on the columns to make
  8000. editing the data easier and less error prone.
  8001. @<MeasurementModel Implementation@>=
  8002. bool MeasurementModel::setData(const QModelIndex &index,
  8003. const QVariant &value, int role)@t\2\2@>@/
  8004. {@t\1@>@/
  8005. if(role != Qt::EditRole && role != Qt::DisplayRole)@/
  8006. {@t\1@>@/
  8007. return false;@t\2@>@/
  8008. }@/
  8009. @<Check that the index is valid@>@;
  8010. if(!valid)@/
  8011. {@t\1@>@/
  8012. return false;@t\2@>@/
  8013. }@/
  8014. MeasurementList *row = entries->at(index.row());
  8015. if(index.column() >= row->size())
  8016. {
  8017. @<Expand the row to prepare for new data@>@;
  8018. }
  8019. if(index.column() == 0)
  8020. {
  8021. @<Edit data in the time column@>@;
  8022. }
  8023. else
  8024. {
  8025. @<Edit data in other columns@>@;
  8026. }
  8027. return true;@t\2@>@/
  8028. }
  8029. @ There is no sense in attempting to edit the data if there isn't any data
  8030. available to edit. This check is also used when retrieving data from the model.
  8031. @<Check that the index is valid@>=
  8032. bool valid = false;
  8033. if(index.isValid())@/
  8034. {@t\1@>@/
  8035. if(index.row() < entries->size())@/
  8036. {@t\1@>@/
  8037. if(index.column() < colcount)@/
  8038. {@t\1@>@/
  8039. valid = true;@t\2@>@/
  8040. }@t\2@>@/
  8041. }@t\2@>@/
  8042. }
  8043. @ When editing data, there might not be anything where we want to add the data.
  8044. For example, adding an annotation to an otherwise unannotated measurement. This
  8045. is fine, but we need to expand the row instead of inserting data out of bounds.
  8046. @<Expand the row to prepare for new data@>=
  8047. for(int i = row->size() - 1; i < index.column(); i++)
  8048. {
  8049. row->append(QVariant());
  8050. }
  8051. @ Changing time data must be considered separately from other data. As the model
  8052. keeps itself sorted based on the time field, allowing the user to get the model
  8053. data out of order would result in poorly defined behavior later. Our approach is
  8054. to remove the row from the model temporarily then reuse the code from
  8055. |newMeasurement()| to find the new insertion point. No attempt is made to merge
  8056. the contents from two rows with identical times, but an attempt is made to not
  8057. be too rigid in what we expect the user to enter. If an invalid time is entered,
  8058. we give up and leave the data as we found it.
  8059. @<Edit data in the time column@>=
  8060. QTime time;@/
  8061. if(!(time = QTime::fromString(value.toString(), "m:s.z")).isValid())@/
  8062. {@t\1@>@/
  8063. if(!(time = QTime::fromString(value.toString(), "m:s")).isValid())@/
  8064. {@t\1@>@/
  8065. return false;@t\2@>@/
  8066. }@t\2@>@/
  8067. }@/
  8068. row = entries->takeAt(index.row());
  8069. row->replace(index.column(), QVariant(time));
  8070. MeasurementList *temp = row;
  8071. @<Find the insertion point@>@;
  8072. entries->insert(i, row);
  8073. int newRow = entries->indexOf(*i);
  8074. if(newRow < index.row())@/
  8075. {
  8076. emit dataChanged(createIndex(newRow, index.column()), index);
  8077. }
  8078. else@/
  8079. {
  8080. emit dataChanged(index, createIndex(newRow, index.column()));
  8081. }
  8082. @ Data in other columns is a little easier to handle.
  8083. @<Edit data in other columns@>=
  8084. row->replace(index.column(), value);
  8085. emit dataChanged(index, index);
  8086. @ As it has already been established that the first column is always considered
  8087. the time of the measurement, this assumption can be built into the model
  8088. constructor.
  8089. @<MeasurementModel Implementation@>=
  8090. MeasurementModel::MeasurementModel(QObject *parent) : QAbstractItemModel(parent),
  8091. unit(Fahrenheit), hData(new QStringList),
  8092. lastTemperature(new QHash<int, int>)@/
  8093. {
  8094. colcount = 1;
  8095. entries = new QList<MeasurementList *>;
  8096. lastInsertion = entries->begin();
  8097. hData->append(tr("Time"));
  8098. }
  8099. @ In the destructor we need to remember to clean up after ourselves.
  8100. @<MeasurementModel Implementation@>=
  8101. MeasurementModel::~MeasurementModel()
  8102. {
  8103. clear();
  8104. delete entries;
  8105. delete hData;
  8106. }
  8107. @ A pair of functions are used to determine the number of rows and columns the
  8108. model provides. No entries in the model have children, so the parent should
  8109. always be the invisible root object. If it isn't, we should return 0.
  8110. @<MeasurementModel Implementation@>=
  8111. int MeasurementModel::rowCount(const QModelIndex &parent) const
  8112. {
  8113. if(parent == QModelIndex())
  8114. {
  8115. return entries->size();
  8116. }
  8117. return 0;
  8118. }
  8119. int MeasurementModel::columnCount(const QModelIndex &parent) const
  8120. {
  8121. if(parent == QModelIndex())
  8122. {
  8123. return colcount;
  8124. }
  8125. return 0;
  8126. }
  8127. @ The model maintains a set of header data. At present, it only supports header
  8128. data at the top of the model due to the author's preference to not have row
  8129. numbers littering the left of the table (the time column is sufficient to
  8130. identify the row for the user).
  8131. The model view architecture supports the concept of different data roles in the
  8132. header data. At present, this model ignores the role when setting header data.
  8133. @<MeasurementModel Implementation@>=
  8134. bool MeasurementModel::setHeaderData(int section, Qt::Orientation orientation,@|
  8135. const QVariant &value, int)@t\2@>@/
  8136. @t\4@>{@/
  8137. if(orientation == Qt::Horizontal)@/
  8138. {@t\1@>@/
  8139. if(hData->size() < section + 1)@/
  8140. {@/
  8141. for(int i = hData->size(); i < section + 1; i++)@/
  8142. {@/
  8143. if(colcount < i)@/
  8144. {@/
  8145. beginInsertColumns(QModelIndex(), i, i);
  8146. }
  8147. hData->append(QString());
  8148. if(colcount < i)@/
  8149. {@/
  8150. endInsertColumns();
  8151. }
  8152. }
  8153. }
  8154. hData->replace(section, value.toString());
  8155. emit headerDataChanged(orientation, section, section);
  8156. if(colcount < section + 1)@/
  8157. {@/
  8158. colcount = section + 1;
  8159. }@/
  8160. return true;@t\2@>@/
  8161. }@/
  8162. return false;@/
  8163. @t\4@>}
  8164. @ While the current implementation always receives measurements in degrees
  8165. Fahrenheit, international users often want to see data presented in Celsius. To
  8166. do this, a slot is provided to allow selecting among different units. When this
  8167. method is called, the model indicates that all attached views must update all
  8168. displayed data and requests for temperature data will have any needed conversion
  8169. performed before sending that information to the view. Another method is
  8170. available to request a number identifyin the currently displayed units.
  8171. @<MeasurementModel Implementation@>=
  8172. void MeasurementModel::setDisplayUnits(int scale)
  8173. {
  8174. beginResetModel();
  8175. unit = scale;
  8176. endResetModel();
  8177. }
  8178. int MeasurementModel::displayUnits()
  8179. {
  8180. return unit;
  8181. }
  8182. @ A model is generally quite useless if the data the model contains cannot be
  8183. retrieved. To do this, we check that the index requested is a valid index that
  8184. is within the bounds of the model data and that a role we understand has been
  8185. requested. If none of these conditions are met, a default constructed |QVariant|
  8186. is returned.
  8187. At present, |Qt::DisplayRole| and |Qt::EditRole| are supported. These return the
  8188. same thing. Views will request the display role for presenting the information
  8189. to the user, but they will request the edit role if the user attempts to modify
  8190. the data through a view.
  8191. @<MeasurementModel Implementation@>=
  8192. QVariant MeasurementModel::data(const QModelIndex &index, int role) const@/
  8193. {@/
  8194. @<Check that the index is valid@>@;
  8195. if(!valid)
  8196. {
  8197. return QVariant();
  8198. }
  8199. if(role == Qt::DisplayRole || role == Qt::EditRole)
  8200. {
  8201. MeasurementList *row = entries->at(index.row());
  8202. if(index.column() > row->size())
  8203. {
  8204. return QVariant();
  8205. }
  8206. else
  8207. {
  8208. if(index.column() == 0)
  8209. {
  8210. return QVariant(row->at(0).toTime().toString("mm:ss.zzz"));
  8211. }
  8212. else if(lastTemperature->contains(index.column()))
  8213. {
  8214. if(row->at(index.column()).toString().isEmpty())
  8215. {
  8216. return QVariant();
  8217. }
  8218. switch(unit)
  8219. {
  8220. case Auto:
  8221. case Fahrenheit:
  8222. return QVariant(row->at(index.column()).toString());
  8223. break;
  8224. case Celsius:
  8225. return QVariant((row->at(index.column()).toDouble() -
  8226. 32) * 5 / 9);
  8227. break;
  8228. case Kelvin:
  8229. return QVariant((row->at(index.column()).toDouble() +
  8230. 459.67) * 5 / 9);
  8231. break;
  8232. case Rankine:
  8233. return QVariant(row->at(index.column()).toDouble() +
  8234. 459.67);
  8235. break;
  8236. default:
  8237. break;
  8238. }
  8239. }
  8240. return QVariant(row->at(index.column()).toString());
  8241. }
  8242. }
  8243. return QVariant();@/
  8244. }
  8245. @ Views also must be able to retrieve the header data.
  8246. @<MeasurementModel Implementation@>=
  8247. QVariant MeasurementModel::headerData(int section, Qt::Orientation orientation,
  8248. int role ) const
  8249. {
  8250. if(orientation == Qt::Horizontal)
  8251. {
  8252. if(role == Qt::DisplayRole)
  8253. {
  8254. if(section < hData->size())
  8255. {
  8256. return QVariant(hData->at(section));
  8257. }
  8258. }
  8259. }
  8260. return QVariant();
  8261. }
  8262. @ Views will sometimes request information about the interactions available for
  8263. an index. In the case of this model, each index is treated in the same way.
  8264. It may be a good idea to extend the model class to allow models that can be
  8265. edited through the view such as the table view presented in the |LogEditWindow|
  8266. and models that probably shouldn't be edited in the view, such as the models
  8267. managed by |ZoomLog|. This could be done by subclassing and only reimplementing
  8268. this method. Otherwise, a new method to specify that the user should not edit
  8269. the model could be provided and a flag would be checked here.
  8270. @<MeasurementModel Implementation@>=
  8271. Qt::ItemFlags MeasurementModel::flags(const QModelIndex &index) const@/
  8272. {@/
  8273. @<Check that the index is valid@>@;
  8274. if(valid)
  8275. {
  8276. return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable;
  8277. }
  8278. return 0;
  8279. }
  8280. @ Much of the way models are interacted with in Qt's model view architecture is
  8281. through model indices. The model is responsible for creating these indices from
  8282. row column pairs.
  8283. @<MeasurementModel Implementation@>=
  8284. QModelIndex MeasurementModel::index(int row, int column,
  8285. const QModelIndex &parent) const@t\2\2@>@/
  8286. {@t\1@>@/
  8287. if(parent == QModelIndex())@/
  8288. {@t\1@>@/
  8289. if(row < entries->size() && entries->isEmpty() == false)@/
  8290. {@/
  8291. if(column < entries->at(row)->size())@/
  8292. {@/
  8293. return createIndex(row, column);@/
  8294. }@/
  8295. }@t\2@>@/
  8296. }@/
  8297. return QModelIndex();@/
  8298. @t\4@>}
  8299. @** Annotating roast data.
  8300. \noindent In addition to recording time temperature pairs, \pn{} allows the user
  8301. to annotate the roasting log to indicate control changes, the end of the batch,
  8302. or samples collected from the roast. It is important that these annotations can
  8303. be applied to the roasting log quickly. This is the purpose of the
  8304. |AnnotationButton| class.
  8305. @<Class declarations@>=
  8306. class AnnotationButton : public QPushButton@/
  8307. {@t\1@>@/
  8308. Q_OBJECT@;
  8309. QString note;
  8310. int tc;
  8311. int ac;
  8312. int count;
  8313. public:@/
  8314. AnnotationButton(const QString &text, QWidget *parent = NULL);@/
  8315. @t\4@>public slots@t\kern-3pt@>:@/
  8316. void setAnnotation(const QString &annotation);
  8317. void setTemperatureColumn(int tempcolumn);
  8318. void setAnnotationColumn(int annotationcolumn);
  8319. void annotate();
  8320. void resetCount();
  8321. signals:@/
  8322. void annotation(QString annotation, int tempcolumn,
  8323. int notecolumn);@t\2@>@/
  8324. }@t\kern-3pt@>;
  8325. @ Setting up a new annotation button begins with the constructor. This takes a
  8326. string specifying the text that will appear on the button and optionally a
  8327. parent widget. This is also a sensible place to set up the desired behavior the
  8328. button should exhibit when clicked.
  8329. @<AnnotationButton Implementation@>=
  8330. AnnotationButton::AnnotationButton(const QString &text, QWidget *parent) :
  8331. QPushButton(text, parent), note(""), tc(0), ac(0), count(0)@/
  8332. {
  8333. connect(this, SIGNAL(clicked()), this, SLOT(annotate()));
  8334. }
  8335. @ The slot that is called when the button is clicked needs to be able to handle
  8336. two types of annotations. Simple annotations send the same annotation every time
  8337. the button is clicked. Counting annotations are annotation strings that have a
  8338. |"%1"| somewhere in the string. That substring will be replaced with an integer
  8339. that is incremented before the annotation is sent. This integer is initialized
  8340. to 0. It will be incremented to 1 the first time the button is clicked and that
  8341. will be the replacement value.
  8342. @<AnnotationButton Implementation@>=
  8343. void AnnotationButton::annotate()
  8344. {
  8345. if(note.contains("%1"))
  8346. {
  8347. count++;
  8348. emit annotation(note.arg(count), tc, ac);
  8349. }
  8350. else
  8351. {
  8352. emit annotation(note, tc, ac);
  8353. }
  8354. }
  8355. @ A few methods are available to indicate which temperature series the
  8356. annotation should be applied to, which column in a table view the annotation
  8357. should be entered in, and what text should be in the annotation.
  8358. @<AnnotationButton Implementation@>=
  8359. void AnnotationButton::setTemperatureColumn(int tempcolumn)
  8360. {
  8361. tc = tempcolumn;
  8362. }
  8363. void AnnotationButton::setAnnotationColumn(int annotationcolumn)
  8364. {
  8365. ac = annotationcolumn;
  8366. }
  8367. void AnnotationButton::setAnnotation(const QString &annotation)
  8368. {
  8369. note = annotation;
  8370. }
  8371. @ Finally, in the case of counting annotations, there should be a way to reset
  8372. the number used in the annotation.
  8373. @<AnnotationButton Implementation@>=
  8374. void AnnotationButton::resetCount()
  8375. {
  8376. count = 0;
  8377. }
  8378. @ A script constructor is needed to allow an |AnnotationButton| to be created
  8379. from a script.
  8380. @<Function prototypes for scripting@>=
  8381. QScriptValue constructAnnotationButton(QScriptContext *context,
  8382. QScriptEngine *engine);
  8383. void setAnnotationButtonProperties(QScriptValue value, QScriptEngine *engine);
  8384. @ In order to use this, the engine needs to be informed of the function.
  8385. @<Set up the scripting engine@>=
  8386. constructor = engine->newFunction(constructAnnotationButton);
  8387. value = engine->newQMetaObject(&AnnotationButton::staticMetaObject,
  8388. constructor);
  8389. engine->globalObject().setProperty("AnnotationButton", value);
  8390. @ The implementation is trivial.
  8391. @<Functions for scripting@>=
  8392. QScriptValue constructAnnotationButton(QScriptContext *context,
  8393. QScriptEngine *engine)
  8394. {
  8395. QScriptValue object =
  8396. engine->newQObject(new AnnotationButton(argument<QString>(0, context)));
  8397. setAnnotationButtonProperties(object, engine);
  8398. return object;
  8399. }
  8400. void setAnnotationButtonProperties(QScriptValue value, QScriptEngine *engine)
  8401. {
  8402. setQPushButtonProperties(value, engine);
  8403. }
  8404. @* A spin box for annotations.
  8405. \noindent While the annotation button is adequate for most log annotation tasks,
  8406. there are some times where the log should contain a small number of numerical
  8407. observations where it is inconvenient or cost prohibitive to enable automated
  8408. logging. For these tasks, a spin box that produces an appropriate annotation may
  8409. be useful.
  8410. @<Class declarations@>=
  8411. class AnnotationSpinBox : public QDoubleSpinBox@/
  8412. {@t\1@>@/
  8413. Q_OBJECT@;
  8414. QString pretext;
  8415. QString posttext;
  8416. int tc;
  8417. int ac;
  8418. bool change;
  8419. public:
  8420. AnnotationSpinBox(const QString &pret, const QString &postt,
  8421. QWidget *parent = NULL);@/
  8422. @t\4@>public slots@t\kern-3pt@>:@/
  8423. void setPretext(const QString &pret);
  8424. void setPosttext(const QString &postt);
  8425. void setTemperatureColumn(int tempcolumn);
  8426. void setAnnotationColumn(int annotationcolumn);
  8427. void annotate();
  8428. void resetChange();
  8429. signals:@/
  8430. void annotation(QString annotation, int tempcolumn,
  8431. int notecolumn);@t\2@>@/
  8432. }@t\kern-3pt@>;
  8433. @ Setting up a new annotation spin box begins with the constructor. This takes
  8434. two strings specifying optional text that may appear before or after the
  8435. numerical value of the spin box in the annotation. No spaces are placed between
  8436. the text and the numerical values, so if such spacing is required, it must be
  8437. included in the relevant string.
  8438. This function also sets up the behavior for firing annotation events. An
  8439. annotation should be fired when the user presses enter while the spin box has
  8440. focus. This implementation will also attempt to fire an annotation when the
  8441. spin box loses focus. No annotation is fired if the value of the spin box has
  8442. not been changed since the previous annotation event.
  8443. @<AnnotationSpinBox Implementation@>=
  8444. AnnotationSpinBox::AnnotationSpinBox(const QString &pret,
  8445. const QString &postt,@|
  8446. QWidget *parent)
  8447. : QDoubleSpinBox(parent), pretext(pret), posttext(postt)@/
  8448. {
  8449. resetChange();
  8450. connect(this, SIGNAL(editingFinished()), this, SLOT(annotate()));
  8451. connect(this, SIGNAL(valueChanged(double)), this, SLOT(resetChange()));
  8452. }
  8453. @ The |resetChange()| signal just sets a boolean which is checked prior to
  8454. sending an annotation. This is called automatically when the value of the spin
  8455. box is changed, but it should also be called when a batch is finished in case
  8456. the first required annotation is the same as the last required annotation from
  8457. the previous batch.
  8458. @<AnnotationSpinBox Implementation@>=
  8459. void AnnotationSpinBox::resetChange()@t\2\2@>@/
  8460. {@t\1@>@/
  8461. change = true;@t\2@>@/
  8462. }
  8463. @ The annotation slot is responsible for determining if an annotation should be
  8464. sent. The current implementation is to only attempt to send such a signal when
  8465. the |editingFinished()| signal is emitted, however this could also be connected
  8466. to other signals.
  8467. @<AnnotationSpinBox Implementation@>=
  8468. void AnnotationSpinBox::annotate()@t\2\2@>@/
  8469. {@t\1@>@/
  8470. if(change)@/
  8471. {@t\1@>@/
  8472. change = false;@/
  8473. emit annotation(QString("%1%2%3").arg(pretext).
  8474. arg(value()).arg(posttext), tc, ac);@t\2@>@/
  8475. }@t\2@>@/
  8476. }
  8477. @ These methods set various properties of the annotation.
  8478. @<AnnotationSpinBox Implementation@>=
  8479. void AnnotationSpinBox::setTemperatureColumn(int tempcolumn)
  8480. {
  8481. tc = tempcolumn;
  8482. }
  8483. void AnnotationSpinBox::setAnnotationColumn(int annotationcolumn)
  8484. {
  8485. ac = annotationcolumn;
  8486. }
  8487. void AnnotationSpinBox::setPretext(const QString &pret)
  8488. {
  8489. pretext = pret;
  8490. }
  8491. void AnnotationSpinBox::setPosttext(const QString &postt)
  8492. {
  8493. posttext = postt;
  8494. }
  8495. @ Two functions are needed to interface |AnnotationSpinBox| with the host
  8496. environment. Additional functions are required for setting up inheritance
  8497. properly.
  8498. @<Function prototypes for scripting@>=
  8499. QScriptValue constructAnnotationSpinBox(QScriptContext *context,
  8500. QScriptEngine *engine);
  8501. void setAnnotationSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  8502. void setQDoubleSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  8503. void setQAbstractSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  8504. @ The first of these is passed into the host environment.
  8505. @<Set up the scripting engine@>=
  8506. constructor = engine->newFunction(constructAnnotationSpinBox);
  8507. value = engine->newQMetaObject(&AnnotationSpinBox::staticMetaObject,
  8508. constructor);
  8509. engine->globalObject().setProperty("AnnotationSpinBox", value);
  8510. @ The script constructor creates a new object and passes it to a function that
  8511. is responsible for setting up properties in the inheritance chain.
  8512. @<Functions for scripting@>=
  8513. QScriptValue constructAnnotationSpinBox(QScriptContext *context,
  8514. QScriptEngine *engine)
  8515. {
  8516. QScriptValue object = engine->newQObject(new AnnotationSpinBox(
  8517. argument<QString>(0, context), argument<QString>(1, context)));
  8518. setAnnotationSpinBoxProperties(object, engine);
  8519. return object;
  8520. }
  8521. void setAnnotationSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  8522. {
  8523. setQDoubleSpinBoxProperties(value, engine);
  8524. }
  8525. void setQDoubleSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  8526. {
  8527. setQAbstractSpinBoxProperties(value, engine);
  8528. }
  8529. void setQAbstractSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  8530. {
  8531. setQWidgetProperties(value, engine);
  8532. }
  8533. @** A digital timer.
  8534. \noindent Before \pn{} was a data logger, it was a simple digital timer written
  8535. because there were no shops in Racine that could sell a simple dual digital
  8536. count up timer at a time when my first timer was malfunctioning. After
  8537. attempting to purchase a replacement device at several stores that have sold
  8538. such devices in the past, I decided to spend a couple hours writing my own
  8539. timer.
  8540. For historical reasons, the |TimerDisplay| class is considerably more functional
  8541. than \pn{} requires. Those needing only a digital timer can extract the code for
  8542. this class and use it in a timer application. This should work on any platform
  8543. supported by Qt.
  8544. @<Class declarations@>=
  8545. class TimerDisplay : public QLCDNumber@/
  8546. {@t\1@>@/
  8547. Q_OBJECT@/
  8548. @<TimerDisplay Properties@>@;
  8549. @t\4@>private slots@t\kern-3pt@>:@/
  8550. void updateTime();
  8551. void setCountUpMode();
  8552. void setCountDownMode();
  8553. void setClockMode();
  8554. public:@/
  8555. TimerDisplay(QWidget *parent = NULL);
  8556. ~TimerDisplay();
  8557. enum TimerMode
  8558. {
  8559. CountUp,
  8560. CountDown,
  8561. Clock
  8562. };
  8563. QString value();
  8564. QTime seconds();
  8565. TimerMode mode();
  8566. bool isRunning();
  8567. QTime resetValue();
  8568. QString displayFormat();
  8569. bool autoReset();@/
  8570. @t\4@>public slots@t\kern-3pt@>:@/
  8571. void setTimer(QTime value = QTime(0, 0, 0));
  8572. void setMode(TimerMode mode);
  8573. void startTimer();
  8574. void stopTimer();
  8575. void copyTimer();
  8576. void setResetValue(QTime value = QTime(0, 0, 0));
  8577. void reset();
  8578. void setDisplayFormat(QString format);
  8579. void setAutoReset(bool reset);
  8580. void updateDisplay();
  8581. signals:@/
  8582. void valueChanged(QTime);
  8583. void runStateChanged(bool);@/
  8584. private:@/
  8585. @<TimerDisplay Private Variables@>@;@t\2@>@/
  8586. }@t\kern-3pt@>;
  8587. @ Qt provides a property system based on its meta-object system. This allows for
  8588. a number of advanced features which \pn{} does not use. The properties available
  8589. for the TimerDisplay class exist for historical reasons, but there are some
  8590. plans for future development which may make use of them. The properties may also
  8591. be useful for someone using this class in another program.
  8592. @<TimerDisplay Properties@>=
  8593. Q_PROPERTY(QTime seconds READ seconds WRITE setTimer)@/
  8594. Q_PROPERTY(TimerMode mode READ mode WRITE setMode)@/
  8595. Q_PROPERTY(bool running READ isRunning)@/
  8596. Q_PROPERTY(QTime resetValue READ resetValue WRITE setResetValue)@/
  8597. Q_PROPERTY(QString displayFormat READ displayFormat WRITE setDisplayFormat)@/
  8598. Q_PROPERTY(bool autoReset READ autoReset WRITE setAutoReset)@/
  8599. @ A number of private variables are used to implement this class.
  8600. @<TimerDisplay Private Variables@>=
  8601. QTime s;
  8602. QTime r;
  8603. QTimer clock;
  8604. TimerDisplay::TimerMode m;
  8605. bool running;
  8606. bool ar;
  8607. QAction *startAction;
  8608. QAction *stopAction;
  8609. QAction *resetAction;
  8610. QString f;
  8611. QTime relative;
  8612. QTime base;
  8613. @ |TimerDisplay| is a specialization of |QLCDNumber| designed for time keeping
  8614. purposes. It sets up a timer that fires roughly every half second to see if it
  8615. needs to update itself. The constructor sets this up, but does not start the
  8616. timer. The class provides three actions which can be used to start, stop, or
  8617. reset the timer. These actions are also set up in the constructor.
  8618. By default, the timer will display its time in hours, minutes, and seconds. This
  8619. can be changed as is done with the batch timer (it is expected that nobody will
  8620. want to spend an hour or more to roast a batch of coffee). The display style is
  8621. also changed to a sensible default, but this can be changed with the usual
  8622. |QLCDNumber| methods.
  8623. @<TimerDisplay Implementation@>=
  8624. TimerDisplay::TimerDisplay(QWidget *parent) : QLCDNumber(8, parent),
  8625. s(QTime(0, 0, 0)), r(QTime(0, 0, 0)), clock(NULL),@/ m(TimerDisplay::CountUp),
  8626. running(false), ar(false), startAction(new QAction(tr("Start"), NULL)),@/
  8627. stopAction(new QAction(tr("Stop"), NULL)),
  8628. resetAction(new QAction(tr("Reset"), NULL)),@/ f(QString("hh:mm:ss")),
  8629. relative(QTime::currentTime()), base(QTime(0, 0, 0))@/
  8630. {
  8631. connect(startAction, SIGNAL(triggered(bool)), this, SLOT(startTimer()));
  8632. connect(stopAction, SIGNAL(triggered(bool)), this, SLOT(stopTimer()));
  8633. connect(resetAction, SIGNAL(triggered(bool)), this, SLOT(reset()));
  8634. clock.setInterval(500);
  8635. clock.setSingleShot(false);
  8636. connect(&clock, SIGNAL(timeout()), this, SLOT(updateTime()));
  8637. setSegmentStyle(Filled);
  8638. updateDisplay();
  8639. }
  8640. @ The complicated bits are all in the |updateTime()| method. The behavior of
  8641. this function depends on the current |TimerMode| of the display.
  8642. @<TimerDisplay Implementation@>=
  8643. void TimerDisplay::updateTime()
  8644. {
  8645. QTime time;
  8646. int cseconds = 0;
  8647. int oseconds = 0;
  8648. int r = 0;
  8649. QTime nt = QTime(0, 0, 0);
  8650. int n = 0;
  8651. int bseconds = 0;
  8652. switch(m)@/
  8653. {@t\1@>@/
  8654. case TimerDisplay::CountUp:@/
  8655. @<Check for Timer Increment@>;
  8656. break;
  8657. case TimerDisplay::CountDown:@/
  8658. @<Check for Timer Decrement@>;
  8659. break;
  8660. case TimerDisplay::Clock:@/
  8661. @<Check for Clock Change@>;
  8662. break;
  8663. default:@/
  8664. Q_ASSERT_X(false, "updateTime", "invalid timer mode");
  8665. break;@t\2@>@/
  8666. }
  8667. updateDisplay();
  8668. }
  8669. @ To have the timer count up, we calculate the value that the timer should
  8670. indicate and compare it to the time indicated. If there is a difference, we
  8671. update the time to the new value and send emit a signal.
  8672. @<Check for Timer Increment@>=
  8673. @<Load seconds since base time into r@>@;
  8674. nt = nt.addSecs(r);
  8675. if(nt != s)
  8676. {
  8677. s = nt;
  8678. emit valueChanged(s);
  8679. }
  8680. @ Here we want to calculate the number of seconds in the current time, the
  8681. number of seconds in a base time, and the difference between the two. The
  8682. value loaded into oseconds could probably be cached.
  8683. @d TIMETOINT(t) ((t.hour() * 60 * 60) + (t.minute() * 60) + (t.second()))
  8684. @<Load seconds since base time into r@>=
  8685. time = QTime::currentTime();
  8686. cseconds = TIMETOINT(time);
  8687. oseconds = TIMETOINT(relative);
  8688. r = cseconds - oseconds;
  8689. @ The logic for a count down timer is very similar to the logic for a count up
  8690. timer. A key difference is that we don't want to continue counting down if the
  8691. timer has already reached 0.
  8692. @<Check for Timer Decrement@>=
  8693. if(s > QTime(0, 0, 0))@/
  8694. {@/
  8695. @<Load seconds since base time into r@>@;
  8696. bseconds = TIMETOINT(base);
  8697. n = bseconds - r;
  8698. nt = nt.addSecs(n);
  8699. if(nt != s)
  8700. {
  8701. s = nt;
  8702. emit valueChanged(s);
  8703. }
  8704. }
  8705. @ The clock mode is the simplest case as it just needs to find out if the time
  8706. has changed.
  8707. @<Check for Clock Change@>=
  8708. time = QTime::currentTime();
  8709. if(time != s)
  8710. {
  8711. s = time;
  8712. emit valueChanged(s);
  8713. }
  8714. @ When counting up or down, it is important to record the time at which the
  8715. timer starts. The clock that triggers time updates must also be started. The
  8716. timer also needs to reset its value if that behavior is desired.
  8717. @d TIMESUBTRACT(t1, t2) (t1.addSecs(-(TIMETOINT(t2))).addMSecs(-t2.msec()))
  8718. @<TimerDisplay Implementation@>=
  8719. void TimerDisplay::startTimer()@t\2\2@>@/
  8720. {@t\1@>@/
  8721. if(!running)@/
  8722. {@t\1@>@/
  8723. relative = QTime::currentTime();
  8724. if(ar)@/
  8725. {
  8726. reset();
  8727. }
  8728. else
  8729. {
  8730. relative = TIMESUBTRACT(relative, s);
  8731. }
  8732. if(m == Clock)@/
  8733. {
  8734. updateTime();
  8735. }
  8736. base = s;
  8737. clock.start();@/
  8738. running = true;
  8739. emit runStateChanged(true);@t\2@>@/
  8740. }@t\2@>@/
  8741. }
  8742. @ Stopping the timer is a little simpler. Remember to stop the clock so we
  8743. aren't updating senselessly.
  8744. @<TimerDisplay Implementation@>=
  8745. void TimerDisplay::stopTimer()@t\2\2@>@/
  8746. {@t\1@>@/
  8747. if(running)@/
  8748. {@t\1@>@/
  8749. clock.stop();@/
  8750. running = false;
  8751. emit runStateChanged(false);@t\2@>@/
  8752. }@t\2@>@/
  8753. }
  8754. @ The clock is also stopped in the destructor.
  8755. @<TimerDisplay Implementation@>=
  8756. TimerDisplay::~TimerDisplay()
  8757. {
  8758. clock.stop();
  8759. }
  8760. @ The rest of the functions are trivial. There are functions for changing the
  8761. timer mode:
  8762. @<TimerDisplay Implementation@>=
  8763. void TimerDisplay::setCountUpMode()
  8764. {
  8765. m = TimerDisplay::CountUp;
  8766. }
  8767. void TimerDisplay::setCountDownMode()
  8768. {
  8769. m = TimerDisplay::CountDown;
  8770. }
  8771. void TimerDisplay::setClockMode()
  8772. {
  8773. m = TimerDisplay::Clock;
  8774. }
  8775. @ There are a few functions to obtain information about the state of the timer.
  8776. @<TimerDisplay Implementation@>=
  8777. QString TimerDisplay::value()
  8778. {
  8779. return s.toString(f);
  8780. }
  8781. QTime TimerDisplay::seconds()
  8782. {
  8783. return s;
  8784. }
  8785. TimerDisplay::TimerMode TimerDisplay::mode()
  8786. {
  8787. return m;
  8788. }
  8789. bool TimerDisplay::isRunning()
  8790. {
  8791. return running;
  8792. }
  8793. QTime TimerDisplay::resetValue()
  8794. {
  8795. return r;
  8796. }
  8797. QString TimerDisplay::displayFormat()
  8798. {
  8799. return f;
  8800. }
  8801. bool TimerDisplay::autoReset()
  8802. {
  8803. return ar;
  8804. }
  8805. @ There are also some functions for setting aspects of the timer state.
  8806. @<TimerDisplay Implementation@>=
  8807. void TimerDisplay::setTimer(QTime value)
  8808. {
  8809. if(value.isValid())
  8810. {
  8811. s = value;
  8812. updateDisplay();
  8813. emit valueChanged(value);
  8814. }
  8815. }
  8816. void TimerDisplay::setMode(TimerDisplay::TimerMode mode)
  8817. {
  8818. m = mode;
  8819. }
  8820. void TimerDisplay::setResetValue(QTime value)
  8821. {
  8822. r = value;
  8823. }
  8824. void TimerDisplay::setDisplayFormat(QString format)
  8825. {
  8826. f = format;
  8827. setNumDigits(format.length());
  8828. }
  8829. void TimerDisplay::setAutoReset(bool reset)
  8830. {
  8831. ar = reset;
  8832. }
  8833. @ |TimerDisplay| supports using the system clipboard to copy the current timer
  8834. value.
  8835. @<TimerDisplay Implementation@>=
  8836. void TimerDisplay::copyTimer()
  8837. {
  8838. QApplication::clipboard()->setText(value());
  8839. }
  8840. @ Resetting the timer is simple. We don't reset the timer if it is still running
  8841. mainly to prevent accidents.
  8842. @<TimerDisplay Implementation@>=
  8843. void TimerDisplay::reset()
  8844. {
  8845. if(!running)
  8846. {
  8847. s = r;
  8848. updateDisplay();
  8849. }
  8850. }
  8851. @ Finally, there is the function for changing the text of the display to the
  8852. current time value.
  8853. @<TimerDisplay Implementation@>=
  8854. void TimerDisplay::updateDisplay()
  8855. {
  8856. display(value());
  8857. }
  8858. @ Exposing |TimerDisplay| to the host environment is simple.
  8859. @<Function prototypes for scripting@>=
  8860. QScriptValue constructTimerDisplay(QScriptContext *context,
  8861. QScriptEngine *engine);
  8862. void setTimerDisplayProperties(QScriptValue value, QScriptEngine *engine);
  8863. @ The engine must be informed of the script constructor.
  8864. @<Set up the scripting engine@>=
  8865. constructor = engine->newFunction(constructTimerDisplay);
  8866. value = engine->newQMetaObject(&TimerDisplay::staticMetaObject, constructor);
  8867. engine->globalObject().setProperty("TimerDisplay", value);
  8868. @ The implementation of these functions is trivial.
  8869. @<Functions for scripting@>=
  8870. QScriptValue constructTimerDisplay(QScriptContext *, QScriptEngine *engine)
  8871. {
  8872. QScriptValue object = engine->newQObject(new TimerDisplay);
  8873. setTimerDisplayProperties(object, engine);
  8874. return object;
  8875. }
  8876. void setTimerDisplayProperties(QScriptValue value, QScriptEngine *engine)
  8877. {
  8878. setQLCDNumberProperties(value, engine);
  8879. }
  8880. @** The Human Computer Interface.
  8881. \noindent A few classes are required for putting the rest of the program
  8882. together in a way that it can be used by a human. There is a layout class for
  8883. arranging widgets in a way that is not simple with the layouts provided by Qt.
  8884. There are classes for labeling the various indicators. There are also window
  8885. classes that put all of this together in a useful and usable way. One of these
  8886. classes is currently depreciated.
  8887. @* The PackLayout Class.
  8888. \noindent The |PackLayout| class provides functionality similar to the
  8889. |QBoxLayout| class in Qt. It allows the construction of a row or column of
  8890. widgets. Each item will take up space along the orientation of the layout equal
  8891. to its size hint except for the last widget which will take up all remaining
  8892. space. Widgets will be resized in the direction perpendicular to the orientation
  8893. of the layout to use all available space.
  8894. This class was originally written with the |WidgetDecorator| class which we will
  8895. get to later in mind, but it has found use in other places where the left or top
  8896. most widgets should not be resized.
  8897. By default, a new |PackLayout| will arrange widgets horizontally. This can be
  8898. changed with a call to |setOrientation()|.
  8899. @<Class declarations@>=
  8900. class PackLayout : public QLayout@/
  8901. {@/
  8902. int doLayout(const QRect &rect, bool testOnly) const;@/
  8903. QList<QLayoutItem *> itemList;@/
  8904. Qt::Orientations@, orientation;@/
  8905. public:@/
  8906. PackLayout(QWidget *parent, int margin = 0, int spacing = -1);
  8907. PackLayout(int spacing = -1);
  8908. ~PackLayout();
  8909. void addItem(QLayoutItem *item);
  8910. Qt::Orientations@, expandingDirections() const;
  8911. bool hasHeightForWidth() const;
  8912. int heightForWidth(int width) const;
  8913. int count() const;
  8914. QLayoutItem *itemAt(int index) const;
  8915. QSize minimumSize() const;
  8916. void setGeometry(const QRect &rect);
  8917. void setOrientation(Qt::Orientations direction);
  8918. QSize sizeHint() const;
  8919. QLayoutItem *takeAt(int index);
  8920. };
  8921. @ The interesting portion of this class is in |doLayout()|. This function goes
  8922. over the items in the layout and sets the geometry appropriately.
  8923. The seemingly odd choice of returning |y| at the end of this function (indeed of
  8924. having a return value at all) is to allow this function to provide the return
  8925. value needed in |heightForWidth()|.
  8926. If |testOnly| is set to |true|, |y| will be calculated, but the widget geometry
  8927. will not be changed.
  8928. @<PackLayout Implementation@>=
  8929. int PackLayout::doLayout(const QRect &rect, bool testOnly) const
  8930. {
  8931. int x = rect.x();
  8932. int y = rect.y();
  8933. QLayoutItem *item;
  8934. if(orientation == Qt::Horizontal)
  8935. {
  8936. @<Lay the widgets out horizontally@>@;
  8937. }
  8938. else
  8939. {
  8940. @<Lay the widgets out vertically@>@;
  8941. }
  8942. return y;
  8943. }
  8944. @ To lay the widgets out horizontally, we go over each item in the list taking
  8945. the width of the size hint and spacing into account unless the item is the last
  8946. item in the list, in which case the right of the widget needs to be at the end
  8947. of the available space. We use the foreach construction that Qt provides to
  8948. iterate over each item in the list in much the same way as foreach constructions
  8949. are used in languages that support them directly.
  8950. @<Lay the widgets out horizontally@>=
  8951. foreach(item, itemList)
  8952. {
  8953. int nextX = x + item->sizeHint().width() + spacing();
  8954. int right = x + item->sizeHint().width();
  8955. if(item == itemList.last())
  8956. {
  8957. right = rect.right();
  8958. }
  8959. int bottom = rect.bottom();
  8960. if(!testOnly)
  8961. {
  8962. item->setGeometry(QRect(QPoint(x, y), QPoint(right, bottom)));
  8963. }
  8964. x = nextX;
  8965. }
  8966. @ Laying out the widgets vertically is very similar.
  8967. @<Lay the widgets out vertically@>=
  8968. foreach(item, itemList)
  8969. {
  8970. int nextY = y + item->sizeHint().height() + spacing();
  8971. int bottom = y + item->sizeHint().height();
  8972. if(item == itemList.last())
  8973. {
  8974. bottom = rect.bottom();
  8975. }
  8976. int right = rect.right();
  8977. if(!testOnly)
  8978. {
  8979. item->setGeometry(QRect(QPoint(x, y), QPoint(right, bottom)));
  8980. }
  8981. y = nextY;
  8982. }
  8983. @ As a layout class, there are a number of things the class should be able to do
  8984. in order to play nicely with other classes. One of these is determining the
  8985. minimum size of the layout. The minimum size of the layout is equal to the space
  8986. required for each item in the layout plus the margin space. The margin space
  8987. will be equal to twice the specified margin in each direction to account for a
  8988. top, bottom, left, and right margin.
  8989. @<PackLayout Implementation@>=
  8990. QSize PackLayout::minimumSize() const
  8991. {
  8992. QSize size;
  8993. QLayoutItem *item;
  8994. foreach(item, itemList)
  8995. {
  8996. if(orientation == Qt::Horizontal)
  8997. {
  8998. size += QSize(item->minimumSize().width(), 0);
  8999. if(size.height() < item->minimumSize().height())
  9000. {
  9001. size.setHeight(item->minimumSize().height());
  9002. }
  9003. }
  9004. else
  9005. {
  9006. size += QSize(0, item->minimumSize().height());
  9007. if(size.width() < item->minimumSize().width())
  9008. {
  9009. size.setWidth(item->minimumSize().width());
  9010. }
  9011. }
  9012. }
  9013. size += QSize(2*margin(), 2*margin());
  9014. return size;
  9015. }
  9016. @ |PackLayout| features two constructors. One allows for setting the margin,
  9017. spacing, and a parent widget at the time of construction. The other creates a
  9018. parentless layout which will have to be added to another widget or layout.
  9019. @<PackLayout Implementation@>=
  9020. PackLayout::PackLayout(QWidget *parent, int margin, int spacing) :
  9021. QLayout(parent)@/
  9022. {
  9023. setMargin(margin);
  9024. setSpacing(spacing);
  9025. setOrientation(Qt::Horizontal);
  9026. }
  9027. PackLayout::PackLayout(int spacing)
  9028. {
  9029. setSpacing(spacing);
  9030. setOrientation(Qt::Horizontal);
  9031. }
  9032. @ In Qt, items in a layout are owned by that layout. When the layout is
  9033. destroyed, all of the items in that layout must also be deleted.
  9034. @<PackLayout Implementation@>=
  9035. PackLayout::~PackLayout()
  9036. {
  9037. QLayoutItem *item;
  9038. while((item = takeAt(0)))
  9039. {
  9040. delete item;
  9041. }
  9042. }
  9043. @ Deleting the items uses the |takeAt()| method to remove each widget from the
  9044. layout prior to deleting it. The item requested should exist, but if it doesn't,
  9045. |NULL| is returned.
  9046. @<PackLayout Implementation@>=
  9047. QLayoutItem* PackLayout::takeAt(int index)
  9048. {
  9049. if(index >= 0 && index < itemList.size())
  9050. {
  9051. return itemList.takeAt(index);
  9052. }
  9053. else
  9054. {
  9055. return NULL;
  9056. }
  9057. }
  9058. @ If we are interested in which item is in a particular position in the layout
  9059. but do not want to remove it from the layout, |itemAt()| provides that.
  9060. @<PackLayout Implementation@>=
  9061. QLayoutItem* PackLayout::itemAt(int index) const
  9062. {
  9063. if(index >= 0 && index < itemList.size())
  9064. {
  9065. return itemList.at(index);
  9066. }
  9067. else
  9068. {
  9069. return NULL;
  9070. }
  9071. }
  9072. @ A layout class is not very useful unless there is a way to get items into the
  9073. layout. The |QLayoutItem| class is designed in such a way that it is possible to
  9074. pass pointers to objects that inherit |QLayout| or |QWidget|.
  9075. The base |QLayout| class provides an |addWidget()| method that will use our
  9076. version of |addItem()|. That should be used when adding a widget to the layout.
  9077. The Qt documentation recommends also providing an |addLayout()| method so that
  9078. other code does not need to call this method, but that has not been provided
  9079. yet.
  9080. @<PackLayout Implementation@>=
  9081. void PackLayout::addItem(QLayoutItem *item)
  9082. {
  9083. itemList.append(item);
  9084. }
  9085. @ It is sometimes useful to know how many items are in a layout.
  9086. @<PackLayout Implementation@>=
  9087. int PackLayout::count() const@;@/
  9088. {@/
  9089. return itemList.size();@/
  9090. }
  9091. @ A few more functions are needed to make the layout class work well with other
  9092. classes. For more details, please consult the Qt Reference
  9093. Documentation\nfnote{Qt Reference Documentation\par\indent\hbox{%
  9094. \pdfURL{http://doc.trolltech.com/4.3/index.html}%
  9095. {http://doc.trolltech.com/4.3/index.html}}}
  9096. @<PackLayout Implementation@>=
  9097. Qt::Orientations PackLayout::expandingDirections() const
  9098. {
  9099. return Qt::Vertical | Qt::Horizontal;
  9100. }
  9101. bool PackLayout::hasHeightForWidth() const@t\2\2@>@/
  9102. {@t\1@>@/
  9103. return false;@t\2@>@/
  9104. }@/
  9105. int PackLayout::heightForWidth(int width) const
  9106. {
  9107. return doLayout(QRect(0, 0, width, 0), true);
  9108. }
  9109. void PackLayout::setGeometry(const QRect &rect)
  9110. {
  9111. QLayout::setGeometry(rect);
  9112. doLayout(rect, false);
  9113. }
  9114. QSize PackLayout::sizeHint() const
  9115. {
  9116. return minimumSize();
  9117. }
  9118. @ It was mentioned previously that this layout is capable of lining widgets up
  9119. in a row or presenting them in a column. This is done with the
  9120. |setOrientation()| method.
  9121. @<PackLayout Implementation@>=
  9122. void PackLayout::setOrientation(Qt::Orientations direction)
  9123. {
  9124. orientation = direction;
  9125. doLayout(geometry(), false);
  9126. }
  9127. @* The SceneButton Class.
  9128. \noindent Ordinarily, mouse down events that are passed from a |QGraphicsView|
  9129. to an interactive |QGraphicsScene| will continue to pass that click down to an
  9130. item in the scene. This class is used when we are interested in a click anywhere
  9131. in the view and it doesn't really matter where in the scene that click occurred
  9132. or even if there is a graphics item at that point. Any click passed to the
  9133. |SceneButton| will cause the scene to emit a signal containing the screen
  9134. coordinates of the click.
  9135. This was originally designed for use in the |WidgetDecorator| class. While the
  9136. functionality provided is not currently used, the original plan was to use this
  9137. to provide access to configuration options.
  9138. It is possible that this class is no longer necessary even if features it was
  9139. made for are implemented.
  9140. @<Class declarations@>=
  9141. class SceneButton : public QGraphicsScene@/
  9142. {@/
  9143. Q_OBJECT@;
  9144. public:@/
  9145. SceneButton();
  9146. ~SceneButton();
  9147. protected:@/
  9148. void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent);
  9149. signals:@/
  9150. void clicked(QPoint pos);
  9151. };
  9152. @ The implementation is trivial.
  9153. @<SceneButton Implementation@>=
  9154. SceneButton::SceneButton() : QGraphicsScene()@/
  9155. {
  9156. /* Nothing has to be done here. */
  9157. }
  9158. SceneButton::~SceneButton()
  9159. {
  9160. /* Nothing has to be done here. */
  9161. }
  9162. void SceneButton::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
  9163. {
  9164. emit clicked(mouseEvent->buttonDownScreenPos(mouseEvent->button()));
  9165. }
  9166. @* The WidgetDecorator Class.
  9167. \noindent The |WidgetDecorator| class provides a way to label various widgets
  9168. while also providing additional options for interacting with them. The
  9169. decoration can exist to the left or atop the widget being decorated. When the
  9170. label is to the left of the widget, the label text is rotated.
  9171. This class is likely to change considerably in the future as features are added
  9172. that allow actions to be added to the decoration to allow various configuration
  9173. options.
  9174. @<Class declarations@>=
  9175. class WidgetDecorator : public QWidget@/
  9176. {
  9177. Q_OBJECT@;
  9178. PackLayout *layout;
  9179. QGraphicsView *label;
  9180. QGraphicsTextItem *text;
  9181. SceneButton *scene;
  9182. public:@/
  9183. WidgetDecorator(QWidget *widget, const QString &labeltext,@|
  9184. Qt::Orientations@, orientation = Qt::Horizontal,@|
  9185. QWidget *parent = NULL, Qt::WindowFlags f = 0);
  9186. ~WidgetDecorator();
  9187. void setBackgroundBrush(QBrush background);
  9188. void setTextColor(QColor color);
  9189. };
  9190. @ Almost everything this class currently does is handled in the constructor.
  9191. @<WidgetDecorator Implementation@>=
  9192. WidgetDecorator::WidgetDecorator(QWidget *widget, const QString &labeltext,
  9193. Qt::Orientations orientation,
  9194. QWidget *parent, Qt::WindowFlags f)@/:
  9195. QWidget(parent, f), label(new QGraphicsView()),
  9196. scene(new SceneButton())@t\2@>@/
  9197. {
  9198. layout = new PackLayout(this);
  9199. layout->setOrientation(orientation);
  9200. @<Prepare the graphics view@>@;
  9201. @<Add the label to the scene@>@;
  9202. @<Adjust the decoration width@>@;
  9203. @<Pack widgets into the layout@>@;
  9204. }
  9205. @ The decoration is a |QGraphicsView|. To get this to look right, we need to
  9206. make sure there aren't any scroll bars and there shouldn't be a frame
  9207. surrounding it. While we're at it, we allow it to accept clicks, though this
  9208. functionality is not yet used.
  9209. @<Prepare the graphics view@>=
  9210. label->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  9211. label->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  9212. label->setFrameShape(QFrame::NoFrame);
  9213. label->setInteractive(true);
  9214. @ The |QGraphicsView| needs a scene to display anything. The scene consists of a
  9215. background which, by default is solid cyan. This can be changed later by setting
  9216. a different background brush. Text also needs to be added to the scene. If the
  9217. decoration is to the left of the widget, the text needs to be rotated.
  9218. @<Add the label to the scene@>=
  9219. scene->setBackgroundBrush(Qt::cyan);
  9220. text = scene->addText(labeltext);
  9221. if(orientation == Qt::Horizontal)
  9222. {
  9223. text->rotate(270.0);
  9224. }
  9225. label->setScene(scene);
  9226. @ The decoration should have the text centered in the view. The widget should
  9227. also be no wider (or taller for horizontal orientation) than necessary for the
  9228. text.
  9229. The case for horizontal orientation here may seem a little strange, however the
  9230. dimensions of the bounding rectangle are not affected by rotation. This means
  9231. that even though we want the width of the rotated text, this is the same as the
  9232. height of the text.
  9233. @<Adjust the decoration width@>=
  9234. if(orientation == Qt::Horizontal)
  9235. {
  9236. label->setMaximumWidth((int)(text->boundingRect().height() + 1));
  9237. }
  9238. else
  9239. {
  9240. label->setMaximumHeight((int)(text->boundingRect().height() + 1));
  9241. }
  9242. label->centerOn(text);
  9243. @ Once the decoration is ready, the decoration and the widget being decorated
  9244. can be added to the layout. A minimum size for the compound widget is also
  9245. calculated.
  9246. @<Pack widgets into the layout@>=
  9247. layout->addWidget(label);
  9248. layout->addWidget(widget);
  9249. if(orientation == Qt::Horizontal)
  9250. {
  9251. setMinimumSize(widget->sizeHint().width() + label->sizeHint().width(),
  9252. widget->sizeHint().height());
  9253. }
  9254. else
  9255. {
  9256. setMinimumSize(widget->sizeHint().width(),
  9257. widget->sizeHint().height() + label->sizeHint().height());
  9258. }
  9259. @ As mentioned previously, it is possible to change the background pattern for
  9260. the decoration. It is also possible to change the color of the text.
  9261. @<WidgetDecorator Implementation@>=
  9262. void WidgetDecorator::setBackgroundBrush(QBrush background)
  9263. {
  9264. scene->setBackgroundBrush(background);
  9265. }
  9266. void WidgetDecorator::setTextColor(QColor color)
  9267. {
  9268. text->setDefaultTextColor(color);
  9269. }
  9270. @ Finally, there is a destructor.
  9271. @<WidgetDecorator Implementation@>=
  9272. WidgetDecorator::~WidgetDecorator()
  9273. {
  9274. /* Nothing has to be done here. */
  9275. }
  9276. @ In order to create a decorated widget from a script, we need these functions.
  9277. @<Function prototypes for scripting@>=
  9278. void setWidgetDecoratorProperties(QScriptValue value, QScriptEngine *engine);
  9279. QScriptValue constructWidgetDecorator(QScriptContext *context,
  9280. QScriptEngine *engine);
  9281. @ The scripting engine must be informed of this function.
  9282. @<Set up the scripting engine@>=
  9283. constructor = engine->newFunction(constructWidgetDecorator);
  9284. value = engine->newQMetaObject(&WidgetDecorator::staticMetaObject, constructor);
  9285. engine->globalObject().setProperty("WidgetDecorator", value);
  9286. @ The constructor is slightly more complex than other script constructors, but
  9287. still simple.
  9288. @<Functions for scripting@>=
  9289. QScriptValue constructWidgetDecorator(QScriptContext *context,
  9290. QScriptEngine *engine)
  9291. {
  9292. QWidget *widget = argument<QWidget *>(0, context);
  9293. QString text = argument<QString>(1, context);
  9294. Qt::Orientations@, orientation;
  9295. switch(argument<int>(2, context))@/
  9296. {@t\1@>@/
  9297. case 2:@/
  9298. orientation = Qt::Vertical;
  9299. break;
  9300. default:@/
  9301. orientation = Qt::Horizontal;
  9302. break;@t\2@>@/
  9303. }
  9304. QScriptValue object =
  9305. engine->newQObject(new WidgetDecorator(widget, text, orientation));
  9306. setWidgetDecoratorProperties(object, engine);
  9307. return object;
  9308. }
  9309. void setWidgetDecoratorProperties(QScriptValue value, QScriptEngine *engine)
  9310. {
  9311. setQWidgetProperties(value, engine);
  9312. }
  9313. @* The LogEditWindow Class.
  9314. \noindent This class will be depreciated in a future release once I have
  9315. confirmed that the class can be replaced by the configuration system. It has not
  9316. been updated to support new functionality added in version 1.2.3 and use of this
  9317. class is highly discouraged.
  9318. While the logging window provided in the example configuration is fine for
  9319. recording an existing roast, there are some who would like to be able to use
  9320. \pn{} to work with data collected with a manual logger. Different controls are
  9321. useful in such a case. The |LogEditWindow| provides this.
  9322. @<Class declarations@>=
  9323. class LogEditWindow : public QMainWindow@/
  9324. {@t\1@>@/
  9325. Q_OBJECT@;
  9326. QWidget *centralWidget;
  9327. PackLayout *mainLayout;
  9328. QHBoxLayout *addRowsLayout;
  9329. QLabel *startTimeLabel;
  9330. QTimeEdit *startTime;
  9331. QLabel *endTimeLabel;
  9332. QTimeEdit *endTime;
  9333. QLabel *intervalLabel;
  9334. QSpinBox *interval;
  9335. QPushButton *addRows;
  9336. QAction *saveXml;
  9337. QAction *saveCsv;
  9338. QAction *openXml;
  9339. MeasurementModel *model;
  9340. QTableView *log;@/
  9341. @t\4@>private slots@t\kern-3pt@>:@/
  9342. void addTheRows();
  9343. void saveXML();
  9344. void saveCSV();
  9345. void openXML();@/
  9346. protected:@/
  9347. void closeEvent(QCloseEvent *event);@/
  9348. public:@/
  9349. LogEditWindow();@t\2@>@/
  9350. }@t\kern-3pt@>;
  9351. @ This window provides controls for adding rows to a measurement. Typically, the
  9352. data on a manual roast log will have measurements at regular intervals with the
  9353. possible exception of a few points where there are control changes or the end of
  9354. the batch. The routine for adding rows is capable of adding a single row, rows
  9355. in a range of times at regular intervals, or rows in a range of times at regular
  9356. intervals plus one time at the end.
  9357. @<LogEditWindow Implementation@>=
  9358. void LogEditWindow::addTheRows()
  9359. {
  9360. QTime s = startTime->time();
  9361. while(s < endTime->time())
  9362. {
  9363. model->newMeasurement(Measurement(0, s), 1);
  9364. s = s.addSecs(interval->value());
  9365. }
  9366. model->newMeasurement(Measurement(0, endTime->time()), 1);
  9367. }
  9368. @ The window is prepared in its constructor.
  9369. @<LogEditWindow Implementation@>=
  9370. LogEditWindow::LogEditWindow() : QMainWindow(NULL),
  9371. centralWidget(new QWidget(NULL)), mainLayout(new PackLayout(0)),@|
  9372. addRowsLayout(new QHBoxLayout(NULL)),
  9373. startTimeLabel(new QLabel("Start Time")),@|
  9374. startTime(new QTimeEdit(QTime(0, 0, 0, 0))),@|
  9375. endTimeLabel(new QLabel("End Time")),
  9376. endTime(new QTimeEdit(QTime(0, 20, 0, 0))),@|
  9377. intervalLabel(new QLabel("Interval (seconds)")),@|
  9378. interval(new QSpinBox()),
  9379. addRows(new QPushButton("Add Rows")),@|
  9380. saveXml(new QAction(tr("Save Profile As..."), NULL)),@|
  9381. saveCsv(new QAction(tr("Export CSV"), NULL)),@|
  9382. openXml(new QAction(tr("Load Target Profile..."), NULL)),@|
  9383. model(new MeasurementModel()),
  9384. log(new QTableView())@/
  9385. {
  9386. @<Restore editor window geometry from settings@>@;
  9387. @<Set up the editor control bar@>@;
  9388. @<Prepare the model@>@;
  9389. @<Prepare the log table@>@;
  9390. mainLayout->addItem(addRowsLayout);
  9391. mainLayout->addWidget(log);
  9392. centralWidget->setLayout(mainLayout);
  9393. setCentralWidget(centralWidget);
  9394. QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
  9395. fileMenu->addAction(openXml);
  9396. connect(openXml, SIGNAL(triggered()), this, SLOT(openXML()));
  9397. fileMenu->addAction(saveXml);
  9398. connect(saveXml, SIGNAL(triggered()), this, SLOT(saveXML()));
  9399. fileMenu->addAction(saveCsv);
  9400. connect(saveCsv, SIGNAL(triggered()), this, SLOT(saveCSV()));
  9401. }
  9402. @ The window keeps its previous size and location in settings. These need to be
  9403. restored when a new window is created.
  9404. @<Restore editor window geometry from settings@>=
  9405. QSettings settings;
  9406. resize(settings.value("logSize", QSize(620,400)).toSize());
  9407. move(settings.value("logPos", QPoint(200,60)).toPoint());
  9408. @ When a new window is opened, it starts with an empty profile. If this is used
  9409. to manually enter a profile rather than edit an existing profile, rows will need
  9410. to be added. For this, we provide a set of controls where a start time, an end
  9411. time, and an interval in seconds is specified along with a button that, when
  9412. pressed, will produce a row in the model for the starting time, the ending time,
  9413. and regularly spaced times between the two. If only a single row is needed, this
  9414. can be produced by setting the start and end times the same.
  9415. @<Set up the editor control bar@>=
  9416. mainLayout->setOrientation(Qt::Vertical);
  9417. addRowsLayout->addSpacing(10);
  9418. addRowsLayout->addWidget(startTimeLabel);
  9419. addRowsLayout->addWidget(startTime);
  9420. addRowsLayout->addSpacing(10);
  9421. startTime->setDisplayFormat("mm:ss");
  9422. addRowsLayout->addWidget(endTimeLabel);
  9423. addRowsLayout->addWidget(endTime);
  9424. addRowsLayout->addSpacing(10);
  9425. endTime->setDisplayFormat("mm:ss");
  9426. addRowsLayout->addWidget(intervalLabel);
  9427. addRowsLayout->addWidget(interval);
  9428. addRowsLayout->addSpacing(10);
  9429. interval->setRange(0, 60);
  9430. interval->setValue(30);
  9431. addRowsLayout->addWidget(addRows);
  9432. addRowsLayout->addSpacing(10);
  9433. connect(addRows, SIGNAL(clicked()), this, SLOT(addTheRows()));
  9434. @ The model will have three columns: Time, Temperature, and Annotation. This
  9435. probably should not be hard coded.
  9436. @<Prepare the model@>=
  9437. model->setHeaderData(0, Qt::Horizontal, "Time");
  9438. model->setHeaderData(1, Qt::Horizontal, "Temperature");
  9439. model->setHeaderData(2, Qt::Horizontal, "Annotation");
  9440. model->clear();
  9441. @ The profile is presented in a table view. The columns should be wide enough to
  9442. contain a label, the data contained in the column, and an editor delegate.
  9443. @<Prepare the log table@>=
  9444. log->setModel(model);
  9445. log->setColumnWidth(0, 100);
  9446. log->setColumnWidth(1, 100);
  9447. log->setColumnWidth(2, 100);
  9448. @ Most users will want to save a profile after they've edited it. We also
  9449. provide CSV export here. Note that this class only supports logs with a single
  9450. temperature and a single annotation column. As the class is considered
  9451. depreciated, it will not be extended to support arbitrarily many columns.
  9452. @<LogEditWindow Implementation@>=
  9453. void LogEditWindow::saveXML()
  9454. {
  9455. QSettings settings;
  9456. QString lastDir = settings.value("lastDirectory").toString();
  9457. QString filename = QFileDialog::getSaveFileName(this, tr("Save Log As..."),
  9458. lastDir, "", 0);
  9459. QFile file(filename);
  9460. XMLOutput writer(model, &file, 0);
  9461. writer.addTemperatureColumn("Temperature", 1);
  9462. writer.addAnnotationColumn("Annotation", 2);
  9463. if(writer.output())
  9464. {
  9465. QFileInfo info(filename);
  9466. QDir directory = info.dir();
  9467. lastDir = directory.path();
  9468. settings.setValue("lastDirectory", lastDir);
  9469. }
  9470. }
  9471. void LogEditWindow::saveCSV()
  9472. {
  9473. QSettings settings;
  9474. QString lastDir = settings.value("lastDirectory").toString();
  9475. QString filename = QFileDialog::getSaveFileName(this, tr("Export As..."),
  9476. lastDir, "", 0);
  9477. QFile file(filename);
  9478. CSVOutput writer(model, &file, 0);
  9479. writer.addTemperatureColumn("Temperature", 1);
  9480. writer.addAnnotationColumn("Annotation", 2);
  9481. if(writer.output())
  9482. {
  9483. QFileInfo info(filename);
  9484. QDir directory = info.dir();
  9485. lastDir = directory.path();
  9486. settings.setValue("lastDirectory", lastDir);
  9487. }
  9488. }
  9489. @ Some may want to open a previously saved profile, for example, to adjust the
  9490. position of an annotation. Note that this class is not appropriate for editing
  9491. profiles with more than one temperature column.
  9492. @<LogEditWindow Implementation@>=
  9493. void LogEditWindow::openXML()
  9494. {
  9495. QSettings settings;
  9496. QString lastDir = settings.value("lastDirectory").toString();
  9497. QString filename = QFileDialog::getOpenFileName(this, tr("Open XML Log..."),
  9498. lastDir, "", 0);
  9499. if(filename.isNull())
  9500. {
  9501. return;
  9502. }
  9503. QFile file(filename);
  9504. XMLInput reader(&file, 1);
  9505. connect(&reader, SIGNAL(measure(Measurement, int)),
  9506. model, SLOT(newMeasurement(Measurement, int)));
  9507. connect(&reader, SIGNAL(annotation(QString, int, int)),
  9508. model, SLOT(newAnnotation(QString, int, int)));
  9509. if(reader.input())
  9510. {
  9511. QFileInfo info(filename);
  9512. setWindowTitle(QString(tr("%1 - %2")).@|
  9513. arg(QCoreApplication::applicationName()).arg(info.baseName()));
  9514. QDir directory = info.dir();
  9515. lastDir = directory.path();
  9516. settings.setValue("lastDirectory", lastDir);
  9517. }
  9518. }
  9519. @ The window should remember its last size and position, so we store this
  9520. information in settings when the window is closed.
  9521. @<LogEditWindow Implementation@>=
  9522. void LogEditWindow::closeEvent(QCloseEvent *event)
  9523. {
  9524. QSettings settings;
  9525. settings.setValue("logSize", size());
  9526. settings.setValue("logPos", pos());
  9527. event->accept();
  9528. }
  9529. @ One function is required to instantiate this class from a script.
  9530. @<Function prototypes for scripting@>=
  9531. QScriptValue constructLogEditWindow(QScriptContext *context,
  9532. QScriptEngine *engine);
  9533. @ The engine must be informed of this function.
  9534. @<Set up the scripting engine@>=
  9535. constructor = engine->newFunction(constructLogEditWindow);
  9536. value = engine->newQMetaObject(&LogEditWindow::staticMetaObject, constructor);
  9537. engine->globalObject().setProperty("LogEditWindow", value);
  9538. @ The constructor just creates the window and passes it back to the engine.
  9539. @<Functions for scripting@>=
  9540. QScriptValue constructLogEditWindow(QScriptContext *, QScriptEngine *engine)
  9541. {
  9542. QScriptValue object = engine->newQObject(new LogEditWindow);
  9543. return object;
  9544. }
  9545. @** File IO.
  9546. \noindent So far, the data is all stored in memory. It is often useful to save
  9547. data to a file or read back previously saved data. Presently, two formats are
  9548. supported: an XML format which can also be read back in and CSV which can easily
  9549. be used with many external tools.
  9550. File IO is handled by a few classes: one per input format and one per output
  9551. format. The classes in the following sections should be simple enough to follow
  9552. that it should be clear how to extend \pn{} to support other formats if needed.
  9553. Should additional output formats be required, it may be beneficial to
  9554. reimplement the serializers as subclasses of a new abstract serializer class in
  9555. order to share common code among them where reusing \cweb{} chunks is not an
  9556. appropriate technique.
  9557. @* XML Output.
  9558. \noindent An XML format has been chosen as the native format for \pn{} because
  9559. of Qt's excellent support for reading and writing such documents. Using this
  9560. capability is less error prone than developing a new, more compact format.
  9561. Another reason to choose XML is that it becomes quite easy to modify saved data
  9562. in a text editor and still end up with something \pn{} will understand.
  9563. The structure of the file we will produce is simple, however it has been
  9564. modified from a simpler structure that was used in versions of Typica prior to
  9565. 1.2.3. How to read these files can be determined by the document type found at
  9566. the start of the file. At the start of the file, there should be one or more
  9567. {\tt <tempseries>} elements and one or more {\tt <noteseries>} elements. These
  9568. are empty elements with a {\tt name} attribute which can be used to label the
  9569. column in a view. Once these column declarations have been written, a
  9570. {\tt <roast>} element is produced which contains a set of zero or more
  9571. {\tt <tuple>} elements. Each tuple contains one {\tt <time>} element containing
  9572. the time of the measurement relative to the start of the batch and optionally
  9573. one or more {\tt <temperature>} and {\tt <annotation>} elements containing
  9574. measurement and annotation data associated with that time. The
  9575. {\tt <temperature>} and {\tt <annotation>} elements have a {\tt series}
  9576. attribute where the value of the attribute matches the {\tt name} attribute of a
  9577. {\tt <tempseries>} or {\tt <noteseries>} element which allows each measurement
  9578. to be placed in the correct data series regardless of element ordering in the
  9579. document.
  9580. There are certain oddities about this format compared with other XML based
  9581. formats. The order of some elements in the current implementation affects the
  9582. behavior of the program and there is no longer a proper root element. This
  9583. format may be extended in future versions of \pn{} to support additional
  9584. functionality or to improve the robustness of the format. Should such
  9585. modifications occur, an effort should be made to ensure that \pn{} continues to
  9586. support the import of old data.
  9587. As of version 1.0.8, this class is derived from |QObject| for easier integration
  9588. with the scripting engine.
  9589. The |temperatureColumns| and |annotationColumns| member data structures are
  9590. currently a |QMap| rather than a |QHash| because the number of data series in a
  9591. single file is likely to be small enough that the difference in lookup time
  9592. should be negligeable and the ability to iterate over the keys in the |QMap| in
  9593. sorted order is useful.
  9594. @<Class declarations@>=
  9595. class XMLOutput : public QObject@/
  9596. {@/
  9597. Q_OBJECT@;@/
  9598. MeasurementModel *data;
  9599. QIODevice *out;
  9600. int time;
  9601. QMap<int, QString> temperatureColumns;
  9602. QMap<int, QString> annotationColumns;
  9603. public:@/
  9604. XMLOutput(MeasurementModel *model, QIODevice *device, int timec = 0);
  9605. void addTemperatureColumn(const QString &series, int column);
  9606. void addAnnotationColumn(const QString &series, int column);
  9607. void setModel(MeasurementModel *model);
  9608. void setTimeColumn(int column);
  9609. void setDevice(QIODevice *device);
  9610. bool output();
  9611. };
  9612. @ The interesting part of this class is the |output| routine. This goes over the
  9613. data in the model and constructs an appropriate XML document. If the operation
  9614. fails, the function returns |false|, otherwise it returns |true|.
  9615. @<XMLOutput Implementation@>=
  9616. bool XMLOutput::output()@t\2\2@>@/
  9617. {@t\1@>@/
  9618. if(!out->open(QIODevice::WriteOnly | QIODevice::Text))@/
  9619. {@t\1@>@/
  9620. return false;@t\2@>@/
  9621. }@/
  9622. QXmlStreamWriter xmlout(out);
  9623. xmlout.writeStartDocument("1.0");
  9624. xmlout.writeDTD("<!DOCTYPE roastlog2.0>");
  9625. xmlout.writeStartElement("roastlog");
  9626. @<Output the column declarations@>@;
  9627. xmlout.writeStartElement("roast");
  9628. bool oresult;
  9629. for(int i = 0; i < data->rowCount(); i++)@/
  9630. {
  9631. @<Check if row should be output@>@;
  9632. if(oresult)
  9633. {
  9634. @<Output tuple element@>@;
  9635. }
  9636. }
  9637. xmlout.writeEndElement();
  9638. xmlout.writeEndElement();
  9639. xmlout.writeEndDocument();
  9640. out->close();@/
  9641. return true;@t\2@>@/
  9642. }
  9643. @ Temperature column declarations are output before annotation column
  9644. declarations. Within each category, column declarations are output in order by
  9645. column number.
  9646. @<Output the column declarations@>=
  9647. foreach(int c, temperatureColumns.keys())
  9648. {
  9649. xmlout.writeStartElement("tempseries");
  9650. xmlout.writeAttribute("name", temperatureColumns.value(c));
  9651. xmlout.writeEndElement();
  9652. }
  9653. foreach(int c, annotationColumns.keys())
  9654. {
  9655. xmlout.writeStartElement("noteseries");
  9656. xmlout.writeAttribute("name", annotationColumns.value(c));
  9657. xmlout.writeEndElement();
  9658. }
  9659. @ When checking a row in the model to determine if it contains values that need
  9660. to be written, we want to know if any of the temperature or annotation columns
  9661. contain a value. If at least one of these columns is not empty for this row, we
  9662. need to output a tuple for that row.
  9663. @<Check if row should be output@>=
  9664. oresult = false;@/
  9665. foreach(int c, temperatureColumns.keys())@/
  9666. {@t\1@>@/
  9667. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  9668. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  9669. {@t\1@>@/
  9670. oresult = true;
  9671. break;@t\2@>@/
  9672. }@t\2@>@/
  9673. }@/
  9674. if(oresult == false)@/
  9675. {@t\1@>@/
  9676. foreach(int c, annotationColumns.keys())@/
  9677. {@t\1@>@/
  9678. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  9679. !(data->data(data->index(i, c), Qt::DisplayRole).toString().
  9680. isEmpty()))@/
  9681. {@t\1@>@/
  9682. oresult = true;
  9683. break;@t\2@>@/
  9684. }@t\2@>@/
  9685. }@t\2@>@/
  9686. }
  9687. @ Now that we know that values from the current row should be output, we can
  9688. produce a {\tt <tuple>} element, a {\tt <time>} element for that tuple, and then
  9689. iterate over the set of columns we might want to output, producing an
  9690. appropriate element for each non-empty column for that row.
  9691. @<Output tuple element@>=
  9692. xmlout.writeStartElement("tuple");
  9693. xmlout.writeTextElement("time", data->data(data->index(i, time),
  9694. Qt::DisplayRole).toString());
  9695. foreach(int c, temperatureColumns.keys())@/
  9696. {
  9697. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  9698. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  9699. {
  9700. xmlout.writeStartElement("temperature");
  9701. xmlout.writeAttribute("series", temperatureColumns.value(c));
  9702. xmlout.writeCharacters(data->data(data->index(i, c), Qt::DisplayRole).
  9703. toString());
  9704. xmlout.writeEndElement();
  9705. }
  9706. }
  9707. foreach(int c, annotationColumns.keys())@/
  9708. {
  9709. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  9710. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  9711. {
  9712. xmlout.writeStartElement("annotation");
  9713. xmlout.writeAttribute("series", annotationColumns.value(c));
  9714. xmlout.writeCharacters(data->data(data->index(i, c), Qt::DisplayRole).
  9715. toString());
  9716. xmlout.writeEndElement();
  9717. }
  9718. }
  9719. xmlout.writeEndElement();
  9720. @ The rest of the class just initializes the private member data.
  9721. @<XMLOutput Implementation@>=
  9722. XMLOutput::XMLOutput(MeasurementModel *model, QIODevice *device, int timec)
  9723. : QObject(NULL), data(model), out(device), time(timec)@/
  9724. {
  9725. /* Nothing has to be done here. */
  9726. }@;
  9727. void XMLOutput::setModel(MeasurementModel *model)
  9728. {
  9729. data = model;
  9730. }
  9731. void XMLOutput::setTimeColumn(int column)
  9732. {
  9733. time = column;
  9734. }
  9735. void XMLOutput::setDevice(QIODevice *device)
  9736. {
  9737. out = device;
  9738. }
  9739. @ As of version 1.2.3, the old |setTemperatureColumn()| and
  9740. |setAnnotationColumn()| methods have been replaced with the
  9741. |addTemperatureColumn()| and |addAnnotationColumn()| methods respectively. The
  9742. main difference is that the new methods take a column name in addition to a
  9743. number and it is now possible to specify multiple columns of each category for
  9744. export.
  9745. @<XMLOutput Implementation@>=
  9746. void XMLOutput::addTemperatureColumn(const QString &series, int column)
  9747. {
  9748. temperatureColumns.insert(column, series);
  9749. }
  9750. void XMLOutput::addAnnotationColumn(const QString &series, int column)
  9751. {
  9752. annotationColumns.insert(column, series);
  9753. }
  9754. @* XML Input.
  9755. \noindent Once model data can be saved to a file, it is useful to be able to
  9756. read that data back in. This is a little different from reading data out of a
  9757. model as more than one object is potentially interested in the data. Instead, we
  9758. emit signals for measurements and annotations. This class has been modified to
  9759. support both the current (as of version 1.2.3) output of the |XMLOutput| class
  9760. and the older version. If changes are made to |XMLOutput| this class may also
  9761. need to be modified.
  9762. The main differences in the current version of this class are that the first
  9763. column is specified rather than specifying temperature and annotation columns
  9764. separately and additional signals are emitted to allow views to prepare for an
  9765. arbitrary number of columns.
  9766. The |newTemperatureColumn| and |newAnnotationColumn| signals can be used to set
  9767. up column headers while the |lastColumn| signal can be used to shift live data
  9768. streams to unoccupied columns.
  9769. @<Class declarations@>=
  9770. class XMLInput : public QObject@/
  9771. {
  9772. Q_OBJECT@;
  9773. int firstc;
  9774. QIODevice *in;
  9775. public:@/
  9776. XMLInput(QIODevice *input, int c);
  9777. void setFirstColumn(int column);
  9778. void setDevice(QIODevice *device);
  9779. bool input();
  9780. signals:@/
  9781. void measure(Measurement, int);
  9782. void annotation(QString, int, int);
  9783. void newTemperatureColumn(int, QString);
  9784. void newAnnotationColumn(int, QString);
  9785. void lastColumn(int);
  9786. };
  9787. @ The main point of interest here is the |input()| method. If the file is read
  9788. successfully, |true| is returned. Otherwise, |false| is returned.
  9789. @<XMLInput Implementation@>=
  9790. bool XMLInput::input()@t\2\2@>@/
  9791. {@t\1@>@/
  9792. if(!in->open(QIODevice::ReadOnly | QIODevice::Text))@/
  9793. {@t\1@>@/
  9794. return false;@t\2@>@/
  9795. }@/
  9796. QXmlStreamReader xmlin(in);
  9797. QMap<QString, int> temperatureColumns;
  9798. QMap<QString, int> annotationColumns;
  9799. int nextColumn = firstc;
  9800. @<Read column declarations@>@;
  9801. QTime timeval = QTime();
  9802. double tempval = 0;
  9803. QString noteval = QString();
  9804. int column;
  9805. int counter = 0;@/
  9806. while(!xmlin.atEnd())@/
  9807. {@/
  9808. @<Read XML file@>@;
  9809. }@/
  9810. return true;@t\2@>@/
  9811. }
  9812. @ A data file may or may not contain elements that specify the name of a column.
  9813. In order to determine how to proceed, we should check the doctype of the input
  9814. file. This should be the first element of the input file encountered.
  9815. \danger There is not nearly enough error checking here.
  9816. \endanger
  9817. @<Read column declarations@>=
  9818. while(!xmlin.isDTD())
  9819. {
  9820. xmlin.readNext();
  9821. }
  9822. if(xmlin.isDTD())
  9823. {
  9824. if(xmlin.text() == "<!DOCTYPE roastlog>")
  9825. {
  9826. @<Emit old format column specification@>@;
  9827. }
  9828. else
  9829. {
  9830. xmlin.readNext();
  9831. @<Scan for column declarations and emit@>@;
  9832. }
  9833. }
  9834. @ Old format data will not have column declarations. This means that we must
  9835. produce a default set of signals rather than waiting to read elements describing
  9836. the columns.
  9837. @<Emit old format column specification@>=
  9838. emit newTemperatureColumn(firstc, "Bean");
  9839. emit newAnnotationColumn(firstc + 1, "Note");
  9840. emit lastColumn(firstc + 1);
  9841. @ The current format will have column declarations prior to the {\tt <roast>}
  9842. element. We can just read until we hit that element and emit the appropriate
  9843. signals as elements are encountered.
  9844. @<Scan for column declarations and emit@>=
  9845. while(xmlin.name() != "roast")
  9846. {
  9847. if(xmlin.isStartElement())
  9848. {
  9849. if(xmlin.name() == "tempseries")
  9850. {
  9851. temperatureColumns.insert(xmlin.attributes().value("name").
  9852. toString(),
  9853. nextColumn);
  9854. emit newTemperatureColumn(nextColumn,
  9855. xmlin.attributes().value("name").
  9856. toString());
  9857. nextColumn++;
  9858. }
  9859. else if(xmlin.name() == "noteseries")
  9860. {
  9861. annotationColumns.insert(xmlin.attributes().value("name").
  9862. toString(), nextColumn);
  9863. emit newAnnotationColumn(nextColumn,
  9864. xmlin.attributes().value("name").
  9865. toString());
  9866. nextColumn++;
  9867. }
  9868. }
  9869. xmlin.readNext();
  9870. }
  9871. emit lastColumn(nextColumn - 1);
  9872. @ Now we are ready to read measurements from the file. When encountering a
  9873. {\tt <time>} element, we record the time and move on. For {\tt <temperature>}
  9874. and {\tt <annotation>} elements, we emit the appropriate signal. This is handled
  9875. slightly differently depending on which version of the file format is being
  9876. used. Note that there is not nearly enough error checking here and we are
  9877. basically ignoring {\tt <tuple>} elements.
  9878. Due to the typically large number of measurements taken over the course of a
  9879. roast and the amount of time often taken to process these measurements when they
  9880. are read from a file, there is a need to periodically pass control back to the
  9881. event loop to remain responsive to user input.
  9882. @<Read XML file@>=
  9883. xmlin.readNext();
  9884. if(xmlin.isStartElement())
  9885. {
  9886. @<Read measurement data@>@;
  9887. }
  9888. counter++;
  9889. if(counter % 100 == 0)
  9890. {
  9891. QCoreApplication::processEvents();
  9892. }
  9893. @ When reading start elements, it is safe to ignore {\tt <tuple>} and
  9894. {\tt <roast>}. Technically, this means that the program can read certain types
  9895. of invalid data. The Robustness Principle\nfnote{``Be liberal in what you
  9896. accept, and conservative in what you send,'' --- Robert Braden, {\it RFC 1122
  9897. \S 1.2.2}} is generally applicable to any type of data exchange. That said,
  9898. malformed data is not guaranteed readable in the future, even if it does work
  9899. now.
  9900. \danger One set of test input caused this code to emit an empty annotation for
  9901. every measurement. This is the reason for wrapping the annotation signal
  9902. emission to check for this. The detected annotation elements were not present in
  9903. the input stream and I have absolutely no idea where the program came up with
  9904. them. \endanger
  9905. @<Read measurement data@>=
  9906. if(xmlin.name() == "time")
  9907. {
  9908. timeval = QTime::fromString(xmlin.readElementText(), "mm:ss.zzz");
  9909. }
  9910. else if(xmlin.name() == "temperature")
  9911. {
  9912. column = xmlin.attributes().value("series").toString().isEmpty() ?
  9913. firstc : temperatureColumns.value(xmlin.attributes().
  9914. value("series").toString());
  9915. tempval = xmlin.readElementText().toDouble();
  9916. Measurement measurement(tempval, timeval);
  9917. emit measure(measurement, column);
  9918. }
  9919. else if(xmlin.name() == "annotation")
  9920. {
  9921. column = xmlin.attributes().value("series").toString().isEmpty() ?
  9922. firstc + 1 : annotationColumns.value(xmlin.attributes().
  9923. value("series").toString());
  9924. noteval = xmlin.readElementText();
  9925. if(!noteval.isEmpty())
  9926. {
  9927. emit annotation(noteval, firstc, column);
  9928. }
  9929. }
  9930. @ The other methods just set the private member data.
  9931. @<XMLInput Implementation@>=
  9932. XMLInput::XMLInput(QIODevice *input, int c) :
  9933. firstc(c), in(input)@/
  9934. {@/
  9935. /* Nothing has to be done here. */
  9936. }
  9937. void XMLInput::setFirstColumn(int column)
  9938. {
  9939. firstc = column;
  9940. }
  9941. void XMLInput::setDevice(QIODevice *device)
  9942. {
  9943. in = device;
  9944. }
  9945. @ In order to allow scripts to instantiate the |XMLInput| class, we need a
  9946. constructor and a wrapper around the |input()| method.
  9947. @<Function prototypes for scripting@>=
  9948. QScriptValue constructXMLInput(QScriptContext *context, QScriptEngine *engine);
  9949. QScriptValue XMLInput_input(QScriptContext *context, QScriptEngine *engine);
  9950. @ The script constructor is passed to the scripting engine.
  9951. @<Set up the scripting engine@>=
  9952. constructor = engine->newFunction(constructXMLInput);
  9953. value = engine->newQMetaObject(&XMLInput::staticMetaObject, constructor);
  9954. engine->globalObject().setProperty("XMLInput", value);
  9955. @ The implementation should seem familiar.
  9956. @<Functions for scripting@>=
  9957. QScriptValue constructXMLInput(QScriptContext *context, QScriptEngine *engine)
  9958. {
  9959. QIODevice *device = argument<QIODevice *>(0, context);
  9960. QScriptValue object = engine->newQObject(new XMLInput(&*device,
  9961. argument<int>(1, context)));
  9962. object.setProperty("input", engine->newFunction(XMLInput_input));
  9963. return object;
  9964. }
  9965. QScriptValue XMLInput_input(QScriptContext *context, QScriptEngine *)
  9966. {
  9967. XMLInput *self = getself<@[XMLInput *@]>(context);
  9968. self->input();
  9969. return QScriptValue();
  9970. }
  9971. @* CSV Output.
  9972. \noindent While XML is convenient for \pn{}, other programs may not handle this
  9973. format well. For this purpose, we use a text file with comma separated values.
  9974. Data in this format can easily be handled by shell scripts, simple programs, and
  9975. any spreadsheet (though some may handle the time column poorly).
  9976. We do not need to concern ourselves with reading data in this format back in,
  9977. but there is no reason a class could not be written to do this.
  9978. The structure of this class is very similar to the |XMLOutput| class.
  9979. @<Class declarations@>=
  9980. class CSVOutput@/
  9981. {@/
  9982. MeasurementModel *data;
  9983. QIODevice *out;
  9984. int time;
  9985. QMap<int, QString> temperatureColumns;
  9986. QMap<int, QString> annotationColumns;@/
  9987. public:@/
  9988. CSVOutput(MeasurementModel *model, QIODevice *device, int timec = 0);
  9989. void addTemperatureColumn(const QString &series, int column);
  9990. void addAnnotationColumn(const QString &series, int column);
  9991. void setModel(MeasurementModel *model);
  9992. void setTimeColumn(int column);
  9993. void setDevice(QIODevice *device);
  9994. bool output();@/
  9995. };
  9996. @ Very little needs to be done to output the data. We open the output stream
  9997. and, if the output stream was successfully opened, we look for measurements and
  9998. output the text, remembering to output a comma between items and a newline after
  9999. each record. If the data is successfully output, |true| is returned, otherwise
  10000. we return |false|.
  10001. The comparably simple structure of the CSV format allows us to just fling the
  10002. data onto a text stream.
  10003. @<CSVOutput Implementation@>=
  10004. bool CSVOutput::output()@t\2\2@>@/
  10005. {@t\1@>@/
  10006. if(!out->open(QIODevice::WriteOnly | QIODevice::Text))@/
  10007. {@t\1@>@/
  10008. return false;@t\2@>@/
  10009. }@/
  10010. QTextStream output(out);
  10011. @<Output CSV column headers@>@;
  10012. bool oresult;
  10013. for(int i = 0; i < data->rowCount(); i++)@/
  10014. {
  10015. @<Check if row should be output@>@;
  10016. if(oresult)
  10017. {
  10018. @<Output CSV row@>@;
  10019. }
  10020. }
  10021. out->close();@/
  10022. return true;@t\2@>@/
  10023. }
  10024. @ Before writing the data, we output a row containing the name of each column.
  10025. @<Output CSV column headers@>=
  10026. output << "Time";
  10027. foreach(int c, temperatureColumns.keys())
  10028. {
  10029. output << ',' << temperatureColumns.value(c);
  10030. }
  10031. foreach(int c, annotationColumns.keys())
  10032. {
  10033. output << ',' << annotationColumns.value(c);
  10034. }
  10035. output << '\n';
  10036. @ Once the header information has been written, we can proceed to output the
  10037. real data. The algorithm for doing this has been changed as of version 1.2.3
  10038. with the result that most uses will now produce more delimiters than the same
  10039. data in previous versions. This should have no impact on the ability of other
  10040. programs to interact with data produced by \pn{}. The code to handle output in
  10041. this way is much easier to read. A future version might once again suppress
  10042. superfluous commas, however the presence of these commas is not considered a
  10043. serious issue at this time.
  10044. @<Output CSV row@>=
  10045. output << data->data(data->index(i, time), Qt::DisplayRole).toString();
  10046. foreach(int c, temperatureColumns.keys())
  10047. {
  10048. output << ',' << data->data(data->index(i, c), Qt::DisplayRole).toString();
  10049. }
  10050. foreach(int c, annotationColumns.keys())
  10051. {
  10052. output << ',' << data->data(data->index(i, c), Qt::DisplayRole).toString();
  10053. }
  10054. output << '\n';
  10055. @ The rest of the class just initializes the private member data. See notes
  10056. on the implementation of |XMLOutput|.
  10057. @<CSVOutput Implementation@>=
  10058. CSVOutput::CSVOutput(MeasurementModel *model, QIODevice *device, int timec) :
  10059. data(model), out(device), time(timec)@/
  10060. {
  10061. /* Nothing has to be done here. */
  10062. }@;
  10063. void CSVOutput::setModel(MeasurementModel *model)
  10064. {
  10065. data = model;
  10066. }
  10067. void CSVOutput::setTimeColumn(int column)
  10068. {
  10069. time = column;
  10070. }
  10071. void CSVOutput::addTemperatureColumn(const QString &series, int column)
  10072. {
  10073. temperatureColumns.insert(column, series);
  10074. }
  10075. void CSVOutput::addAnnotationColumn(const QString &series, int column)
  10076. {
  10077. annotationColumns.insert(column, series);
  10078. }
  10079. void CSVOutput::setDevice(QIODevice *device)
  10080. {
  10081. out = device;
  10082. }
  10083. @* Web views.
  10084. The |QWebView| class was initially brought in to handle printing roast profile
  10085. data. This works by transforming the roasting data to an XHTML+SVG document,
  10086. loading it into a web view, and calling the |print()| method on that. Support
  10087. has since been extended to make it easier to produce reports that require either
  10088. postprocessing database results or database capabilities that are not readily
  10089. available in the reporting framework.
  10090. With this new use, future development should allow inclusion of a web view in
  10091. the user interface without needing to instantiate it from a script.
  10092. @<Set up the scripting engine@>=
  10093. constructor = engine->newFunction(constructWebView);
  10094. value = engine->newQMetaObject(&QWebView::staticMetaObject, constructor);
  10095. engine->globalObject().setProperty("WebView", value);
  10096. @ A few properties are required. These should be available regardless of how the
  10097. object was created.
  10098. @<Functions for scripting@>=
  10099. QScriptValue constructWebView(QScriptContext *, QScriptEngine *engine)
  10100. {
  10101. QScriptValue object = engine->newQObject(new QWebView());
  10102. setQWebViewProperties(object, engine);
  10103. return object;
  10104. }
  10105. void setQWebViewProperties(QScriptValue value, QScriptEngine *engine)
  10106. {
  10107. setQWidgetProperties(value, engine);
  10108. value.setProperty("load", engine->newFunction(WebView_load));
  10109. value.setProperty("print", engine->newFunction(WebView_print));
  10110. value.setProperty("setHtml", engine->newFunction(WebView_setHtml));
  10111. value.setProperty("setContent", engine->newFunction(WebView_setContent));
  10112. value.setProperty("saveXml", engine->newFunction(WebView_saveXml));
  10113. }
  10114. @ To get data into the web view, we load it from a URL passed in the form of a
  10115. string. This will usually be a local file, but it doesn't have to be.
  10116. @<Functions for scripting@>=
  10117. QScriptValue WebView_load(QScriptContext *context, QScriptEngine *)
  10118. {
  10119. QWebView *self = getself<QWebView *>(context);
  10120. QString file = argument<QString>(0, context);
  10121. self->load(QUrl(file));
  10122. return QScriptValue();
  10123. }
  10124. @ When wrapping |QWebView::print()|, we need to obtain a |QPrinter| which that
  10125. method expects. In order to set everything up properly, we display a standard
  10126. print dialog.
  10127. @<Functions for scripting@>=
  10128. QScriptValue WebView_print(QScriptContext *context, QScriptEngine *)
  10129. {
  10130. QWebView *self = getself<QWebView *>(context);
  10131. QPrinter *printer = new QPrinter(QPrinter::HighResolution);
  10132. QPrintDialog printDialog(printer, NULL);
  10133. if(printDialog.exec() == QDialog::Accepted)
  10134. {
  10135. self->print(printer);
  10136. }
  10137. return QScriptValue();
  10138. }
  10139. @ When wrapping |QWebView::setHtml()|, only the first argument containing the
  10140. content is required.
  10141. @<Functions for scripting@>=
  10142. QScriptValue WebView_setHtml(QScriptContext *context, QScriptEngine *)
  10143. {
  10144. QWebView *self = getself<QWebView *>(context);
  10145. QString content = argument<QString>(0, context);
  10146. self->setHtml(content);
  10147. return QScriptValue();
  10148. }
  10149. @ This is a simple wrapper around |QWebView::setContent()|, but it obtains its
  10150. argument from the data in a |QIODevice|. A MIME type of application/xhtml+xml is
  10151. specified by default to allow embedding SVG.
  10152. @<Functions for scripting@>=
  10153. QScriptValue WebView_setContent(QScriptContext *context, QScriptEngine *)
  10154. {
  10155. QWebView *self = getself<QWebView *>(context);
  10156. QIODevice *device = argument<QIODevice *>(0, context);
  10157. device->reset();
  10158. QByteArray content = device->readAll();
  10159. self->setContent(content, "application/xhtml+xml");
  10160. return QScriptValue();
  10161. }
  10162. @ It should be possible to save the XHTML documents generated for reports. The
  10163. saveXml property provides one way to do this.
  10164. @<Functions for scripting@>=
  10165. QScriptValue WebView_saveXml(QScriptContext *context, QScriptEngine *)
  10166. {
  10167. QWebView *self = getself<QWebView *>(context);
  10168. return QScriptValue(self->page()->currentFrame()->documentElement().toOuterXml());
  10169. }
  10170. @ The web view can be created from the XML portion of the configuration
  10171. document. This function adds the view to a box layout.
  10172. @<Functions for scripting@>=
  10173. void addWebViewToLayout(QDomElement element, QStack<QWidget *> *,
  10174. QStack<QLayout *> *layoutStack)
  10175. {
  10176. QWebView *view = new QWebView;
  10177. if(element.hasAttribute("id"))
  10178. {
  10179. view->setObjectName(element.attribute("id"));
  10180. }
  10181. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  10182. layout->addWidget(view);
  10183. }
  10184. @ The function prototypes used above follow.
  10185. @<Function prototypes for scripting@>=
  10186. QScriptValue constructWebView(QScriptContext *context, QScriptEngine *engine);
  10187. QScriptValue WebView_load(QScriptContext *context, QScriptEngine *engine);
  10188. QScriptValue WebView_print(QScriptContext *context, QScriptEngine *engine);
  10189. QScriptValue WebView_setContent(QScriptContext *context, QScriptEngine *engine);
  10190. QScriptValue WebView_setHtml(QScriptContext *context, QScriptEngine *engine);
  10191. QScriptValue WebView_saveXml(QScriptContext *context, QScriptEngine *);
  10192. void addWebViewToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  10193. QStack<QLayout *> *layoutStack);
  10194. void setQWebViewProperties(QScriptValue value, QScriptEngine *engine);
  10195. @* The Application class.
  10196. The |Application| class represents the \pn{} program. It is responsible for
  10197. setting up the settings object and localization in addition to the normal
  10198. responsibilities of |QApplication|. In addition to declaring the class, we also
  10199. define a macro that returns the |Application| instance.
  10200. @d AppInstance (qobject_cast<@[Application *@]>(qApp))
  10201. @<Class declarations@>=
  10202. class NodeInserter;
  10203. class DeviceTreeModel;
  10204. class Application : public QApplication@/
  10205. {@/
  10206. @[Q_OBJECT@]@;
  10207. public:@/
  10208. Application(int &argc, char **argv);
  10209. QDomDocument* configuration();
  10210. @<Device configuration members@>@;
  10211. QSqlDatabase database();
  10212. QScriptEngine *engine;@/
  10213. @[public slots@]:@/
  10214. @<Extended Application slots@>@;
  10215. private:@/
  10216. @<Application private data members@>@;
  10217. QDomDocument conf;
  10218. };
  10219. @ The constructor for this class handles a few things that had previously been
  10220. handled in |main()|.
  10221. @<Application Implementation@>=
  10222. Application::Application(int &argc, char **argv) : QApplication(argc, argv)@/
  10223. {
  10224. @<Allow use of the default QSettings constructor@>@;
  10225. @<Load translation objects@>@;
  10226. @<Register meta-types@>@;
  10227. @<Register top level device configuration nodes@>@;
  10228. }
  10229. @ We use |QSettings| objects throughout \pn{} to remember details such as the
  10230. size and position of windows and the most recently used directory. To simplify
  10231. the creation of these objects, we specify some details up front. This allows us
  10232. to use the default constructor rather than specifying these things every time we
  10233. need an object.
  10234. @<Allow use of the default QSettings constructor@>=
  10235. setOrganizationName("Wilson's Coffee & Tea");
  10236. setOrganizationDomain("wilsonscoffee.com");
  10237. setApplicationName(PROGRAM_NAME);
  10238. @ Much of the user visible text in \pn{} is wrapped in a call to |tr()|. Such
  10239. text can be replaced with translated text based on the user's locale. For more
  10240. details, see the Qt Linguist manual.
  10241. @<Load translation objects@>=
  10242. QTranslator base;
  10243. if(base.load(QString("qt_%1").arg(QLocale::system().name())))
  10244. {
  10245. installTranslator(&base);
  10246. }
  10247. QTranslator app;
  10248. if(app.load(QString("%1_%2").arg("Typica").arg(QLocale::system().name())))
  10249. {
  10250. installTranslator(&app);
  10251. }
  10252. @ We also want to be able to access the application instance from within the
  10253. scripting engine. We don't need to be able to create new instances, just access
  10254. the one that already exists.
  10255. @<Set up the scripting engine@>=
  10256. value = engine->newQObject(AppInstance);
  10257. engine->globalObject().setProperty("Application", value);
  10258. @ The |configuration()| method provides access to an XML document containing the
  10259. current application configuration. The object is populated in |main()|.
  10260. @<Application Implementation@>=
  10261. QDomDocument* Application::configuration()
  10262. {
  10263. return &conf;
  10264. }
  10265. @ The |database()| method provides access to a database connection for use by
  10266. database aware widgets.
  10267. @<Application Implementation@>=
  10268. QSqlDatabase Application::database()
  10269. {
  10270. QString connectionName;
  10271. QSqlDatabase connection = QSqlDatabase::database();
  10272. do
  10273. {
  10274. connectionName = QUuid::createUuid().toString();
  10275. } while (QSqlDatabase::connectionNames().contains(connectionName));
  10276. return QSqlDatabase::cloneDatabase(connection, connectionName);
  10277. }
  10278. @** Table editor for ordered arrays with SQL relations.
  10279. \noindent A database in use at Wilson's Coffee \char'046~Tea stores information
  10280. for a roasting log and uses entered information to adjust inventory tracking
  10281. tables. This roasting log connects the use of unroasted coffee with the creation
  10282. of roasted coffee. In order to support roasting coffee from more than one lot at
  10283. the same time, the columns that specify the types of coffee used and the amount
  10284. of each coffee are entered as ordered arrays in which the first entry in the
  10285. array specifying an unroasted coffee is associated with the first entry in the
  10286. array specifying the amount of coffee used. While most batches will involve only
  10287. a single unroasted coffee, the database has no limitation on the number of
  10288. coffees that may be roasted in a single batch. An additional characteristic of
  10289. this table is that the database requires an identification number for unroasted
  10290. coffee items, but it would be better to provide a list of acceptable items with
  10291. human readable names.
  10292. A scrollable area containing a table view which can provide the necessary input
  10293. delegates (such as a combo box for SQL relations) and validators which ensures
  10294. that there is always at least one empty row available for input with convenience
  10295. functions for extracting the arrays needed for database insertion would be ideal
  10296. for this.
  10297. To get this, we need a simple table model based on |QStandardItemModel|
  10298. or |QAbstractItemModel|. The model should ensure that there is always at least
  10299. one empty row available for editing. It should also provide a function for
  10300. obtaining a string that presents all values from a specified column with a given
  10301. role as an array literal suitable for binding to an SQL query.
  10302. A class based on |QComboBox| providing options selected from an SQL query will
  10303. be needed. This can be used as a standalone widget elsewhere, but here it is
  10304. also needed as an editor class for a column delegate. Another delegate class
  10305. allows input in another column to be constrained by a |QValidator| (in this case
  10306. a |QDoubleValidator|).
  10307. A class based on |QTableView| brings all of these classes together and presents
  10308. them to the user.
  10309. @* A table model for producing SQL array literals.
  10310. \noindent This is a simple table model which provides two somewhat unusual
  10311. features. First, it always provides at least one empty row at the end of the
  10312. data. Second, it provides SQL array literals for columns in the model.
  10313. \danger At some point I would like to replace this model and |MeasurementModel|
  10314. with an improved table model suitable to replace both. Some preliminary design
  10315. work suggests that this improvement simplifies \pn{} considerably both
  10316. internally and in the data flow configuration. This has not yet been done due to
  10317. development time constraints.\endanger
  10318. @<Class declarations@>=
  10319. class SaltModel : public QAbstractItemModel@/
  10320. {
  10321. Q_OBJECT@t\2\2@>@/
  10322. QList<QList<QMap<int, QVariant> > > modelData;
  10323. QStringList hData;
  10324. int colcount;@t\1\1@>@/
  10325. public:@/
  10326. SaltModel(int columns);
  10327. ~SaltModel();
  10328. int rowCount(const QModelIndex &parent = QModelIndex()) const;
  10329. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  10330. bool setHeaderData(int section, Qt::Orientation@, orientation,
  10331. const QVariant &value, int role = Qt::DisplayRole);
  10332. QVariant data(const QModelIndex &index, int role) const;
  10333. bool setData(const QModelIndex &index, const QVariant &value,
  10334. int role = Qt::EditRole);
  10335. Qt::ItemFlags@, flags(const QModelIndex &index) const;
  10336. QVariant headerData(int section, Qt::Orientation@, orientation,
  10337. int role = Qt::DisplayRole) const;
  10338. QModelIndex index(int row, int column,
  10339. const QModelIndex &parent = QModelIndex()) const;
  10340. QModelIndex parent(const QModelIndex &index) const;
  10341. QString arrayLiteral(int column, int role) const;
  10342. QString quotedArrayLiteral(int column, int role) const;
  10343. };
  10344. @ The only unique methods in this class are the |arrayLiteral| and
  10345. |quotedArrayLiteral| methods. These take a column number and a data role and
  10346. produce a SQL array literal for every entry in that column with the specified
  10347. role. The string will take the form of
  10348. {\tt{'\LB row 1, row 2, }}$\dots$ {\tt{row N\RB '}}.
  10349. This is done simply by starting with a string identifying the start of an array
  10350. literal, looping over the rows in the model while appending any data found along
  10351. with the commas to separate values. If any data is found, the extra comma and
  10352. space are removed from the constructed string. Finally, text marking the end of
  10353. the array literal is added.
  10354. The |arrayLiteral| method is appropriate where the expected values are numeric.
  10355. The |quotedArrayLiteral| method is appropriate where the expected values are
  10356. text. The values in the array will have quotation marks around them for the
  10357. |quotedArrayLiteral|. Note that when binding these values to placeholders in a
  10358. SQL query the leading and trailing single quote characters should be removed.
  10359. \danger The way this method is currently used is quite harmless. Data from one
  10360. column is integer data obtained as a result of a previous database query and
  10361. data from the other column is restricted by the view to numeric data. Please
  10362. note, however, that it would be extremely stupid to use code such as this when
  10363. user input cannot be controlled so tightly. Were this model used with a view
  10364. that allows general text input, it would be trivial to construct an SQL
  10365. injection attack.
  10366. \medskip
  10367. \centerline{\includegraphics[width=6in]{exploits_of_a_mom}}
  10368. \smallskip
  10369. \centerline{Figure \secno: An Example of an SQL injection attack.\nfnote{%
  10370. Comic copyright Randall Munroe. Original can be found at:~%
  10371. \pdfURL{%
  10372. http://xkcd.com/327/}%
  10373. {http://xkcd.com/327/}}}
  10374. \medskip
  10375. \endanger
  10376. @<SaltModel Implementation@>=
  10377. QString SaltModel::arrayLiteral(int column, int role) const
  10378. {
  10379. QString literal = "'{";
  10380. for(int i = 0; i < rowCount(); i++)
  10381. {
  10382. QString datum = data(index(i, column), role).toString();
  10383. if(!datum.isEmpty())
  10384. {
  10385. literal.append(datum);
  10386. literal.append(", ");
  10387. }
  10388. }
  10389. if(literal.size() > 2)
  10390. {
  10391. literal.chop(2);
  10392. }
  10393. literal.append("}'");
  10394. return literal;
  10395. }
  10396. QString SaltModel::quotedArrayLiteral(int column, int role) const
  10397. {
  10398. QString literal = "'{";
  10399. for(int i = 0; i < rowCount(); i++)
  10400. {
  10401. QString datum = data(index(i, column), role).toString();
  10402. if(!datum.isEmpty())
  10403. {
  10404. literal.append("\"");
  10405. literal.append(datum);
  10406. literal.append("\", ");
  10407. }
  10408. }
  10409. if(literal.size() > 2)
  10410. {
  10411. literal.chop(2);
  10412. }
  10413. literal.append("}'");
  10414. return literal;
  10415. }
  10416. @ No entries in this model have children.
  10417. @<SaltModel Implementation@>=
  10418. QModelIndex SaltModel::parent(const QModelIndex &) const
  10419. {
  10420. return QModelIndex();
  10421. }
  10422. @ The |setData()| method is called by delegates on views when the user enters
  10423. new data. This method must check to determine if the data is being entered in
  10424. the last row to increase the size of the table.
  10425. The end of this function may seem a little strange. Why not simply look up the
  10426. map and insert information directly into the model data? Well, as of this
  10427. writing, that doesn't work. There are two ways around that problem. One is to
  10428. have the lists store references and dereference the real data. The other option
  10429. is to obtain a copy of the row, then a copy of the cell, update the cell, then
  10430. replace the old value of the cell in the copy of the row, then replace the old
  10431. values of the row in the real data. The other option would probably be more
  10432. efficient, but this does work.
  10433. @<SaltModel Implementation@>=
  10434. bool SaltModel::setData(const QModelIndex &index, const QVariant &value,
  10435. int role)@t\2\2@>@/
  10436. {@t\1@>@/
  10437. @<Check that the SaltModel index is valid@>@;
  10438. if(!valid)@/
  10439. {@t\1@>@/
  10440. return false;@t\2@>@/
  10441. }
  10442. if(index.row() == modelData.size() - 1)@/
  10443. {
  10444. beginInsertRows(QModelIndex(), modelData.size(), modelData.size());
  10445. @<Expand the SaltModel@>@;
  10446. endInsertRows();
  10447. }
  10448. QList<QMap<int, QVariant> > row = modelData.at(index.row());
  10449. QMap<int, QVariant> cell = row.at(index.column());
  10450. cell.insert(role, value);
  10451. if(role == Qt::EditRole)@/
  10452. {
  10453. cell.insert(Qt::DisplayRole, value);
  10454. }
  10455. row.replace(index.column(), cell);
  10456. modelData.replace(index.row(), row);
  10457. emit dataChanged(index, index);@/
  10458. return true;@t\2@>@/
  10459. }
  10460. @ Some model operations require checking that a model index is valid. This
  10461. chunk is used in these cases.
  10462. @<Check that the SaltModel index is valid@>=
  10463. bool valid = false;@/
  10464. if(index.isValid())@/
  10465. {@t\1@>@/
  10466. if(index.row() < modelData.size())@/
  10467. {@t\1@>@/
  10468. if(index.column() < colcount)@/
  10469. {@t\1@>@/
  10470. valid = true;@t\2@>@/
  10471. }@t\2@>@/
  10472. }@t\2@>@/
  10473. }
  10474. @ When data is modified in the last row of the table, the model must be expanded
  10475. to allow for additional data.
  10476. @<Expand the SaltModel@>=
  10477. QList<QMap<int, QVariant> > newRow;
  10478. QMap<int, QVariant> defaults;
  10479. for(int i = 0; i < colcount; i++)
  10480. {
  10481. newRow.append(defaults);
  10482. }
  10483. modelData.append(newRow);
  10484. @ The number of columns in the table is specified in the model constructor.
  10485. @<SaltModel Implementation@>=
  10486. SaltModel::SaltModel(int columns) : QAbstractItemModel(), colcount(columns)
  10487. {
  10488. for(int i = 0; i < columns; i++)
  10489. {
  10490. hData << "";
  10491. }
  10492. @<Expand the SaltModel@>@;
  10493. }
  10494. @ The destructor doesn't need to do anything.
  10495. @<SaltModel Implementation@>=
  10496. SaltModel::~SaltModel()
  10497. {
  10498. /* Nothing needs to be done here. */
  10499. }
  10500. @ A pair of methods provide the number of rows and columns in the model. No
  10501. entries in the model have children, so the parent should always be the invisible
  10502. root object.
  10503. @<SaltModel Implementation@>=
  10504. int SaltModel::rowCount(const QModelIndex &parent) const
  10505. {
  10506. return (parent == QModelIndex() ? modelData.size() : 0);
  10507. }
  10508. int SaltModel::columnCount(const QModelIndex &parent) const
  10509. {
  10510. return (parent == QModelIndex() ? colcount : 0);
  10511. }
  10512. @ The model maintains header data for labeling the model columns.
  10513. @<SaltModel Implementation@>=
  10514. bool SaltModel::setHeaderData(int section, Qt::Orientation@, orientation,@|
  10515. const QVariant &value, int)@t\2\2@>@/
  10516. {@t\1@>@/
  10517. if(orientation == Qt::Horizontal && section < colcount)@/
  10518. {@t\1@>@/
  10519. hData.replace(section, value.toString());@/
  10520. emit headerDataChanged(orientation, section, section);@/
  10521. return true;@t\2@>@/
  10522. }@/
  10523. return false;@t\2@>@/
  10524. }
  10525. @ Views need to be able to retrieve model and header data.
  10526. @<SaltModel Implementation@>=
  10527. QVariant SaltModel::data(const QModelIndex &index, int role) const
  10528. {
  10529. @<Check that the SaltModel index is valid@>@;
  10530. if(!valid)
  10531. {
  10532. return QVariant();
  10533. }
  10534. QList<QMap<int,QVariant> > row = modelData.at(index.row());
  10535. QMap<int,QVariant> cell = row.at(index.column());
  10536. return cell.value(role, QVariant());
  10537. }
  10538. QVariant SaltModel::headerData(int section, Qt::Orientation@, orientation,
  10539. int role) const
  10540. {
  10541. if(orientation == Qt::Horizontal && role == Qt::DisplayRole &&
  10542. section < colcount)
  10543. {
  10544. return QVariant(hData.at(section));
  10545. }
  10546. return QVariant();
  10547. }
  10548. @ Views need to know certain details such as if an item in the view can be
  10549. altered by the view. For this model, all valid indices can be edited.
  10550. @<SaltModel Implementation@>=
  10551. Qt::ItemFlags SaltModel::flags(const QModelIndex &index) const
  10552. {
  10553. @<Check that the SaltModel index is valid@>@;
  10554. if(valid)
  10555. {
  10556. return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable;
  10557. }
  10558. return 0;
  10559. }
  10560. @ So far, many of the methods use model indices. The model is responsible for
  10561. creating these.
  10562. @<SaltModel Implementation@>=
  10563. QModelIndex SaltModel::index(int row, int column,
  10564. const QModelIndex &parent) const
  10565. {
  10566. if(parent == QModelIndex())
  10567. {
  10568. if(row < modelData.size() && column < colcount)
  10569. {
  10570. return createIndex(row, column);
  10571. }
  10572. }
  10573. return QModelIndex();
  10574. }
  10575. @* A Delegate for SQL Relations.
  10576. \noindent The first column of the table view being described is responsible for
  10577. providing item numbers to the database. Requiring that these numbers be entered
  10578. directly is prone to not particularly user friendly and almost encourages input
  10579. errors. These item numbers, however, refer to the items table in the database
  10580. which includes, among other details, a human readable text string naming the
  10581. item. This delegate provides the user with a drop down menu from which such a
  10582. string may be selected with this information provided by the database itself.
  10583. When the user selects an item, it informs the model not only of the text string
  10584. in the display role, but also of the id number in a user data role which can
  10585. later be queried in order to properly craft the appropriate query.
  10586. This is implemented with two classes. The first is a |QComboBox| which queries
  10587. the database and maintains a mapping of id to text. This is made its own widget
  10588. as it is useful without being turned into a delegate. The second class provides
  10589. this widget as a delegate and handles communications between it and the model.
  10590. @<Class declarations@>=
  10591. class SqlComboBox : public QComboBox@/
  10592. {@t\1@>@/
  10593. Q_OBJECT@;
  10594. int dataColumn;
  10595. int displayColumn;
  10596. bool dataColumnShown;
  10597. public:@/
  10598. SqlComboBox();
  10599. ~SqlComboBox();
  10600. SqlComboBox* clone(QWidget *parent);@/
  10601. @t\4@>public slots@t\kern-3pt@>:@/
  10602. void addNullOption();
  10603. void addSqlOptions(QString query);
  10604. void setDataColumn(int column);
  10605. void setDisplayColumn(int column);
  10606. void showData(bool show);@t\2@>@/
  10607. }@t\kern-3pt@>;
  10608. @ In order to make this class work a little more nicely as an item delegate,
  10609. the |clone()| method has been provided to create a new object with the same
  10610. options as a prototype.
  10611. @<SqlComboBox Implementation@>=
  10612. SqlComboBox* SqlComboBox::clone(QWidget *parent)
  10613. {
  10614. SqlComboBox *widget = new SqlComboBox();
  10615. widget->setParent(parent);
  10616. for(int i = 0; i < count(); i++)
  10617. {
  10618. widget->addItem(itemText(i), itemData(i));
  10619. }
  10620. return widget;
  10621. }
  10622. @ When using this class, we must first decide if the data column is shown. If
  10623. this is desired, the entries displayed will contain both the value from the
  10624. display column followed by the value from the data column. This can be useful in
  10625. cases where the same text is used for two different items.
  10626. @<SqlComboBox Implementation@>=
  10627. void SqlComboBox::showData(bool show)
  10628. {
  10629. dataColumnShown = show;
  10630. }
  10631. @ Next, there is a need to know if the NULL value may legally be selected. Where
  10632. this is the case, we generally want this to be inserted first. As the
  10633. |QComboBox| supports storing both display and user data, much of the code is a
  10634. thin wrapper around calls to the base class.
  10635. @<SqlComboBox Implementation@>=
  10636. void SqlComboBox::addNullOption()
  10637. {
  10638. addItem(tr("Unknown"), QVariant(QVariant::String));
  10639. }
  10640. @ Typically, the SQL query used to populate this widget will request two columns
  10641. of data. One column is used as the display data, the other as user data. This is
  10642. done to present a human readable string where a database query needs an
  10643. identification number. By default, column |0| is used in both roles. If this
  10644. is not desired, the methods to change that must be called before specifying the
  10645. query.
  10646. @<SqlComboBox Implementation@>=
  10647. void SqlComboBox::setDataColumn(int column)
  10648. {
  10649. dataColumn = column;
  10650. }
  10651. void SqlComboBox::setDisplayColumn(int column)
  10652. {
  10653. displayColumn = column;
  10654. }
  10655. @ Once the widget is properly configured, we can run the SQL query and populate
  10656. the combo box with the results.
  10657. @<SqlComboBox Implementation@>=
  10658. void SqlComboBox::addSqlOptions(QString query)
  10659. {
  10660. SqlQueryConnection *dbquery = new SqlQueryConnection;
  10661. if(!dbquery->exec(query))
  10662. {
  10663. QSqlError error = dbquery->lastError();
  10664. qDebug() << error.databaseText();
  10665. qDebug() << error.driverText();
  10666. qDebug() << error.text();
  10667. qDebug() << dbquery->lastQuery();
  10668. /* Throw an error here, please. */
  10669. }
  10670. while(dbquery->next())
  10671. {
  10672. QString displayValue(dbquery->value(displayColumn).toString());
  10673. QString dataValue(dbquery->value(dataColumn).toString());
  10674. if(dataColumnShown)
  10675. {
  10676. displayValue.append(QString(" (%1)").arg(dataValue));
  10677. }
  10678. addItem(displayValue, dataValue);
  10679. }
  10680. delete dbquery;
  10681. }
  10682. @ The constructor only needs to initialize some private member data. The
  10683. destructor has even less to do.
  10684. @<SqlComboBox Implementation@>=
  10685. SqlComboBox::SqlComboBox() :
  10686. dataColumn(0), displayColumn(0), dataColumnShown(false)
  10687. {
  10688. /* Nothing needs to be done here. */
  10689. }
  10690. SqlComboBox::~SqlComboBox()
  10691. {
  10692. /* Nothing needs to be done here. */
  10693. }
  10694. @ To use this class as an editor delegate in a model we wrap the class in a
  10695. |QItemDelegate|.
  10696. @<Class declarations@>=
  10697. class SqlComboBoxDelegate : public QItemDelegate@/
  10698. {
  10699. Q_OBJECT@;
  10700. SqlComboBox *delegate;
  10701. public:@/
  10702. SqlComboBoxDelegate(QObject *parent = NULL);
  10703. QWidget *createEditor(QWidget *parent,
  10704. const QStyleOptionViewItem &option,@|
  10705. const QModelIndex &index) const;
  10706. void setEditorData(QWidget *editor, const QModelIndex &index) const;
  10707. void setModelData(QWidget *editor, QAbstractItemModel *model,@|
  10708. const QModelIndex &index) const;
  10709. void setWidget(SqlComboBox *widget);
  10710. virtual QSize sizeHint() const;
  10711. void updateEditorGeometry(QWidget *editor,
  10712. const QStyleOptionViewItem &option,@|
  10713. const QModelIndex &index) const;
  10714. };
  10715. @ Rather than set the values for the combo box through the delegate class, we
  10716. create the editor and pass it in to the delegate.
  10717. @<SqlComboBoxDelegate Implementation@>=
  10718. void SqlComboBoxDelegate::setWidget(SqlComboBox *widget)
  10719. {
  10720. delegate = widget;
  10721. }
  10722. @ When a view requests this delegate, we simply return the widget that was
  10723. previously passed in.
  10724. @<SqlComboBoxDelegate Implementation@>=
  10725. QWidget* SqlComboBoxDelegate::createEditor(QWidget *parent,@|
  10726. const QStyleOptionViewItem &,
  10727. const QModelIndex &) const
  10728. {
  10729. return delegate->clone(parent);
  10730. }
  10731. @ To set the appropriate editor data, we check the value in the model and
  10732. attempt to set the value to match that.
  10733. @<SqlComboBoxDelegate Implementation@>=
  10734. void SqlComboBoxDelegate::setEditorData(QWidget *editor,
  10735. const QModelIndex &index) const
  10736. {
  10737. SqlComboBox *self = qobject_cast<SqlComboBox *>(editor);
  10738. self->setCurrentIndex(self->findData(
  10739. index.model()->data(index,
  10740. Qt::UserRole).toString()));
  10741. }
  10742. @ When setting the model data, we need to specify both the display role and the
  10743. user data role.
  10744. @<SqlComboBoxDelegate Implementation@>=
  10745. void SqlComboBoxDelegate::setModelData(QWidget *editor,@|
  10746. QAbstractItemModel *model,
  10747. const QModelIndex &index) const
  10748. {
  10749. SqlComboBox *self = qobject_cast<SqlComboBox *>(editor);
  10750. model->setData(index, self->itemData(self->currentIndex(), Qt::UserRole),
  10751. Qt::UserRole);
  10752. model->setData(index, self->currentText(), Qt::DisplayRole);
  10753. }
  10754. @ This is needed to play nicely with the model view architecture.
  10755. @<SqlComboBoxDelegate Implementation@>=
  10756. void SqlComboBoxDelegate::updateEditorGeometry(QWidget *editor,
  10757. const QStyleOptionViewItem &option,
  10758. const QModelIndex &) const
  10759. {
  10760. editor->setGeometry(option.rect);
  10761. }
  10762. @ When this delegate is used in a table view, we want to be able to provide a
  10763. size hint that can be used to resize the column in order to fit the delegate.
  10764. @<SqlComboBoxDelegate Implementation@>=
  10765. QSize SqlComboBoxDelegate::sizeHint() const
  10766. {
  10767. return delegate->sizeHint();
  10768. }
  10769. @ Finally, we need a constructor.
  10770. @<SqlComboBoxDelegate Implementation@>=
  10771. SqlComboBoxDelegate::SqlComboBoxDelegate(QObject *parent)
  10772. : QItemDelegate(parent)@/
  10773. {
  10774. /* Nothing needs to be done here. */
  10775. }
  10776. @** The main program.
  10777. The |main()| function is where program execution starts. Most of the work
  10778. required here is taken care of for us by the |Application| object.
  10779. The odd handling of argc is required to prevent segmentation faults in the Linux
  10780. build.
  10781. @<The main program@>=
  10782. int main(int argc, char **argv)@/
  10783. {@/
  10784. int *c = &argc;
  10785. Application app(*c, argv);
  10786. @<Set up icons@>@;
  10787. QSettings settings;
  10788. @<Register device configuration widgets@>@;
  10789. @<Prepare the database connection@>@;
  10790. @<Load the application configuration@>@;
  10791. @<Set up the scripting engine@>@;
  10792. app.engine = engine;
  10793. @<Find and evaluate starting script@>@;
  10794. int retval = app.exec();
  10795. delete engine;
  10796. return retval;@/
  10797. }
  10798. @ \pn{} 1.4 introduces the ability to use icons in certain interface elements.
  10799. Some commonly desired public domain graphics are provided by the Tango Desktop
  10800. Project. We also set an application level default window icon.
  10801. @<Set up icons@>=
  10802. QStringList themeSearchPath = QIcon::themeSearchPaths();
  10803. themeSearchPath.append(":/resources/icons/tango");
  10804. QIcon::setThemeSearchPaths(themeSearchPath);
  10805. QIcon::setThemeName(":/resources/icons/tango");
  10806. app.setWindowIcon(QIcon(":/resources/icons/appicons/logo.svg"));
  10807. @ Some widgets provided by \pn{} require access to a database in order to work.
  10808. To simplify using these widgets, the application will request information
  10809. needed to connect to a database. The use of two distinct |if| blocks rather than
  10810. an |if|$\dots$|else| construction is used because the data from settings can be
  10811. changed if an attempt to connect to the database fails.
  10812. @<Prepare the database connection@>=
  10813. if(settings.value("database/exists", "false").toString() == "true")
  10814. {
  10815. @<Try connecting to the database@>@;
  10816. }
  10817. if(settings.value("database/exists", "false").toString() == "false")
  10818. {
  10819. @<Prompt for database connection information@>@;
  10820. }
  10821. @ In order to connect to the database, we need five pieces of information: the
  10822. name of a database driver (PostgreSQL is recommended for now), the host name of
  10823. the computer running the database, the name of the database, the name of the
  10824. user connecting to the database, and that user's password. This information will
  10825. be stored in the user settings for the application so that the database
  10826. connection can be established without prompting the user next time. A class is
  10827. provided to gather this information.
  10828. @<Class declarations@>=
  10829. class SqlConnectionSetup : public QDialog@/
  10830. {@t\1@>@/
  10831. Q_OBJECT@;
  10832. public:@/
  10833. SqlConnectionSetup();
  10834. ~SqlConnectionSetup();@/
  10835. @t\4@>public slots@t\kern-3pt@>:@/
  10836. void testConnection();
  10837. private:@/
  10838. QFormLayout *formLayout;
  10839. QComboBox *driver;
  10840. QLineEdit *hostname;
  10841. QLineEdit *dbname;
  10842. QLineEdit *user;
  10843. QLineEdit *password;
  10844. QVBoxLayout *layout;
  10845. QHBoxLayout *buttons;
  10846. QPushButton *cancelButton;
  10847. QPushButton *connectButton;@t\2@>@/
  10848. }@t\kern-3pt@>;
  10849. @ The constructor sets up this widget. The destructor does nothing.
  10850. @<SqlConnectionSetup implementation@>=
  10851. SqlConnectionSetup::SqlConnectionSetup() :
  10852. formLayout(new QFormLayout), driver(new QComboBox), hostname(new QLineEdit),
  10853. dbname(new QLineEdit), user(new QLineEdit), password(new QLineEdit),
  10854. layout(new QVBoxLayout), buttons(new QHBoxLayout),
  10855. cancelButton(new QPushButton(tr("Cancel"))),
  10856. connectButton(new QPushButton(tr("Connect")))@/
  10857. {
  10858. driver->addItem("PostgreSQL", "QPSQL");
  10859. formLayout->addRow(tr("Database driver:"), driver);
  10860. formLayout->addRow(tr("Host name:"), hostname);
  10861. formLayout->addRow(tr("Database name:"), dbname);
  10862. formLayout->addRow(tr("User name:"), user);
  10863. password->setEchoMode(QLineEdit::Password);
  10864. formLayout->addRow(tr("Password:"), password);
  10865. layout->addLayout(formLayout);
  10866. buttons->addStretch(1);
  10867. buttons->addWidget(cancelButton);
  10868. connect(cancelButton, SIGNAL(clicked(bool)), this, SLOT(reject()));
  10869. buttons->addWidget(connectButton);
  10870. layout->addLayout(buttons);
  10871. connect(connectButton, SIGNAL(clicked(bool)), this, SLOT(testConnection()));
  10872. setLayout(layout);
  10873. setModal(true);
  10874. }
  10875. SqlConnectionSetup::~SqlConnectionSetup()
  10876. {
  10877. /* Nothing needs to be done here. */
  10878. }
  10879. @ The |testConnection()| method checks if the information provided can be used
  10880. to open a new database connection.
  10881. @<SqlConnectionSetup implementation@>=
  10882. void SqlConnectionSetup::testConnection()
  10883. {
  10884. QSqlDatabase database =
  10885. QSqlDatabase::addDatabase(driver->itemData(driver->currentIndex()).
  10886. toString());
  10887. database.setHostName(hostname->text());
  10888. database.setDatabaseName(dbname->text());
  10889. database.setUserName(user->text());
  10890. database.setPassword(password->text());
  10891. if(database.open())
  10892. {
  10893. QSettings settings;
  10894. settings.setValue("database/exists", "true");
  10895. settings.setValue("database/driver",
  10896. driver->itemData(driver->currentIndex()).toString());
  10897. settings.setValue("database/hostname", hostname->text());
  10898. settings.setValue("database/dbname", dbname->text());
  10899. settings.setValue("database/user", user->text());
  10900. settings.setValue("database/password", password->text());
  10901. accept();
  10902. }
  10903. else
  10904. {
  10905. QMessageBox::information(this, tr("Database connection failed"),
  10906. tr("Failed to connect to database."));
  10907. }
  10908. }
  10909. @ In order to prompt for connection information, we simply create a
  10910. |SqlConnectionSetup| object and call |exec()|. When control returns, the
  10911. settings will either contain appropriate connection information or we have to
  10912. give up on getting that information from the user for now.
  10913. @<Prompt for database connection information@>=
  10914. SqlConnectionSetup dialog;
  10915. dialog.exec();
  10916. @ If we have connected to a database in the previous running of the application,
  10917. we try to connect to the same database automatically rather than prompt the
  10918. user. If the connection attempt fails, we can fall back on asking the user for
  10919. help.
  10920. @<Try connecting to the database@>=
  10921. QSqlDatabase database =
  10922. QSqlDatabase::addDatabase(settings.value("database/driver").toString());
  10923. database.setHostName(settings.value("database/hostname").toString());
  10924. database.setDatabaseName(settings.value("database/dbname").toString());
  10925. database.setUserName(settings.value("database/user").toString());
  10926. database.setPassword(settings.value("database/password").toString());
  10927. if(!database.open())
  10928. {
  10929. settings.setValue("database/exists", "false");
  10930. }
  10931. @** Viewing a record of batches.
  10932. \noindent It is frequently useful to present a table view with the results of a
  10933. SQL query and have a way of interacting with that view to obtain more details
  10934. related to a given record in that table. For this purpose, \pn{} provides a
  10935. widget based on |QTableView| which presents information from a
  10936. |QSqlQueryModel|. The table emits signals when an entry in the table is double
  10937. clicked. One of these contains the data from the first column of that row and
  10938. is suitable for use when a primary key is presented in that column and this is
  10939. sufficient for the desired drill down. The other signal provides the row number
  10940. which can be used along with a reference to the table to obtain the data in any
  10941. column.
  10942. This class also automatically persists column widths when these are changed.
  10943. @<Class declarations@>=
  10944. class SqlQueryView : public QTableView@/
  10945. {@t\1@>@/
  10946. Q_OBJECT@;
  10947. public:@/
  10948. SqlQueryView(QWidget *parent = NULL);
  10949. void setQuery(const QString &query);
  10950. bool setHeaderData(int section, Qt::Orientation@, orientation,
  10951. const QVariant &value, int role);
  10952. Q_INVOKABLE QVariant data(int row, int column,
  10953. int role = Qt::DisplayRole);@/
  10954. signals:@/
  10955. void openEntry(QString key);
  10956. void openEntryRow(int row);@t\2@>@/
  10957. protected:@/
  10958. virtual void showEvent(QShowEvent *event);
  10959. private slots@t\kern-3pt@>:@t\1@>@/
  10960. void openRow(const QModelIndex &index);
  10961. void persistColumnResize(int column, int oldsize, int newsize);@t\2@>@/
  10962. }@t\kern-3pt@>;
  10963. @ The constructor sets up the communication between the model and the view and
  10964. also provides the connection needed to notice when columns change size to
  10965. persist that preference.
  10966. @<SqlQueryView implementation@>=
  10967. SqlQueryView::SqlQueryView(QWidget *parent) : QTableView(parent)
  10968. {
  10969. setModel(new QSqlQueryModel);
  10970. connect(this, SIGNAL(doubleClicked(QModelIndex)),
  10971. this, SLOT(openRow(QModelIndex)));
  10972. connect(horizontalHeader(), SIGNAL(sectionResized(int, int, int)),
  10973. this, SLOT(persistColumnResize(int, int, int)));
  10974. }
  10975. @ Column width persistance requires two methods. First we have a slot
  10976. method which is called when a column width is changed. This is saved with
  10977. |QSettings| under a key utilizing the name of the window, the name of the
  10978. table, and the column number.
  10979. @<SqlQueryView implementation@>=
  10980. void SqlQueryView::persistColumnResize(int column, int, int newsize)
  10981. {
  10982. @<Save updated column size@>@;
  10983. }
  10984. @ The body of this function has been split out so that it can be shared with
  10985. other table views without the need to introduce a new common base class.
  10986. @<Save updated column size@>=
  10987. QSettings settings;
  10988. @<Obtain top level widget@>@;
  10989. settings.setValue(QString("columnWidths/%1/%2/%3").
  10990. arg(topLevelWidget->objectName()).
  10991. arg(objectName()).arg(column),
  10992. QVariant(newsize));
  10993. @ To determine which window a given table is in, we just follow
  10994. |parentWidget()| until there isn't one. It is possible that the table view
  10995. will also be the window, however this is not advised as it is easier for the
  10996. settings key to be non-unique in such a case.
  10997. @<Obtain top level widget@>=
  10998. QWidget *topLevelWidget = this;
  10999. while(topLevelWidget->parentWidget())
  11000. {
  11001. topLevelWidget = topLevelWidget->parentWidget();
  11002. }
  11003. @ We restore column widths in response to a show event. One of these should be
  11004. received just before the widget is shown so the widget should appear correctly.
  11005. @<SqlQueryView implementation@>=
  11006. void SqlQueryView::showEvent(QShowEvent *event)
  11007. {
  11008. @<Restore table column widths@>@;
  11009. event->accept();
  11010. }
  11011. @ Similarly, most of the body of this method has also been split into a chunk
  11012. so that it might be shared with other classes.
  11013. @<Restore table column widths@>=
  11014. QSettings settings;
  11015. @<Obtain top level widget@>
  11016. QString baseKey =
  11017. QString("columnWidths/%1/%2").arg(topLevelWidget->objectName()).
  11018. arg(objectName());
  11019. for(int i = 0; i < model()->columnCount(); i++)
  11020. {
  11021. QString key = QString("%1/%2").arg(baseKey).arg(i);
  11022. if(settings.contains(key))
  11023. {
  11024. setColumnWidth(i, settings.value(key).toInt());
  11025. }
  11026. }
  11027. @ A slot is required for obtaining the information to send out in our signals.
  11028. @<SqlQueryView implementation@>=
  11029. void SqlQueryView::openRow(const QModelIndex &index)
  11030. {
  11031. emit openEntry(((QSqlQueryModel *)model())->record(index.row()).value(0).toString());
  11032. emit openEntryRow(index.row());
  11033. }
  11034. @ The other functions are wrappers around model methods.
  11035. \danger |setQuery()| leaks database connections.
  11036. @<SqlQueryView implementation@>=
  11037. void SqlQueryView::setQuery(const QString &query)
  11038. {
  11039. QSqlDatabase database = AppInstance->database();
  11040. database.open();
  11041. QSqlQuery q(query, database);
  11042. ((QSqlQueryModel*)model())->setQuery(q);
  11043. }
  11044. bool SqlQueryView::setHeaderData(int section, Qt::Orientation@, orientation,
  11045. const QVariant &value, int role)
  11046. {
  11047. return model()->setHeaderData(section, orientation, value, role);
  11048. }
  11049. @ A method is also provided to allow scripts to access the data.
  11050. @<SqlQueryView implementation@>=
  11051. QVariant SqlQueryView::data(int row, int column, int role)
  11052. {
  11053. return model()->data(model()->index(row, column), role);
  11054. }
  11055. @ To use this class, it is useful to expose it to the host environment.
  11056. @<Function prototypes for scripting@>=
  11057. void setSqlQueryViewProperties(QScriptValue value, QScriptEngine *engine);
  11058. QScriptValue constructSqlQueryView(QScriptContext *context,
  11059. QScriptEngine *engine);
  11060. QScriptValue SqlQueryView_setQuery(QScriptContext *context,
  11061. QScriptEngine *engine);
  11062. QScriptValue SqlQueryView_setHeaderData(QScriptContext *context,
  11063. QScriptEngine *engine);
  11064. @ The script constructor is passed to the host environment.
  11065. @<Set up the scripting engine@>=
  11066. constructor = engine->newFunction(constructSqlQueryView);
  11067. value = engine->newQMetaObject(&SqlQueryView::staticMetaObject, constructor);
  11068. engine->globalObject().setProperty("SqlQueryView", value);
  11069. @ Next we construct the view, add properties to access its methods from the host
  11070. environment, and pass that back.
  11071. @<Functions for scripting@>=
  11072. QScriptValue constructSqlQueryView(QScriptContext *, QScriptEngine *engine)
  11073. {
  11074. QScriptValue object = engine->newQObject(new SqlQueryView);
  11075. setSqlQueryViewProperties(object, engine);
  11076. return object;
  11077. }
  11078. void setSqlQueryViewProperties(QScriptValue value, QScriptEngine *engine)
  11079. {
  11080. setQTableViewProperties(value, engine);
  11081. value.setProperty("setHeaderData",
  11082. engine->newFunction(SqlQueryView_setHeaderData));
  11083. value.setProperty("setQuery", engine->newFunction(SqlQueryView_setQuery));
  11084. }
  11085. @ The properties added are simplified wrappers around the class methods.
  11086. @<Functions for scripting@>=
  11087. QScriptValue SqlQueryView_setQuery(QScriptContext *context, QScriptEngine *)
  11088. {
  11089. SqlQueryView *self = getself<SqlQueryView *>(context);
  11090. QString query = argument<QString>(0, context);
  11091. self->setQuery(query);
  11092. self->reset();
  11093. return QScriptValue();
  11094. }
  11095. QScriptValue SqlQueryView_setHeaderData(QScriptContext *context,
  11096. QScriptEngine *)
  11097. {
  11098. SqlQueryView *self = getself<SqlQueryView *>(context);
  11099. int section = argument<int>(0, context);
  11100. QString data = argument<QString>(1, context);
  11101. self->setHeaderData(section, Qt::Horizontal, data, Qt::DisplayRole);
  11102. return QScriptValue();
  11103. }
  11104. @** Reporting.
  11105. \noindent \pn{} version 1.4 added a new type of menu which is designed to
  11106. handle reports. This makes extensive use of the previously existing reporting
  11107. system at present which makes modifying existing reports to work with the new
  11108. system very simple. Further changes may be introduced in the future that
  11109. substantially depart from this in order to simplify report files.
  11110. Previously to add a new report to a configuration, you needed to create the
  11111. report, add an {\tt <include>} tag in the main configuration file to bring that
  11112. report into the application configuration, then in any window with a Reports
  11113. menu you would need to add the report to that menu in its configuration file
  11114. and write a small bit of JavaScript to obtain a reference to that new menu
  11115. item and create the report when that menu item is triggered. This is highly
  11116. repetetive, error prone, and with the new approach it is not needed at all.
  11117. To add a new report to a configuration using the new approach one need only
  11118. save the new report file in the appropriate directory and \pn{} will detect
  11119. this, add it to any Reports menus that may exist, and handle all of the details
  11120. of generating these reports on demand.
  11121. The Reports menu is created in a configuration as a {\tt <menu>} element with
  11122. three attributes. The {\tt name} attribute as usual is the name of the menu
  11123. item. The {\tt type} attribute will have a value of {\tt "reports"} and the
  11124. {\tt src} attribute will indicate the directory to search for reports to
  11125. populate that menu. This allows for multiple Reports menus with different
  11126. reports in each menu if desired.
  11127. Reports are added to the menu in the order of the file names in the reports
  11128. directory.
  11129. \danger While it should not be an issue with the limited number of reports
  11130. presently distributed with Typica, the approach taken to implementing this menu
  11131. type is highly inefficient. There are many optimizations available if this
  11132. becomes problematic.\endanger
  11133. @<Populate reports menu@>=
  11134. QSettings settings;
  11135. QDir directory(QString("%1/%2").arg(settings.value("config").toString()).
  11136. arg(element.attribute("src")));
  11137. directory.setFilter(QDir::Files);
  11138. directory.setSorting(QDir::Name);
  11139. QStringList nameFilter;
  11140. nameFilter << "*.xml";
  11141. directory.setNameFilters(nameFilter);
  11142. QFileInfoList reportFiles = directory.entryInfoList();
  11143. for(int i = 0; i < reportFiles.size(); i++)
  11144. {
  11145. QFileInfo reportFile = reportFiles.at(i);
  11146. @<Add report to reports menu@>@;
  11147. }
  11148. @ The menu items themselves are a subclass of |QAction| which holds all of the
  11149. information needed to respond to its activation by generating the appropriate
  11150. report.
  11151. @<Class declarations@>=
  11152. class ReportAction : public QAction
  11153. {
  11154. Q_OBJECT
  11155. public:
  11156. ReportAction(const QString &fileName, const QString &reportName,
  11157. QObject *parent = NULL);
  11158. private slots:
  11159. void createReport();
  11160. private:
  11161. QString reportFile;
  11162. };
  11163. @ The constructor receives the name of the report file which is used to
  11164. generate the report when needed and the name of the report which is used as the
  11165. name presented in the menu.
  11166. @<ReportAction implementation@>=
  11167. ReportAction::ReportAction(const QString &fileName, const QString &reportName,
  11168. QObject *parent) :
  11169. QAction(reportName, parent), reportFile(fileName)
  11170. {
  11171. connect(this, SIGNAL(triggered()), this, SLOT(createReport()));
  11172. }
  11173. @ The slot method is responsible for creating the new report. This is very
  11174. similar to the old approach and reuses much of the same code. Of particular
  11175. note is the |targetID| variable. This is set to facilitate window geometry
  11176. management, though this should probably be set from the {\tt id} attribute
  11177. of the {\tt <window>} element in the file to preserve window geometry
  11178. settings if the configuration is moved to another location in the file
  11179. system.
  11180. @<ReportAction implementation@>=
  11181. void ReportAction::createReport()
  11182. {
  11183. QFile file(reportFile);
  11184. QDomDocument document;
  11185. if(file.open(QIODevice::ReadOnly))
  11186. {
  11187. document.setContent(&file, true);
  11188. QDomElement element = document.documentElement();
  11189. QScriptEngine *engine = AppInstance->engine;
  11190. QScriptContext *context = engine->pushContext();
  11191. QScriptValue object;
  11192. QString targetID = reportFile;
  11193. @<Display the window@>@;
  11194. file.close();
  11195. engine->popContext();
  11196. }
  11197. }
  11198. @ With the |ReportAction| available, we are now ready to add reports to the
  11199. Reports menu. To do this we check each file in the given directory to determine
  11200. if it is a report file, obtain the report title and location within the menu
  11201. hierarchy from the file data, create the actions, and add them to the menu.
  11202. @<Add report to reports menu@>=
  11203. QString path = reportFile.absoluteFilePath();
  11204. QFile file(path);
  11205. if(file.open(QIODevice::ReadOnly))
  11206. {
  11207. QDomDocument document;
  11208. document.setContent(&file, true);
  11209. QDomElement root = document.documentElement();
  11210. QDomNode titleNode = root.elementsByTagName("reporttitle").at(0);
  11211. if(!titleNode.isNull())
  11212. {
  11213. QDomElement titleElement = titleNode.toElement();
  11214. QString title = titleElement.text();
  11215. if(!title.isEmpty())
  11216. {
  11217. QStringList hierarchy = title.split(":->");
  11218. QMenu *insertionPoint = menu;
  11219. @<Traverse report menu hierarchy@>
  11220. ReportAction *action = new ReportAction(path, hierarchy.last());
  11221. insertionPoint->addAction(action);
  11222. }
  11223. }
  11224. }
  11225. @ \pn{} allows the Reports menu to contain arbitrarily deep menu hierarchies.
  11226. It is advised to keep these hierarchies shallow.
  11227. @<Traverse report menu hierarchy@>=
  11228. for(int j = 0; j < hierarchy.size() - 1; j++)
  11229. {
  11230. QObjectList menuList = insertionPoint->children();
  11231. bool menuFound = false;
  11232. for(int k = 0; k < menuList.size(); k++)
  11233. {
  11234. QMenu *currentItem = qobject_cast<QMenu*>(menuList.at(k));
  11235. if(currentItem)
  11236. {
  11237. if(currentItem->title() == hierarchy.at(j))
  11238. {
  11239. menuFound = true;
  11240. insertionPoint = currentItem;
  11241. break;
  11242. }
  11243. }
  11244. }
  11245. if(!menuFound)
  11246. {
  11247. insertionPoint = insertionPoint->addMenu(hierarchy.at(j));
  11248. }
  11249. }
  11250. @ \noindent The reporting functionality in \pn{} is based on the Scribe framework
  11251. in Qt. This brings several benefits, including making it easy to print reports
  11252. or save reports as plain text or HTML.
  11253. Reports are specified in the \pn{}'s configuration document and can include both
  11254. static elements and elements that are populated by external data such as the
  11255. result of a SQL query.
  11256. @<Function prototypes for scripting@>=
  11257. void addReportToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  11258. QStack<QLayout *> *layoutStack);
  11259. @ When adding a report to a layout, we must not only add the widget to the
  11260. layout, but also construct the document.
  11261. @<Functions for scripting@>=
  11262. void addReportToLayout(QDomElement element, QStack<QWidget *> *,@|
  11263. QStack<QLayout *> *layoutStack)
  11264. {
  11265. QTextEdit *widget = new QTextEdit;
  11266. if(element.hasAttribute("id"))
  11267. {
  11268. widget->setObjectName(element.attribute("id"));
  11269. }
  11270. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  11271. layout->addWidget(widget);
  11272. QTextDocument *document = new QTextDocument;
  11273. QFont defaultFont;
  11274. defaultFont.setPointSize(11);
  11275. document->setDefaultFont(defaultFont);
  11276. QTextCursor cursor(document);
  11277. @<Construct report document@>@;
  11278. widget->setDocument(document);
  11279. }
  11280. @ Several child elements are allowed under the {\tt <report>} element. These
  11281. should be processed in order to produce the final report document.
  11282. @<Construct report document@>=
  11283. QDomNodeList children = element.childNodes();
  11284. for(int i = 0; i < children.count(); i++)
  11285. {
  11286. QDomNode current;
  11287. QDomElement currentElement;
  11288. current = children.at(i);
  11289. if(current.isElement())
  11290. {
  11291. currentElement = current.toElement();
  11292. @<Process report document elements@>@;
  11293. }
  11294. }
  11295. @ If any custom styling for HTML content is required, a {\tt <style>} element
  11296. should be placed in the report description before any such content.
  11297. @<Process report document elements@>=
  11298. if(currentElement.tagName() == "style")
  11299. {
  11300. document->setDefaultStyleSheet(currentElement.text());
  11301. }
  11302. @ One common need is the ability to insert static text, such as the title of the
  11303. report. In order to simplify formatting, the text can be interpreted as HTML.
  11304. Note that to avoid having HTML tags eaten by the parser, the text of this
  11305. element should be a CDATA section.
  11306. @<Process report document elements@>=
  11307. if(currentElement.tagName() == "html")
  11308. {
  11309. cursor.insertHtml(currentElement.text());
  11310. }
  11311. @ If no special formatting is needed, a plain text element can be used. This
  11312. might be extended in the future to allow attributes for specifying the character
  11313. formatting to be used with the text.
  11314. @<Process report document elements@>=
  11315. if(currentElement.tagName() == "text")
  11316. {
  11317. cursor.insertText(currentElement.text());
  11318. }
  11319. @ One of the more interesting elements of a report is the {\tt <table>} element.
  11320. This is an element which can change its contents in response to changes in user
  11321. controls.
  11322. @<Process report document elements@>=
  11323. if(currentElement.tagName() == "table")
  11324. {
  11325. QTextFrame *frame = cursor.insertFrame(QTextFrameFormat());
  11326. ReportTable *table = new ReportTable(frame, currentElement);
  11327. table->setParent(widget);
  11328. if(currentElement.hasAttribute("id"))
  11329. {
  11330. table->setObjectName(currentElement.attribute("id"));
  11331. }
  11332. }
  11333. @ The |ReportTable| class is responsible for parsing {\tt <table>} child
  11334. elements and inserting the table into the document at the correct location.
  11335. @<Class declarations@>=
  11336. class ReportTable : public QObject@/
  11337. {@t\1@>@/
  11338. Q_OBJECT@;
  11339. QTextFrame *area;
  11340. QDomElement configuration;
  11341. QMap<QString, QVariant> bindings;
  11342. public:@/
  11343. ReportTable(QTextFrame *frame, QDomElement description);
  11344. ~ReportTable();
  11345. @[Q_INVOKABLE@,@, void@]@, bind(QString placeholder, QVariant value);@t\2\2@>@/
  11346. @t\4@>public slots@t\kern-3pt@>:@/
  11347. void refresh();@t\2@>@/
  11348. }@t\kern-3pt@>;
  11349. @ The |ReportTable| class takes a |QTextFrame| and |QDomElement| pointer in
  11350. its constructor. The former is used to establish the bounds of the table within
  11351. a document and the latter is used for generating the table contents.
  11352. @<ReportTable implementation@>=
  11353. ReportTable::ReportTable(QTextFrame *frame, QDomElement description) :
  11354. area(frame), configuration(description)
  11355. {
  11356. refresh();
  11357. }
  11358. ReportTable::~ReportTable()
  11359. {
  11360. }
  11361. @ In order to change the table contents based on user controls, the |bind()|
  11362. method allows a placeholder to be replaced with a value when evaluating a SQL
  11363. query.
  11364. @<ReportTable implementation@>=
  11365. void ReportTable::bind(QString placeholder, QVariant value)
  11366. {
  11367. bindings.insert(placeholder, value);
  11368. }
  11369. @ All of the interesting work is done in the |refresh()| slot. This method
  11370. deletes the current content of the frame and creates a table based on the
  11371. description of the table in the configuration document.
  11372. @<ReportTable implementation@>=
  11373. void ReportTable::refresh()
  11374. {
  11375. @<Delete current report table content@>@;
  11376. int rows = 1;
  11377. int columns = 1;
  11378. int currentRow = 0;
  11379. QTextTable *table = cursor.insertTable(rows, columns);
  11380. @<Set table formatting@>@;
  11381. @<Reconstruct report table content@>@;
  11382. if(rows > 1)
  11383. {
  11384. table->removeRows(0, 1);
  11385. }
  11386. }
  11387. @ Deleting the current content of the table involves using a cursor to select
  11388. everything in the frame and then removing that selection. There are more optimal
  11389. ways to do this but if there are performance problems with this, you may want to
  11390. reconsider what you are trying to do.
  11391. @<Delete current report table content@>=
  11392. QTextCursor cursor = area->firstCursorPosition();
  11393. while(cursor < area->lastCursorPosition())
  11394. {
  11395. cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
  11396. }
  11397. cursor.removeSelectedText();
  11398. @ When creating a new table, we may need to alter the formatting of that table.
  11399. To do this, we get the current format, modify that based on attributes of the
  11400. {\tt <table>} element, and apply the modified copy to the newly constructed
  11401. table.
  11402. @<Set table formatting@>=
  11403. QTextTableFormat format = table->format();
  11404. format.setBorderStyle(QTextFrameFormat::BorderStyle_None);
  11405. if(configuration.hasAttribute("align"))
  11406. {
  11407. if(configuration.attribute("align") == "center")
  11408. {
  11409. format.setAlignment(Qt::AlignHCenter);
  11410. }
  11411. }
  11412. table->setFormat(format);
  11413. @ To reconstruct the table, we need to parse the description of the table.
  11414. @<Reconstruct report table content@>=
  11415. QDomNodeList children = configuration.childNodes();
  11416. for(int i = 0; i < children.count(); i++)
  11417. {
  11418. QDomNode current;
  11419. QDomElement currentElement;
  11420. current = children.at(i);
  11421. if(current.isElement())
  11422. {
  11423. currentElement = current.toElement();
  11424. if(currentElement.tagName() == "query")
  11425. {
  11426. @<Add SQL query results to report table@>@;
  11427. }
  11428. else if(currentElement.tagName() == "row")
  11429. {
  11430. @<Add new row to report table@>@;
  11431. }
  11432. }
  11433. }
  11434. @ The text of a {\tt <query>} element will be the query desired in the table.
  11435. This might include placeholders that must be bound to values before the query is
  11436. executed. If query execution results in an error (as it will if it contains
  11437. placeholders that have not yet had values bound to them), there will be no
  11438. change to the table and the next child element, if any, will be processed.
  11439. @<Add SQL query results to report table@>=
  11440. SqlQueryConnection query;
  11441. query.prepare(currentElement.text());
  11442. foreach(QString key, bindings.uniqueKeys())
  11443. {
  11444. if(currentElement.text().contains(key))
  11445. {
  11446. query.bindValue(key, bindings.value(key));
  11447. }
  11448. }
  11449. query.exec();
  11450. if(!query.next())
  11451. {
  11452. continue;
  11453. }
  11454. if(query.record().count() > columns)
  11455. {
  11456. table->appendColumns(query.record().count() - columns);
  11457. }
  11458. do
  11459. {
  11460. table->appendRows(1);
  11461. rows++;
  11462. currentRow++;
  11463. for(int j = 0; j < query.record().count(); j++)
  11464. {
  11465. QTextTableCell cell = table->cellAt(currentRow, j);
  11466. cursor = cell.firstCursorPosition();
  11467. cursor.insertText(query.value(j).toString());
  11468. }
  11469. } while(query.next());
  11470. @ It is sometimes desirable to add fixed data such as column headers to a table.
  11471. This is done with the {\tt <row>} element.
  11472. Technically, this isn't needed. The same results can be produced by using a
  11473. {\tt <query>} element to select constant data, but this approach saves a trip to
  11474. the database.
  11475. @<Add new row to report table@>=
  11476. table->appendRows(1);
  11477. currentRow++;
  11478. rows++;
  11479. QDomNodeList rowChildren = currentElement.childNodes();
  11480. int currentColumn = 0;
  11481. for(int j = 0; j < rowChildren.count(); j++)
  11482. {
  11483. QDomNode node;
  11484. QDomElement nodeElement;
  11485. node = rowChildren.at(j);
  11486. if(node.isElement())
  11487. {
  11488. nodeElement = node.toElement();
  11489. if(nodeElement.tagName() == "cell")
  11490. {
  11491. if(currentColumn == columns)
  11492. {
  11493. table->appendColumns(1);
  11494. columns++;
  11495. }
  11496. QTextTableCell cell = table->cellAt(currentRow, currentColumn);
  11497. cursor = cell.firstCursorPosition();
  11498. cursor.insertText(nodeElement.text());
  11499. currentColumn++;
  11500. }
  11501. }
  11502. }
  11503. @ In order to expose report printing capabilities, we provide a property on
  11504. |QTextEdit| objects to handle this.
  11505. @<Function prototypes for scripting@>=
  11506. void setQTextEditProperties(QScriptValue value, QScriptEngine *engine);
  11507. QScriptValue QTextEdit_print(QScriptContext *context, QScriptEngine *engine);
  11508. @ This function is a trivial adaptation from the Qt documentation.
  11509. @<Functions for scripting@>=
  11510. QScriptValue QTextEdit_print(QScriptContext *context, QScriptEngine *)
  11511. {
  11512. QTextEdit *self = getself<QTextEdit *>(context);
  11513. QTextDocument *document = self->document();
  11514. QPrinter printer;
  11515. QPrintDialog printwindow(&printer, self);
  11516. if(printwindow.exec() != QDialog::Accepted)
  11517. {
  11518. return QScriptValue();
  11519. }
  11520. document->print(&printer);
  11521. return QScriptValue();
  11522. }
  11523. @ The host environment must be informed of this function.
  11524. @<Functions for scripting@>=
  11525. void setQTextEditProperties(QScriptValue value, QScriptEngine *engine)
  11526. {
  11527. setQAbstractScrollAreaProperties(value, engine);
  11528. value.setProperty("print", engine->newFunction(QTextEdit_print));
  11529. }
  11530. @** An area for repeated user interface elements.
  11531. \noindent There are multiple use cases in which it is useful to specify a
  11532. complex aggregation of user interface elements to be repeated arbitrarily many
  11533. times. For example, placing multiple copies of a cupping form in a single area
  11534. for conveniently entering observations for all coffees in a particular session
  11535. or providing any number of copies of the form for entering coffee purchase
  11536. information. The |FormArray| widget provides this capability, allowing the
  11537. XML portion of the configuration document to specify the form once and allowing
  11538. the host environment to access the copies.
  11539. Slots and the |Q_INVOKABLE| macro are used to simplify the use of this class
  11540. from the host environment.
  11541. @<Class declarations@>=
  11542. class FormArray : public QScrollArea@/
  11543. {@t\1@>@/
  11544. Q_OBJECT@;
  11545. QDomElement configuration;
  11546. QWidget itemContainer;
  11547. QVBoxLayout itemLayout;
  11548. int maxwidth;
  11549. int maxheight;
  11550. public:@/
  11551. FormArray(QDomElement description);
  11552. @[Q_INVOKABLE@,@, QWidget*@] elementAt(int index);@t\2\2@>@/
  11553. @[Q_INVOKABLE@,@, int@] elements();@t\2\2@>@/
  11554. @t\4@>public slots@t\kern-3pt@>:@/
  11555. void addElements(int copies = 1);
  11556. void removeAllElements();
  11557. void setMaximumElementWidth(int width);
  11558. void setMaximumElementHeight(int height);@t\2@>@/
  11559. }@t\kern-3pt@>;
  11560. @ The |FormArray| is just a |QScrollArea| providing a view onto a |QWidget|
  11561. containing a layout which has arbitrarily many copies of a |QWidget| with
  11562. contents determined by the configuration document used to create the
  11563. |FormArray|.
  11564. @<FormArray implementation@>=
  11565. FormArray::FormArray(QDomElement description) : configuration(description),
  11566. maxwidth(-1), maxheight(-1)@/
  11567. {
  11568. setWidget(&itemContainer);
  11569. itemContainer.setLayout(&itemLayout);
  11570. }
  11571. @ The |FormArray| was initially created by an XML element. A copy of this is
  11572. stored in the private variable |configuration|. This can have the same child
  11573. elements as {\tt <widget>}, allowing us to reuse the function for creating
  11574. populating the widget. When adding a new element, we must resize the
  11575. |itemContainer|, otherwise Qt will attempt to cram all widgets in the layout
  11576. into the same vertical space as was previously required. The result is not
  11577. attractive. We also set a minimum width just in case the newly created widget is
  11578. the first one added to the area.
  11579. @<FormArray implementation@>=
  11580. void FormArray::addElements(int copies)
  11581. {
  11582. QStack<QWidget *> *widgetStack = new QStack<QWidget *>;
  11583. QStack<QLayout *> *layoutStack = new QStack<QLayout *>;
  11584. QWidget *widget;
  11585. for(int i = 0; i < copies; i++)
  11586. {
  11587. widget = new QWidget;
  11588. if(maxwidth > -1)
  11589. {
  11590. widget->setMaximumWidth(maxwidth);
  11591. }
  11592. if(maxheight > -1)
  11593. {
  11594. widget->setMaximumHeight(maxheight);
  11595. }
  11596. if(configuration.hasChildNodes())
  11597. {
  11598. widgetStack->push(widget);
  11599. populateWidget(configuration, widgetStack, layoutStack);
  11600. widgetStack->pop();
  11601. widget->setMinimumHeight(widget->sizeHint().height());
  11602. itemLayout.addWidget(widget);
  11603. if(widget->sizeHint().height() > maxheight && maxheight > -1)
  11604. {
  11605. itemContainer.setMinimumHeight(maxheight * elements() + 50);
  11606. }
  11607. else
  11608. {
  11609. itemContainer.setMinimumHeight(itemContainer.sizeHint().height()
  11610. + widget->sizeHint().height());
  11611. }
  11612. if(maxwidth > -1)
  11613. {
  11614. itemContainer.setMinimumWidth(maxwidth + 50);
  11615. }
  11616. else
  11617. {
  11618. itemContainer.setMinimumWidth(widget->sizeHint().width() + 50);
  11619. }
  11620. }
  11621. }
  11622. }
  11623. @ In order to retrieve a widget from the area, we use the |elementAt()| method.
  11624. The pointer returned by this function can be used as the first argument to
  11625. |findChildObject()| in the host environment in order to find any widget in the
  11626. form.
  11627. @<FormArray implementation@>=
  11628. QWidget* FormArray::elementAt(int index)
  11629. {
  11630. if(index < itemLayout.count())
  11631. {
  11632. QLayoutItem *item = itemLayout.itemAt(index);
  11633. return item->widget();
  11634. }
  11635. else
  11636. {
  11637. return NULL;
  11638. }
  11639. }
  11640. @ Removing all elements is trivial, however we must be sure to reset the size of
  11641. |itemContainer|.
  11642. @<FormArray implementation@>=
  11643. void FormArray::removeAllElements()
  11644. {
  11645. while(itemLayout.count() > 0)
  11646. {
  11647. QLayoutItem *item;
  11648. item = itemLayout.itemAt(0);
  11649. item->widget()->hide();
  11650. itemLayout.removeWidget(item->widget());
  11651. }
  11652. itemContainer.setMinimumHeight(0);
  11653. }
  11654. @ This just leaves a method for determining the number of elements already in
  11655. the view. This is equal to the number of items in the layout.
  11656. @<FormArray implementation@>=
  11657. int FormArray::elements()
  11658. {
  11659. return itemLayout.count();
  11660. }
  11661. @ Some widgets do not behave well in a |FormArray| setting and will try to use
  11662. an excess of screen space. In these cases, constraining the size of the elements
  11663. can be beneficial. These just set private member variables which are used when
  11664. adding new elements.
  11665. @<FormArray implementation@>=
  11666. void FormArray::setMaximumElementWidth(int width)
  11667. {
  11668. maxwidth = width;
  11669. }
  11670. void FormArray::setMaximumElementHeight(int height)
  11671. {
  11672. maxheight = height;
  11673. }
  11674. @ In order to create an instance of this class from the configuration document,
  11675. a {\tt <formarray>} element is used. This can be added to any layout.
  11676. @<Function prototypes for scripting@>=
  11677. void addFormArrayToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  11678. QStack<QLayout *> *layoutStack);
  11679. @ Processing child elements is deferred until a call to
  11680. |FormArray::addElements()| has been made.
  11681. @<Functions for scripting@>=
  11682. void addFormArrayToLayout(QDomElement element, QStack<QWidget *> *,@|
  11683. QStack<QLayout *> *layoutStack)
  11684. {
  11685. FormArray *widget = new FormArray(element);
  11686. if(element.hasAttribute("id"))
  11687. {
  11688. widget->setObjectName(element.attribute("id"));
  11689. }
  11690. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  11691. layout->addWidget(widget);
  11692. }
  11693. @** Scale widgets.
  11694. \noindent One of the most commonly used methods of documenting the properties of
  11695. a coffee is through a cupping form. Several such forms exist to meet different
  11696. needs, however most involve several scales which can be marked to determine some
  11697. aspect of a particular attribute. Some of these scales are scored values which,
  11698. when considered with other scored values produce a numerical representation of
  11699. the quality of a given coffee. Others are unscored values which serve to provide
  11700. additional documentation of a property. For example, when the SCAA cupping form
  11701. expanded to the current form of ten scored properties with defects subtracted
  11702. from the total, a second scale was added for the acidity property. The scored
  11703. scale is used for marking the quality of the acidity while another unscored
  11704. scale is used for marking the intensity of that acidity.
  11705. Previously, in order to enter cupping information in \pn{}, numeric entry fields
  11706. were used. While this was very efficient for transcribing paper cupping forms
  11707. (and this was, in fact, the principal use case for our prototype cupping form
  11708. database software), it is not a form that lends itself to convenient use at the
  11709. cupping table.
  11710. Two new widgets are therefore introduced which allows a cupper to simply click
  11711. at some point on the scale to record that impression. Unfortunately, this is
  11712. still something of a tradeoff. It is not quite so efficient as using a paper
  11713. form in my experience, however it is faster than transcribing a stack of cupping
  11714. forms, particularly when working with cuppers with ambiguous handwriting. By
  11715. moving data acquisition to the point of data generation, a more useful record
  11716. can be produced for use in aggregate analysis.
  11717. @* The Horizontal Scale.
  11718. \noindent Several cupping forms make use of 10 point scales for the quality of
  11719. various attributes. The |ScaleControl| widget provides such a scale. It
  11720. consists of a bar with major ticks at 0, 5, and 10 and minor ticks at integer
  11721. values within this range. The first click sets both the initial and final value
  11722. of the scale while subsequent clicks adjust only the final value. A pair of
  11723. controls at each end of the scale allows the user to adjust either of these
  11724. values to compensate for imprecision at the point of the click. The two values,
  11725. an initial unscored value and a final scored value, provide some limited
  11726. temporal documentation. That is, it documents how the perception of a coffee
  11727. changes as it cools.
  11728. The widget is implemented as a |QGraphicsView| subclass. Please note that the
  11729. scale widgets are not particularly robust. In order to support a broader range
  11730. of cupping forms, there are plans to extend this class to allow user defined
  11731. range and tick patterns and user defined colors for the indicators.
  11732. @<Class declarations@>=
  11733. class ScaleControl : public QGraphicsView@/
  11734. {@t\1@>@/
  11735. Q_OBJECT@/
  11736. Q_PROPERTY(double initialValue READ initialValue WRITE setInitialValue)@/
  11737. Q_PROPERTY(double finalValue READ finalValue WRITE setFinalValue)@/
  11738. @<ScaleControl private members@>@t\2\2@>@/
  11739. public:@/
  11740. ScaleControl();
  11741. double initialValue(void);
  11742. double finalValue(void);
  11743. virtual QSize sizeHint() const;@/
  11744. @[public slots@]:@/
  11745. void setInitialValue(double value);
  11746. void setFinalValue(double value);@/
  11747. signals:@/
  11748. void initialChanged(double);
  11749. void finalChanged(double);@/
  11750. protected:@/
  11751. virtual void mousePressEvent(QMouseEvent *event);
  11752. virtual void mouseReleaseEvent(QMouseEvent *event);@t\2@>@/
  11753. }@t\kern-4pt@>;
  11754. @ The private variables available to instances of this class are used for
  11755. managing various aspects of the widget.
  11756. @<ScaleControl private members@>=
  11757. QGraphicsScene scene;
  11758. QGraphicsPolygonItem initialDecrement;
  11759. QGraphicsPolygonItem initialIncrement;
  11760. QGraphicsPolygonItem finalDecrement;
  11761. QGraphicsPolygonItem finalIncrement;
  11762. QGraphicsPolygonItem initialIndicator;
  11763. QGraphicsPolygonItem finalIndicator;
  11764. QGraphicsPathItem scaleLine;
  11765. QPolygonF left;
  11766. QPolygonF right;
  11767. QPolygonF down;
  11768. QPolygonF up;
  11769. QPainterPath scalePath;
  11770. QBrush initialBrush;
  11771. QBrush finalBrush;
  11772. double nonScoredValue;
  11773. double scoredValue;
  11774. bool initialSet;
  11775. bool finalSet;
  11776. bool scaleDown;
  11777. @ The constructor sets up the scene displayed by this widget. There is
  11778. considerable room for improvement here.
  11779. @<ScaleControl implementation@>=
  11780. ScaleControl::ScaleControl() : QGraphicsView(NULL, NULL), nonScoredValue(-1),
  11781. scoredValue(-1), initialSet(false), finalSet(false), scaleDown(false)
  11782. {
  11783. left << QPointF(0, 5) << QPointF(10, 0) << QPointF(10, 10) <<
  11784. QPointF(0, 5);
  11785. right << QPointF(10, 5) << QPointF(0, 0) << QPointF(0, 10) <<
  11786. QPointF(10, 5);
  11787. down << QPointF(0, 0) << QPointF(-5, -10) << QPointF(5, -10) <<
  11788. QPointF(0, 0);
  11789. up << QPointF(0, 0) << QPointF(-5, 10) << QPointF(4, 10) << QPointF(0, 0);
  11790. initialBrush.setColor(QColor(170, 170, 255));
  11791. initialBrush.setStyle(Qt::SolidPattern);
  11792. finalBrush.setColor(Qt::blue);
  11793. finalBrush.setStyle(Qt::SolidPattern);
  11794. initialDecrement.setPolygon(left);
  11795. initialDecrement.setBrush(initialBrush);
  11796. initialDecrement.setPos(0, 0);
  11797. scene.addItem(&initialDecrement);
  11798. initialIncrement.setPolygon(right);
  11799. initialIncrement.setBrush(initialBrush);
  11800. initialIncrement.setPos(122, 0);
  11801. scene.addItem(&initialIncrement);
  11802. finalDecrement.setPolygon(left);
  11803. finalDecrement.setBrush(finalBrush);
  11804. finalDecrement.setPos(0, 12);
  11805. scene.addItem(&finalDecrement);
  11806. finalIncrement.setPolygon(right);
  11807. finalIncrement.setBrush(finalBrush);
  11808. finalIncrement.setPos(122, 12);
  11809. scene.addItem(&finalIncrement);
  11810. scalePath.moveTo(0, 10);
  11811. scalePath.lineTo(100, 10);
  11812. scalePath.moveTo(0, 0);
  11813. scalePath.lineTo(0, 20);
  11814. scalePath.moveTo(10, 5);
  11815. scalePath.lineTo(10, 15);
  11816. scalePath.moveTo(20, 5);
  11817. scalePath.lineTo(20, 15);
  11818. scalePath.moveTo(30, 5);
  11819. scalePath.lineTo(30, 15);
  11820. scalePath.moveTo(40, 5);
  11821. scalePath.lineTo(40, 15);
  11822. scalePath.moveTo(50, 0);
  11823. scalePath.lineTo(50, 20);
  11824. scalePath.moveTo(60, 5);
  11825. scalePath.lineTo(60, 15);
  11826. scalePath.moveTo(70, 5);
  11827. scalePath.lineTo(70, 15);
  11828. scalePath.moveTo(80, 5);
  11829. scalePath.lineTo(80, 15);
  11830. scalePath.moveTo(90, 5);
  11831. scalePath.lineTo(90, 15);
  11832. scalePath.moveTo(100, 0);
  11833. scalePath.lineTo(100, 20);
  11834. scaleLine.setPath(scalePath);
  11835. scaleLine.setPos(16, 1);
  11836. scene.addItem(&scaleLine);
  11837. setScene(&scene);
  11838. initialIndicator.setPolygon(down);
  11839. initialIndicator.setBrush(initialBrush);
  11840. finalIndicator.setPolygon(up);
  11841. finalIndicator.setBrush(finalBrush);
  11842. setMinimumSize(sizeHint());
  11843. setMaximumSize(sizeHint());
  11844. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  11845. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  11846. setMinimumSize(sizeHint());
  11847. }
  11848. @ The size hint forces a smaller representation of the widget, making it easier
  11849. to arrange with other widgets.
  11850. @<ScaleControl implementation@>=
  11851. QSize ScaleControl::sizeHint() const
  11852. {
  11853. return QSize(140, 30);
  11854. }
  11855. @ The methods for setting the values represented on the scale must ensure that
  11856. the appropriate indicator is drawn and position it appropriately.
  11857. @<ScaleControl implementation@>=
  11858. void ScaleControl::setInitialValue(double value)@t\2\2@>@/
  11859. {@t\1@>@/
  11860. if(value >= 0 && value <= 10)@/
  11861. {@t\1@>@/
  11862. nonScoredValue = value;
  11863. if(!initialSet)
  11864. {
  11865. scene.addItem(&initialIndicator);
  11866. }
  11867. initialSet = true;
  11868. initialIndicator.setPos(value * 10 + 16, 10);
  11869. emit initialChanged(value);
  11870. if(!finalSet)
  11871. {
  11872. setFinalValue(value);
  11873. }@t\2@>@/
  11874. }@t\2@>@/
  11875. }@/@/
  11876. void ScaleControl::setFinalValue(double value)@t\2\2@>@/
  11877. {@t\1@>@/
  11878. if(value >= 0 && value <= 10)@/
  11879. {@t\1@>@/
  11880. scoredValue = value;
  11881. if(!finalSet)@/
  11882. {
  11883. scene.addItem(&finalIndicator);
  11884. }
  11885. finalSet = true;
  11886. finalIndicator.setPos(value * 10 + 16, 11);
  11887. emit finalChanged(value);@t\2@>@/
  11888. }@t\2@>@/
  11889. }
  11890. @ These values can, of course, be retrieved programmatically.
  11891. @<ScaleControl implementation@>=
  11892. double ScaleControl::initialValue(void)
  11893. {
  11894. return nonScoredValue;
  11895. }
  11896. double ScaleControl::finalValue(void)
  11897. {
  11898. return scoredValue;
  11899. }
  11900. @ This only leaves the matter of handling interaction with the widget. A future
  11901. version of this class might split the various interface elements in the scene
  11902. into distinct classes capable of using the event propagation capabilities
  11903. provided by the graphics view framework, however with the current design, we
  11904. must do a little more work.
  11905. There are two events which must be accepted in order to register a click on a
  11906. given portion of the scale. One event is generated when the mouse button is
  11907. pressed.
  11908. @<ScaleControl implementation@>=
  11909. void ScaleControl::mousePressEvent(QMouseEvent *event)@t\2\2@>@/
  11910. {@t\1@>@/
  11911. @<Check that the left button was pressed@>@;
  11912. scaleDown = true;
  11913. event->accept();@t\2@>@/
  11914. }
  11915. @ The primary action button on the mouse is the left button. While there might
  11916. be sensible interactions to provide in response to other buttons, these are not
  11917. presently supported.
  11918. @<Check that the left button was pressed@>=
  11919. if(event->button() != Qt::LeftButton)
  11920. {
  11921. event->ignore();
  11922. return;
  11923. }
  11924. @ Most of the click event handling is done in response to releasing the mouse
  11925. button. In this event handler we must determine if the click occurred in a
  11926. clickable portion of the scale and take the appropriate action in response.
  11927. @<ScaleControl implementation@>=
  11928. void ScaleControl::mouseReleaseEvent(QMouseEvent *event)@t\2\2@>@/
  11929. {@t\1@>@/
  11930. @<Check that the left button was pressed@>@;
  11931. if(!scaleDown)
  11932. {
  11933. event->ignore();
  11934. return;
  11935. }
  11936. scaleDown = false;
  11937. QPointF sceneCoordinate = mapToScene(event->x(), event->y());
  11938. @<Handle clicks in the decrement controls@>@;
  11939. @<Handle clicks in the increment controls@>@;
  11940. @<Handle clicks in the scale area@>@;
  11941. event->ignore();
  11942. return;@t\2@>@/
  11943. }
  11944. @ As currently implemented, each horizontal pixel position represents a value
  11945. evenly divisible by $0.1$. It is, however, quite common to see vaues with a
  11946. $.25$ or $.75$ after the whole number on cupping forms. In order to make it
  11947. possible to select such values without vastly increasing the length of the
  11948. scale, the increment and decrement controls adjust the represented value by
  11949. $0.05$.
  11950. @<Handle clicks in the decrement controls@>=
  11951. if(sceneCoordinate.x() >= 0 && sceneCoordinate.x() <= 10)
  11952. {
  11953. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  11954. {
  11955. if(initialSet)
  11956. {
  11957. setInitialValue(nonScoredValue - 0.05);
  11958. }
  11959. event->accept();
  11960. return;
  11961. }
  11962. else if(sceneCoordinate.y() >= 12 && sceneCoordinate.y() <= 22)
  11963. {
  11964. if(finalSet)
  11965. {
  11966. setFinalValue(scoredValue - 0.05);
  11967. event->accept();
  11968. return;
  11969. }
  11970. }
  11971. }
  11972. @ Incrementing represented values is done in the same manner as decrementing
  11973. them.
  11974. @<Handle clicks in the increment controls@>=
  11975. else if(sceneCoordinate.x() >= 122 && sceneCoordinate.x() <= 132)
  11976. {
  11977. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  11978. {
  11979. if(initialSet)
  11980. {
  11981. setInitialValue(nonScoredValue + 0.05);
  11982. event->accept();
  11983. return;
  11984. }
  11985. }
  11986. else if(sceneCoordinate.y() >= 12 && sceneCoordinate.y() <= 22)
  11987. {
  11988. if(finalSet)
  11989. {
  11990. setFinalValue(scoredValue + 0.05);
  11991. event->accept();
  11992. return;
  11993. }
  11994. }
  11995. }
  11996. @ When handling clicks in the scale area, there is a difference between the
  11997. first click and any subsequent click.
  11998. @<Handle clicks in the scale area@>=
  11999. double relativeX = sceneCoordinate.x() - 16;
  12000. if(initialSet)
  12001. {
  12002. if(relativeX >= 0 && relativeX <= 100)
  12003. {
  12004. setFinalValue(relativeX / 10.0);
  12005. event->accept();
  12006. return;
  12007. }
  12008. }
  12009. else
  12010. {
  12011. if(relativeX >= 0 && relativeX <= 100)
  12012. {
  12013. setInitialValue(relativeX / 10.0);
  12014. event->accept();
  12015. return;
  12016. }
  12017. }
  12018. @* The Vertical Scale.
  12019. \noindent In addition to the horizontal scale, there is also a vertical scale.
  12020. The implementation of this class is in some ways a bit simpler as only one value
  12021. must be retained. While there is no prohibition on using this scale for scored
  12022. values (and this might enable a rather compact representation which might be
  12023. useful in some applications), its intent is for unscored values which are less
  12024. likely to change over time. If the dry aroma of a coffee changes significantly
  12025. during a cupping session, you are most likely waiting far too long to pour the
  12026. water.
  12027. @<Class declarations@>=
  12028. class IntensityControl : public QGraphicsView
  12029. {
  12030. Q_OBJECT
  12031. Q_PROPERTY(double value READ value WRITE setValue)
  12032. QGraphicsScene scene;
  12033. QGraphicsPolygonItem decrement;
  12034. QGraphicsPolygonItem increment;
  12035. QGraphicsPolygonItem indicator;
  12036. QGraphicsPathItem scaleLine;
  12037. QPolygonF left;
  12038. QPolygonF up;
  12039. QPolygonF down;
  12040. QPainterPath scalePath;
  12041. QBrush theBrush;
  12042. double theValue;
  12043. bool valueSet;
  12044. bool scaleDown;
  12045. public:
  12046. IntensityControl();
  12047. double value();
  12048. virtual QSize sizeHint() const;
  12049. public slots:
  12050. void setValue(double val);
  12051. signals:
  12052. void valueChanged(double);
  12053. protected:
  12054. virtual void mousePressEvent(QMouseEvent *event);
  12055. virtual void mouseReleaseEvent(QMouseEvent *event);
  12056. };
  12057. @ Note the similarity between this constructor and the the |ScaleControl|
  12058. constructor.
  12059. @<IntensityControl implementation@>=
  12060. IntensityControl::IntensityControl() : QGraphicsView(NULL, NULL), theValue(-1),
  12061. valueSet(false), scaleDown(false)
  12062. {
  12063. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  12064. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  12065. left << QPointF(0, 0) << QPointF(10, -5) << QPointF(10, 5) << QPointF(0, 0);
  12066. down << QPointF(0, 0) << QPointF(10, 0) << QPointF(5, 10) << QPointF(0, 0);
  12067. up << QPointF(0, 10) << QPointF(10, 10) << QPointF(5, 0) << QPointF(0, 10);
  12068. theBrush.setColor(Qt::blue);
  12069. theBrush.setStyle(Qt::SolidPattern);
  12070. increment.setPolygon(up);
  12071. increment.setBrush(theBrush);
  12072. increment.setPos(0, 0);
  12073. scene.addItem(&increment);
  12074. decrement.setPolygon(down);
  12075. decrement.setBrush(theBrush);
  12076. decrement.setPos(0, 122);
  12077. scene.addItem(&decrement);
  12078. scalePath.moveTo(5, 0);
  12079. scalePath.lineTo(5, 100);
  12080. scalePath.moveTo(0, 0);
  12081. scalePath.lineTo(10, 0);
  12082. scalePath.moveTo(0, 10);
  12083. scalePath.lineTo(10, 10);
  12084. scalePath.moveTo(0, 20);
  12085. scalePath.lineTo(10, 20);
  12086. scalePath.moveTo(0, 30);
  12087. scalePath.lineTo(10, 30);
  12088. scalePath.moveTo(0, 40);
  12089. scalePath.lineTo(10, 40);
  12090. scalePath.moveTo(0, 50);
  12091. scalePath.lineTo(10, 50);
  12092. scalePath.moveTo(0, 60);
  12093. scalePath.lineTo(10, 60);
  12094. scalePath.moveTo(0, 70);
  12095. scalePath.lineTo(10, 70);
  12096. scalePath.moveTo(0, 80);
  12097. scalePath.lineTo(10, 80);
  12098. scalePath.moveTo(0, 90);
  12099. scalePath.lineTo(10, 90);
  12100. scalePath.moveTo(0, 100);
  12101. scalePath.lineTo(10, 100);
  12102. scaleLine.setPath(scalePath);
  12103. scaleLine.setPos(0, 16);
  12104. scene.addItem(&scaleLine);
  12105. setScene(&scene);
  12106. indicator.setPolygon(left);
  12107. indicator.setBrush(theBrush);
  12108. setMinimumSize(sizeHint());
  12109. setMaximumSize(sizeHint());
  12110. }
  12111. @ Once again, the size hint reduces the default size of the widget.
  12112. @<IntensityControl implementation@>=
  12113. QSize IntensityControl::sizeHint() const
  12114. {
  12115. return QSize(25, 160);
  12116. }
  12117. @ To support a more intuitive numerical representation, higher values should map
  12118. to higher positions on the scale. This is contrary to the coordinate system
  12119. provided by Qt, so the code setting the position of the indicator on the scale
  12120. must account for this.
  12121. During testing of this class, I found that it was impossible to select the
  12122. values 0 or 10 either through a click or with the increment or decrement
  12123. controls. Adding two additional execution branches corrects this issue.
  12124. @<IntensityControl implementation@>=
  12125. void IntensityControl::setValue(double val)
  12126. {
  12127. if(val >= 0 && val <= 10)
  12128. {
  12129. theValue = val;
  12130. if(!valueSet)
  12131. {
  12132. scene.addItem(&indicator);
  12133. }
  12134. valueSet = true;
  12135. indicator.setPos(6, (100 - (val * 10)) + 16);
  12136. emit(valueChanged(val));
  12137. }
  12138. else if(val < 1)
  12139. {
  12140. setValue(0);
  12141. }
  12142. else
  12143. {
  12144. setValue(10);
  12145. }
  12146. }
  12147. double IntensityControl::value()
  12148. {
  12149. return theValue;
  12150. }
  12151. @ Mouse event handling is similar as well. The mouse press event simply notes
  12152. that the button has been pressed.
  12153. @<IntensityControl implementation@>=
  12154. void IntensityControl::mousePressEvent(QMouseEvent *event)
  12155. {
  12156. @<Check that the left button was pressed@>@;
  12157. scaleDown = true;
  12158. event->accept();
  12159. }
  12160. @ Since there are fewer clickable areas there are fewer regions to check while
  12161. handling the mouse release event. Just as the |setValue()| method must
  12162. compensate for a mismatch between the scale and the underlying coordinate
  12163. system, so must click handling in the scale area take this into consideration
  12164. when determining which value the click intends.
  12165. @<IntensityControl implementation@>=
  12166. void IntensityControl::mouseReleaseEvent(QMouseEvent *event)
  12167. {
  12168. @<Check that the left button was pressed@>@;
  12169. if(!scaleDown)
  12170. {
  12171. event->ignore();
  12172. return;
  12173. }
  12174. scaleDown = false;
  12175. QPointF sceneCoordinate = mapToScene(event->x(), event->y());
  12176. if(sceneCoordinate.x() >= 0 && sceneCoordinate.x() <= 16)
  12177. {
  12178. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  12179. {
  12180. if(valueSet)
  12181. {
  12182. setValue(theValue + 0.05);
  12183. }
  12184. event->accept();
  12185. return;
  12186. }
  12187. else if(sceneCoordinate.y() >= 122 && sceneCoordinate.y() <= 132)
  12188. {
  12189. if(valueSet)
  12190. {
  12191. setValue(theValue - 0.05);
  12192. }
  12193. event->accept();
  12194. return;
  12195. }
  12196. else if(sceneCoordinate.y() >= 16 && sceneCoordinate.y() <= 116)
  12197. {
  12198. setValue(10 - ((sceneCoordinate.y() - 16) / 10.0));
  12199. event->accept();
  12200. return;
  12201. }
  12202. }
  12203. }
  12204. @* Scripting the Scale Widgets.
  12205. \noindent Scale widgets can be added through the configuration system with
  12206. {\tt <hscale>} and {\tt <vscale>} elements. These can be added to layouts.
  12207. @<Function prototypes for scripting@>=
  12208. void addScaleControlToLayout(QDomElement element,
  12209. QStack<QWidget *> *widgetStack,
  12210. QStack<QLayout *> *layoutStack);
  12211. void addIntensityControlToLayout(QDomElement element,
  12212. QStack<QWidget *> *widgetStack,
  12213. QStack<QLayout *> *layoutStack);
  12214. @ Adding these widgets is done in the same way as adding other widgets.
  12215. @<Functions for scripting@>=
  12216. void addScaleControlToLayout(QDomElement element, QStack<QWidget *> *,
  12217. QStack<QLayout *> *layoutStack)
  12218. {
  12219. ScaleControl *scale = new ScaleControl;
  12220. if(element.hasAttribute("id"))
  12221. {
  12222. scale->setObjectName(element.attribute("id"));
  12223. }
  12224. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  12225. layout->addWidget(scale);
  12226. }
  12227. void addIntensityControlToLayout(QDomElement element, QStack<QWidget *> *,
  12228. QStack<QLayout *> *layoutStack)
  12229. {
  12230. IntensityControl *scale = new IntensityControl;
  12231. if(element.hasAttribute("id"))
  12232. {
  12233. scale->setObjectName(element.attribute("id"));
  12234. }
  12235. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  12236. layout->addWidget(scale);
  12237. }
  12238. @** Device Configuration.
  12239. \noindent Starting in \pn{} 1.4, all supported measurement hardware is
  12240. available from the same build and it is possible to use multiple devices from
  12241. differernt vendors at the same time. In previous versions, there were very few
  12242. available hardware configurations and a small number of example configuration
  12243. documents covered the needs of most people using the software. As more hardware
  12244. is supported and more people with distinct needs start using \pn{}, that
  12245. approach becomes unsustainable and the need for in-program configuration
  12246. becomes increasingly pronounced.
  12247. Device configuration is coupled to configuration of the logging window and
  12248. it is possible to configure multiple different roasters with different hardware
  12249. and other customizations of the logging window specific to a particular
  12250. machine.
  12251. The core of this is the use of an XML document saved with |QSettings| under
  12252. the |"DeviceConfiguration"| key. Within the root {\tt <DeviceConfiguration>}
  12253. element there are two grouping elements: {\tt <devices>} and
  12254. {\tt <references>}. The terminology was developed at a time when it was
  12255. thought that hardware configuration and logging view configuration would be
  12256. decoupled from each other, however the benefits of combining these far
  12257. outweighed the minor loss of flexibility with this approach.
  12258. Within the {\tt <devices>} tag there are arbitrarily many {\tt <node>} tags
  12259. which themselves may contain {\tt <node>} tags nested to any depth. Each of
  12260. these has two attributes, a {\tt name} attribute which specifies the display
  12261. text used to represent that node and a {\tt reference} attribute with a
  12262. unique value. Typica will generate a UUID for each node to use as the unique
  12263. value but this is not strictly required. The {\tt name} attribute does not
  12264. need to be unique and will generally be supplied by the person using the
  12265. software. The top level {\tt node} elements represent a coffee roaster and
  12266. the sub-elements can represent hardware, annotation controls, and possibly
  12267. other configurable features.
  12268. Within the {\tt <references>} tag there are as many {\tt <reference>} tags as
  12269. there are {\tt <node>} tags. Each of these has an {\tt id} attribute which
  12270. matches the {\tt reference} attribute in a {\tt <node>} tag and a {\tt driver}
  12271. attribute which is used to determine which class should be used to interact
  12272. with these settings. In the case of device configuration, this allows a
  12273. determination of which class should be used to generate an editor for settings
  12274. related to that node. Within each {\tt <reference>} tag is an arbitrary number
  12275. of {\tt <attribute>} tags with {\tt name} and {\tt value} attributes. Code for
  12276. providing the settings widgets and device interfaces can use these for any
  12277. desired purpose, but it is common to have one {\tt <attribute>} tag per setting
  12278. appropriate for a given node and possibly more to identify the concept a
  12279. particular node represents.
  12280. The global |Application| object is extended to maintain a |QDomDocument|
  12281. representation of this XML document.
  12282. @<Application private data members@>=
  12283. QDomDocument deviceConfigurationDocument;
  12284. @ Two methods are also provided for interacting with this document. The
  12285. |deviceConfiguration()| method returns a pointer to the private data member,
  12286. loading the XML from |QSettings| if required and creating a new document with
  12287. no {\tt <node>} tags if the document does not exist in settings. The
  12288. |saveDeviceConfiguration()| method serializes the |QDomDocument| to settings.
  12289. @<Device configuration members@>=
  12290. QDomDocument deviceConfiguration();
  12291. @ The method for saving should be a slot so a model representing this data
  12292. can persist changes through the signals and slots mechanism rather than
  12293. requiring the calls to be explicitn.
  12294. @<Extended Application slots@>=
  12295. void saveDeviceConfiguration();
  12296. @ Serializing the current configuration is trivial.
  12297. @<Application Implementation@>=
  12298. void Application::saveDeviceConfiguration()
  12299. {
  12300. QSettings settings;
  12301. settings.setValue("DeviceConfiguration",
  12302. QVariant(deviceConfigurationDocument.toByteArray()));
  12303. }
  12304. @ Producing a pointer to a loaded configuration only slightly more complicated.
  12305. If the configuration has been previously loaded we just return the pointer.
  12306. Otherwise, we attempt to load the document.
  12307. @<Application Implementation@>=
  12308. QDomDocument Application::deviceConfiguration()
  12309. {
  12310. if(deviceConfigurationDocument.isNull())
  12311. {
  12312. @<Load device configuration document from settings@>@;
  12313. }
  12314. return deviceConfigurationDocument;
  12315. }
  12316. @ In most cases a document will already exist in settings, but we must verify
  12317. this and create a new document if it does not exist. We also clear device
  12318. configuration settings if the configuration document is invalid.
  12319. @<Load device configuration document from settings@>=
  12320. QSettings settings;
  12321. QByteArray document = settings.value("DeviceConfiguration").toByteArray();
  12322. QString etext;
  12323. int eline;
  12324. int ecol;
  12325. if(document.length() == 0)
  12326. {
  12327. qDebug() << "Loaded settings length is 0. Creating new configuration.";
  12328. @<Create device configuration document@>@;
  12329. }
  12330. else
  12331. {
  12332. if(!deviceConfigurationDocument.setContent(document, false,
  12333. &etext, &eline, &ecol))
  12334. {
  12335. @<Report configuration loading error@>@;
  12336. @<Create device configuration document@>@;
  12337. }
  12338. }
  12339. @ Rather than generate the empty device configuration programmatically, we keep
  12340. an empty device configuration document as a resource.
  12341. @<Create device configuration document@>=
  12342. QFile emptyDocument(":/resources/xml/EmptyDeviceConfiguration.xml");
  12343. emptyDocument.open(QIODevice::ReadOnly);
  12344. if(!deviceConfigurationDocument.setContent(&emptyDocument, false,
  12345. &etext, &eline, &ecol))
  12346. {
  12347. @<Report configuration loading error@>@;
  12348. }
  12349. else
  12350. {
  12351. saveDeviceConfiguration();
  12352. }
  12353. @ There isn't really anything that can be done if the device configuration data
  12354. is corrupt, but an error message can be produced if the program happens to have
  12355. access to a debugging console.
  12356. @<Report configuration loading error@>=
  12357. qDebug() << QString(tr("An error occurred loading device configuration."));
  12358. qDebug() << QString(tr("Line %1, Column %2")).arg(eline).arg(ecol);
  12359. qDebug() << etext;
  12360. @* Model and view for device configuration hierarchy.
  12361. \noindent When manipulating device configuration data, it can be useful to
  12362. present the device hierarchy in a tree view. To do this, we use two classes to
  12363. produce a tree model. This is slightly extended and modified from an example
  12364. in the Qt documentation.\nfnote{Simple DOM Model Example:\par\indent\pdfURL{%
  12365. http://doc.qt.nokia.com/4.7-snapshot/itemviews-simpledommodel.html}
  12366. {http://doc.qt.nokia.com/4.7-snapshot/itemviews-simpledommodel.html}}
  12367. Our model uses the |DeviceTreeModelNode| class to cache the |QDomNode|
  12368. instances with the data we want.
  12369. @<Class declarations@>=
  12370. class DeviceTreeModelNode
  12371. {
  12372. public:
  12373. DeviceTreeModelNode(QDomNode &node, int row,
  12374. DeviceTreeModelNode *parent = NULL);
  12375. ~DeviceTreeModelNode();
  12376. DeviceTreeModelNode *child(int index);
  12377. DeviceTreeModelNode *parent();
  12378. QDomNode node() const;
  12379. int row();
  12380. private:
  12381. QDomNode domNode;
  12382. QHash<int, DeviceTreeModelNode*> children;
  12383. int rowNumber;
  12384. DeviceTreeModelNode *parentItem;
  12385. };
  12386. @ Implementation of this helper class is trivial.
  12387. @<DeviceTreeModelNode implementation@>=
  12388. DeviceTreeModelNode::DeviceTreeModelNode(QDomNode &node, int row,
  12389. DeviceTreeModelNode *parent)
  12390. : domNode(node), rowNumber(row), parentItem(parent)
  12391. {
  12392. /* Nothing needs to be done here. */
  12393. }
  12394. DeviceTreeModelNode::~DeviceTreeModelNode()
  12395. {
  12396. QHash<int, DeviceTreeModelNode *>::iterator@, i;
  12397. for(i = children.begin(); i != children.end(); i++)
  12398. {
  12399. delete i.value();
  12400. }
  12401. }
  12402. DeviceTreeModelNode *DeviceTreeModelNode::parent()
  12403. {
  12404. return parentItem;
  12405. }
  12406. int DeviceTreeModelNode::row()
  12407. {
  12408. return rowNumber;
  12409. }
  12410. QDomNode DeviceTreeModelNode::node() const
  12411. {
  12412. return domNode;
  12413. }
  12414. DeviceTreeModelNode *DeviceTreeModelNode::child(int index)
  12415. {
  12416. if(children.contains(index))
  12417. {
  12418. return children[index];
  12419. }
  12420. if(index >= 0 && index < domNode.childNodes().count())
  12421. {
  12422. QDomNode childNode = domNode.childNodes().item(index);
  12423. DeviceTreeModelNode *childItem = new DeviceTreeModelNode(childNode,
  12424. index, this);
  12425. children[index] = childItem;
  12426. return childItem;
  12427. }
  12428. return NULL;
  12429. }
  12430. @ The model class provides a single column representation of the {\tt devices}
  12431. section of the device configuration document. It provides methods for editing
  12432. the name of any node, for adding new nodes to the model, for deleting any node
  12433. in the model, and for obtaining the {\tt reference} element corresponding to
  12434. a given node.
  12435. @<Class declarations@>=
  12436. class DeviceTreeModel : public QAbstractItemModel@/
  12437. {@/
  12438. @[Q_OBJECT@]@;
  12439. public:@/
  12440. DeviceTreeModel(QObject *parent = NULL);
  12441. ~DeviceTreeModel();
  12442. QVariant data(const QModelIndex &index, int role) const;
  12443. Qt::ItemFlags flags(const QModelIndex &index) const;
  12444. QVariant headerData(int section, Qt::Orientation orientation,
  12445. int role = Qt::DisplayRole) const;
  12446. QModelIndex index(int row, int column,
  12447. const QModelIndex &parent = QModelIndex()) const;
  12448. QModelIndex parent(const QModelIndex &child) const;
  12449. int rowCount(const QModelIndex &parent = QModelIndex()) const;
  12450. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  12451. bool setData(const QModelIndex &index, const QVariant &value,
  12452. int role);
  12453. bool removeRows(int row, int count, const QModelIndex &parent);
  12454. QDomElement referenceElement(const QString &id);
  12455. @[public slots@]:@/
  12456. void newNode(const QString &name, const QString &driver,
  12457. const QModelIndex &parent);
  12458. private:@/
  12459. QDomDocument document;
  12460. DeviceTreeModelNode *root;
  12461. QDomNode referenceSection;
  12462. QDomNode treeRoot;
  12463. };
  12464. @ In the constructor we locate the {\tt devices} and {\tt references} sections
  12465. of the passed in document. Our tree of cached |QDomNode| elements starts with
  12466. the former and is expanded as needed.
  12467. @<DeviceTreeModel implementation@>=
  12468. DeviceTreeModel::DeviceTreeModel(QObject *parent)
  12469. : QAbstractItemModel(parent)
  12470. {
  12471. document = AppInstance->deviceConfiguration();
  12472. QDomNodeList elements = document.elementsByTagName("devices");
  12473. if(elements.size() != 1)
  12474. {
  12475. qDebug() << "Unexpected result when loading device map.";
  12476. }
  12477. treeRoot = elements.at(0);
  12478. root = new DeviceTreeModelNode(treeRoot, 0);
  12479. elements = document.elementsByTagName("references");
  12480. if(elements.size() != 1)
  12481. {
  12482. qDebug() << "No references section. Creating.";
  12483. referenceSection = document.createElement("references");
  12484. document.appendChild(referenceSection);
  12485. }
  12486. else
  12487. {
  12488. referenceSection = elements.at(0);
  12489. }
  12490. connect(this, SIGNAL(dataChanged(QModelIndex, QModelIndex)),
  12491. AppInstance, SLOT(saveDeviceConfiguration()));
  12492. connect(this, SIGNAL(modelReset()),
  12493. AppInstance, SLOT(saveDeviceConfiguration()));
  12494. connect(this, SIGNAL(rowsInserted(QModelIndex, int, int)),
  12495. AppInstance, SLOT(saveDeviceConfiguration()));
  12496. }
  12497. @ We only provide a single column for our model, so |columnCount()| can simply
  12498. return a constant. The |rowCount()| method can return a variety of values
  12499. depending on the parent node.
  12500. @<DeviceTreeModel implementation@>=
  12501. int DeviceTreeModel::columnCount(const QModelIndex &) const
  12502. {
  12503. return 1;
  12504. }
  12505. int DeviceTreeModel::rowCount(const QModelIndex &parent) const
  12506. {
  12507. if(parent.column() > 0)
  12508. {
  12509. return 0;
  12510. }
  12511. @<Get parent item from index@>@;
  12512. return parentItem->node().childNodes().count();
  12513. }
  12514. @ If an invalid index is passed as the parent index, we assume the parent to
  12515. be the root element.
  12516. @<Get parent item from index@>=
  12517. DeviceTreeModelNode *parentItem;
  12518. if(!parent.isValid())
  12519. {
  12520. parentItem = root;
  12521. }
  12522. else
  12523. {
  12524. parentItem = static_cast<DeviceTreeModelNode *>(parent.internalPointer());
  12525. }
  12526. @ As seen in |rowCount()|, we keep a pointer to the cached node in our model
  12527. indices.
  12528. @<DeviceTreeModel implementation@>=
  12529. QModelIndex DeviceTreeModel::index(int row, int column,
  12530. const QModelIndex &parent) const
  12531. {
  12532. if(!hasIndex(row, column, parent))
  12533. {
  12534. return QModelIndex();
  12535. }
  12536. @<Get parent item from index@>@;
  12537. DeviceTreeModelNode *childItem = parentItem->child(row);
  12538. if(childItem)
  12539. {
  12540. return createIndex(row, column, childItem);
  12541. }
  12542. return QModelIndex();
  12543. }
  12544. @ We can also request an index for the parent of a given index.
  12545. @<DeviceTreeModel implementation@>=
  12546. QModelIndex DeviceTreeModel::parent(const QModelIndex &child) const
  12547. {
  12548. if(!child.isValid())
  12549. {
  12550. return QModelIndex();
  12551. }
  12552. DeviceTreeModelNode *childItem =
  12553. static_cast<DeviceTreeModelNode *>(child.internalPointer());
  12554. DeviceTreeModelNode *parentItem = childItem->parent();
  12555. if(!parentItem || parentItem == root)
  12556. {
  12557. return QModelIndex();
  12558. }
  12559. return createIndex(parentItem->row(), 0, parentItem);
  12560. }
  12561. @ All items should be enabled, selectable, and editable.
  12562. @<DeviceTreeModel implementation@>=
  12563. Qt::ItemFlags DeviceTreeModel::flags(const QModelIndex &index) const
  12564. {
  12565. if(!index.isValid())
  12566. {
  12567. return 0;
  12568. }
  12569. return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
  12570. }
  12571. @ Each node in the model maintains two pieces of information. One is the
  12572. display value for the node which is held in the {\tt name} attribute of the
  12573. corresponding XML element. The other is a reference ID held in the
  12574. {\tt reference} attribute.
  12575. @<DeviceTreeModel implementation@>=
  12576. QVariant DeviceTreeModel::data(const QModelIndex &index, int role) const
  12577. {
  12578. if(!index.isValid())
  12579. {
  12580. return QVariant();
  12581. }
  12582. if(role != Qt::DisplayRole && role != Qt::UserRole && role != Qt::EditRole)
  12583. {
  12584. return QVariant();
  12585. }
  12586. DeviceTreeModelNode *item =
  12587. static_cast<DeviceTreeModelNode *>(index.internalPointer());
  12588. QDomNode node = item->node();
  12589. QDomElement element = node.toElement();
  12590. switch(role)
  12591. {
  12592. case Qt::DisplayRole:@/
  12593. case Qt::EditRole:@/
  12594. return QVariant(element.attribute("name"));
  12595. case Qt::UserRole:@/
  12596. return QVariant(element.attribute("reference"));
  12597. default:@/
  12598. return QVariant();
  12599. }
  12600. return QVariant();
  12601. }
  12602. @ The reference value is managed by the model and should never be changed. The
  12603. display value for a node is, however, editable. These changes must propagate
  12604. back to the XML document underlying the model.
  12605. @<DeviceTreeModel implementation@>=
  12606. bool DeviceTreeModel::setData(const QModelIndex &index,
  12607. const QVariant &value, int)@;@/
  12608. {@t\1@>@/
  12609. if(!index.isValid())@/
  12610. {@t\1@>@/
  12611. return false;@t\2@>@/
  12612. }@/
  12613. DeviceTreeModelNode *item =
  12614. static_cast<DeviceTreeModelNode *>(index.internalPointer());
  12615. QDomNode node = item->node();
  12616. QDomElement element = node.toElement();
  12617. element.setAttribute("name", value.toString());
  12618. emit dataChanged(index, index);@;
  12619. return true;@t\2@>@/
  12620. }
  12621. @ A custom method is provided for adding new nodes to the model. This generates
  12622. the two XML elements needed for the node. The |name| parameter is the display
  12623. name of the new node, the |driver| parameter is used as the value for the
  12624. {\tt driver} attribute in the {\tt reference} element which will be used to
  12625. determine what classes are used to work with that data.
  12626. @<DeviceTreeModel implementation@>=
  12627. void DeviceTreeModel::newNode(const QString &name, const QString &driver,
  12628. const QModelIndex &parent)
  12629. {
  12630. QString referenceID = QUuid::createUuid().toString();
  12631. @<Get parent item from index@>@;
  12632. QDomNode parentNode = parentItem->node();
  12633. int newRowNumber = rowCount(parent);
  12634. beginInsertRows(parent, newRowNumber, newRowNumber);
  12635. QDomElement deviceElement = document.createElement("node");
  12636. deviceElement.setAttribute("name", name);
  12637. deviceElement.setAttribute("reference", referenceID);
  12638. parentNode.appendChild(deviceElement);
  12639. QDomElement referenceElement = document.createElement("reference");
  12640. referenceElement.setAttribute("id", referenceID);
  12641. referenceElement.setAttribute("driver", driver);
  12642. referenceSection.appendChild(referenceElement);
  12643. endInsertRows();
  12644. }
  12645. @ We can also delete nodes. When deleting a node, both XML elements are
  12646. removed and our node cache is invalidated.
  12647. @<DeviceTreeModel implementation@>=
  12648. bool DeviceTreeModel::removeRows(int row, int count, const QModelIndex &parent)@t\2\2@>@/
  12649. {@t\1@>@/
  12650. @<Get parent item from index@>@;
  12651. QDomNode parentNode = parentItem->node();
  12652. QDomNodeList childNodes = parentNode.childNodes();@;
  12653. if(childNodes.size() < row + count)@/
  12654. {@t\1@>@/
  12655. return false;@t\2@>@/
  12656. }@/
  12657. beginRemoveRows(parent, row, row + count - 1);
  12658. QList<QDomElement> removalList;
  12659. for(int i = row; i < row + count; i++)
  12660. {
  12661. removalList.append(childNodes.at(i).toElement());
  12662. }
  12663. QDomElement element;
  12664. QDomElement reference;
  12665. for(int i = 0; i < count; i++)
  12666. {
  12667. element = removalList.at(i);
  12668. if(element.hasAttribute("reference"))
  12669. {
  12670. reference = referenceElement(element.attribute("reference"));
  12671. if(!reference.isNull())
  12672. {
  12673. referenceSection.removeChild(reference);
  12674. }
  12675. }
  12676. parentNode.removeChild(element);
  12677. }
  12678. endRemoveRows();
  12679. beginResetModel();
  12680. delete root;
  12681. root = new DeviceTreeModelNode(treeRoot, 0);
  12682. endResetModel();@;
  12683. return true;@t\2@>@/
  12684. }
  12685. @ Another custom method obtains the {\tt reference} element for a given
  12686. reference ID.
  12687. @<DeviceTreeModel implementation@>=
  12688. QDomElement DeviceTreeModel::referenceElement(const QString &id)
  12689. {
  12690. QDomNodeList childNodes = referenceSection.childNodes();
  12691. QDomElement element;
  12692. for(int i = 0; i < childNodes.size(); i++)
  12693. {
  12694. element = childNodes.at(i).toElement();
  12695. if(element.hasAttribute("id"))
  12696. {
  12697. if(element.attribute("id") == id)
  12698. {
  12699. return element;
  12700. }
  12701. }
  12702. }
  12703. return QDomElement();
  12704. }
  12705. @ We don't want any headers, so |headerData()| is very simple.
  12706. @<DeviceTreeModel implementation@>=
  12707. QVariant DeviceTreeModel::headerData(int, Qt::Orientation, int) const
  12708. {
  12709. return QVariant();
  12710. }
  12711. @ The destructor destroys the node cache. The destructor for the top level node
  12712. will recursively destroy all child nodes.
  12713. @<DeviceTreeModel implementation@>=
  12714. DeviceTreeModel::~DeviceTreeModel()
  12715. {
  12716. delete root;
  12717. }
  12718. @ Exposing this class to the host environment allows a number of interesting
  12719. possibilities. Setting the model to a combo box, for example, allows the
  12720. selection of top level nodes representing a particular coffee roaster. It is
  12721. also useful to have the ability to traverse a specified sub-tree of the model
  12722. to set up a logging view that matches the configuration for such a selected
  12723. roaster.
  12724. @<Function prototypes for scripting@>=
  12725. QScriptValue constructDeviceTreeModel(QScriptContext *context,
  12726. QScriptEngine *engine);
  12727. void setDeviceTreeModelProperties(QScriptValue value, QScriptEngine *engine);
  12728. void setQAbstractItemModelProperties(QScriptValue value, QScriptEngine *engine);
  12729. QScriptValue DeviceTreeModel_referenceElement(QScriptContext *context,
  12730. QScriptEngine *engine);
  12731. QScriptValue QAbstractItemModel_data(QScriptContext *context, QScriptEngine *engine);
  12732. QScriptValue QAbstractItemModel_index(QScriptContext *context, QScriptEngine *engine);
  12733. QScriptValue QAbstractItemModel_rowCount(QScriptContext *context, QScriptEngine *engine);
  12734. QScriptValue QAbstractItemModel_hasChildren(QScriptContext *context, QScriptEngine *engine);
  12735. @ The constructor is trivial.
  12736. @<Functions for scripting@>=
  12737. QScriptValue constructDeviceTreeModel(QScriptContext *, QScriptEngine *engine)
  12738. {
  12739. QScriptValue object = engine->newQObject(new DeviceTreeModel);
  12740. setDeviceTreeModelProperties(object, engine);
  12741. return object;
  12742. }
  12743. @ As usual the host environment is informed of this constructor.
  12744. @<Set up the scripting engine@>=
  12745. constructor = engine->newFunction(constructDeviceTreeModel);
  12746. value = engine->newQMetaObject(&DeviceTreeModel::staticMetaObject,
  12747. constructor);
  12748. engine->globalObject().setProperty("DeviceTreeModel", value);
  12749. @ A number of properties are set to allow script code to traverse the model.
  12750. Most of these properties are properly members of |QAbstractItemModel| and
  12751. the code is written to allow any models that may be exposed to the host
  12752. environment in the future to make use of these as well. Note that this is not
  12753. a full set of functionality but only what I needed to implement a particular
  12754. feature set.
  12755. @<Functions for scripting@>=
  12756. void setDeviceTreeModelProperties(QScriptValue value, QScriptEngine *engine)
  12757. {
  12758. setQAbstractItemModelProperties(value, engine);
  12759. value.setProperty("referenceElement",
  12760. engine->newFunction(DeviceTreeModel_referenceElement));
  12761. }
  12762. void setQAbstractItemModelProperties(QScriptValue value, QScriptEngine *engine)
  12763. {
  12764. setQObjectProperties(value, engine);
  12765. value.setProperty("data", engine->newFunction(QAbstractItemModel_data));
  12766. value.setProperty("index", engine->newFunction(QAbstractItemModel_index));
  12767. value.setProperty("rowCount", engine->newFunction(QAbstractItemModel_rowCount));
  12768. value.setProperty("hasChildren", engine->newFunction(QAbstractItemModel_hasChildren));
  12769. }
  12770. @ The wrapped call to |referenceElement| does a little more than might be
  12771. expected. Rather than returning a |QDomElement| and leaving it up to script
  12772. code to traverse the sub-tree, we create a |QVariantMap| which in script code
  12773. is translated as an object with the keys as properties of the object containing
  12774. the values of those keys. This is populated by first specifying a {\tt driver}
  12775. key with its value from the {\tt driver} attribute of the {\tt reference} node.
  12776. We then examine the {\tt <attribute>} sub-elements and use the {\tt name}
  12777. attribute as keys and the {\tt value} attribute as values to fill out the rest
  12778. of the map.
  12779. @<Functions for scripting@>=
  12780. QScriptValue DeviceTreeModel_referenceElement(QScriptContext *context,
  12781. QScriptEngine *engine)
  12782. {
  12783. DeviceTreeModel *model = getself<DeviceTreeModel *>(context);
  12784. QDomElement referenceElement = model->referenceElement(argument<QString>(0, context));
  12785. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  12786. QDomElement node;
  12787. QVariantMap retval;
  12788. retval.insert("driver", referenceElement.attribute("driver"));
  12789. for(int i = 0; i < configData.size(); i++)
  12790. {
  12791. node = configData.at(i).toElement();
  12792. retval.insert(node.attribute("name"), node.attribute("value"));
  12793. }
  12794. return engine->toScriptValue(retval);
  12795. }
  12796. QScriptValue QAbstractItemModel_data(QScriptContext *context, QScriptEngine *engine)
  12797. {
  12798. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  12799. QModelIndex index = argument<QModelIndex>(0, context);
  12800. int role = argument<int>(1, context);
  12801. return engine->toScriptValue(model->data(index, role));
  12802. }
  12803. QScriptValue QAbstractItemModel_index(QScriptContext *context, QScriptEngine *engine)
  12804. {
  12805. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  12806. int row = 0;
  12807. int column = 0;
  12808. QModelIndex index;
  12809. if(context->argumentCount() > 1)
  12810. {
  12811. row = argument<int>(0, context);
  12812. column = argument<int>(1, context);
  12813. }
  12814. if(context->argumentCount() > 2)
  12815. {
  12816. index = argument<QModelIndex>(2, context);
  12817. }
  12818. QModelIndex retval = model->index(row, column, index);
  12819. return engine->toScriptValue(retval);
  12820. }
  12821. QScriptValue QAbstractItemModel_rowCount(QScriptContext *context,
  12822. QScriptEngine *)
  12823. {
  12824. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  12825. QModelIndex index;
  12826. if(context->argumentCount() == 1)
  12827. {
  12828. index = argument<QModelIndex>(0, context);
  12829. }
  12830. return QScriptValue(model->rowCount(index));
  12831. }
  12832. QScriptValue QAbstractItemModel_hasChildren(QScriptContext *context,
  12833. QScriptEngine *engine)
  12834. {
  12835. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  12836. QModelIndex index;
  12837. if(context->argumentCount() == 1)
  12838. {
  12839. index = argument<QModelIndex>(0, context);
  12840. }
  12841. return QScriptValue(engine, model->hasChildren(index));
  12842. }
  12843. @ Some additional work is needed to handle |QModelIndex| appropriately. First
  12844. we declare |QModelIndex| as a metatype.
  12845. @<Class declarations@>=
  12846. Q_DECLARE_METATYPE(QModelIndex)
  12847. @ Next we need a pair of functions to convert |QModelIndex| to and from script
  12848. values.
  12849. @<Function prototypes for scripting@>=
  12850. QScriptValue QModelIndex_toScriptValue(QScriptEngine *engine, const QModelIndex &index);
  12851. void QModelIndex_fromScriptValue(const QScriptValue &value, QModelIndex &index);
  12852. @ These are implemented thusly.
  12853. @<Functions for scripting@>=
  12854. QScriptValue QModelIndex_toScriptValue(QScriptEngine *engine, const QModelIndex &index)
  12855. {
  12856. QVariant var;
  12857. var.setValue(index);
  12858. QScriptValue object = engine->newVariant(var);
  12859. return object;
  12860. }
  12861. void QModelIndex_fromScriptValue(const QScriptValue &value, QModelIndex &index)
  12862. {
  12863. index = value.toVariant().value<QModelIndex>();
  12864. }
  12865. @ Finally we register this with the engine.
  12866. @<Set up the scripting engine@>=
  12867. qScriptRegisterMetaType(engine, QModelIndex_toScriptValue, QModelIndex_fromScriptValue);
  12868. @* Device Configuration Widgets.
  12869. \noindent Each node in the {\tt devices} section of the |DeviceTreeModel| is
  12870. associated with a {\tt reference} element that provides a driver string which
  12871. can be used to identify the classes used to interact with the device
  12872. configuration data. An example of this is selecting which widget to use when
  12873. selecting a node in a configuration window. These widgets must be registered
  12874. to the appropriate driver string in advance. This is currently handled through
  12875. the |Application| instance, though it would probably be better to split this
  12876. into its own class at some point in the future.
  12877. @<Application private data members@>=
  12878. QHash<QString, QMetaObject> deviceConfigurationWidgets;
  12879. @ Two methods register widgets and retrieve an instance of the appropriate
  12880. widget for a given node in the device configuration model.
  12881. @<Device configuration members@>=
  12882. void registerDeviceConfigurationWidget(QString driver, QMetaObject widget);
  12883. QWidget* deviceConfigurationWidget(DeviceTreeModel *model,
  12884. const QModelIndex &index);
  12885. @ Registration is a simple wrapper around the underlying |QHash|.
  12886. @<Application Implementation@>=
  12887. void Application::registerDeviceConfigurationWidget(QString driver,
  12888. QMetaObject widget)
  12889. {
  12890. deviceConfigurationWidgets.insert(driver, widget);
  12891. }
  12892. @ Obtaining the configuration widget for a given node involves looking up the
  12893. reference element, extracting the driver string, looking up the associated
  12894. meta-object, and returning a new instance of that object.
  12895. As there is no concept of an invalid |QMetaObject| we default to the static
  12896. meta-object for a |QWidget| if a widget for the specified driver string is not
  12897. registered and check for this prior to creating a new instance of the
  12898. configuration widget.
  12899. @<Application Implementation@>=
  12900. QWidget* Application::deviceConfigurationWidget(DeviceTreeModel *model,
  12901. const QModelIndex &index)
  12902. {
  12903. QVariant nodeReference = index.data(Qt::UserRole);
  12904. QDomElement referenceElement = model->referenceElement(
  12905. model->data(index, Qt::UserRole).toString());
  12906. QMetaObject metaObject =
  12907. deviceConfigurationWidgets.value(referenceElement.attribute("driver"),
  12908. QWidget::staticMetaObject);
  12909. QWidget *editor;
  12910. if(metaObject.className() == QWidget::staticMetaObject.className())
  12911. {
  12912. editor = NULL;
  12913. }
  12914. else
  12915. {
  12916. editor = qobject_cast<QWidget *>(
  12917. metaObject.newInstance(Q_ARG(DeviceTreeModel *, model),
  12918. Q_ARG(QModelIndex, index)));
  12919. }
  12920. return editor;
  12921. }
  12922. @ Every node type should have an associated editor and the editors for nodes
  12923. which can have child nodes should be able to handle creating these child nodes.
  12924. This leaves the problem of creating the top level nodes. For this we must have
  12925. a way to register three key pieces of information: the text which should appear
  12926. for selecting a new top level node to add to the configuration, the default
  12927. name for a node of that type, and the registered driver string associated with
  12928. that node type. The most likely use for this information is in constructing a
  12929. menu. |QAction| seems like a good fit, but this cannot pass all of the
  12930. required information. Part of the chosen solution is a |QAction| subclass
  12931. which takes all three pieces of information and provides a new signal to
  12932. supply the information needed to add a new top level node.
  12933. @<Class declarations@>=
  12934. class NodeInserter : public QAction@/
  12935. {@/
  12936. @[Q_OBJECT@]@;
  12937. public:@/
  12938. NodeInserter(const QString &title, const QString &name,
  12939. const QString &driver, QObject *parent = NULL);
  12940. signals:@/
  12941. void triggered(QString name, QString driver);
  12942. @[private slots@]:@/
  12943. void onTriggered();
  12944. private:@/
  12945. QString defaultNodeName;
  12946. QString driverString;
  12947. };
  12948. @ The constructor saves the information that will later be emitted and connects
  12949. the |triggered()| signal from |QAction| to a private slot which emits our new
  12950. |triggered()| signal.
  12951. @<NodeInserter implementation@>=
  12952. NodeInserter::NodeInserter(const QString &title, const QString &name,
  12953. const QString &driver, QObject *parent) :
  12954. QAction(title, parent), defaultNodeName(name), driverString(driver)
  12955. {
  12956. connect(this, SIGNAL(triggered()), this, SLOT(onTriggered()));
  12957. }
  12958. void NodeInserter::onTriggered()
  12959. {
  12960. emit triggered(defaultNodeName, driverString);
  12961. }
  12962. @ An interface for adding top level nodes to the device configuration needs to
  12963. be able to access a list of these actions so we make this available through the
  12964. |Application| instance. Once again, it would be better to split device
  12965. configuration registration data to a separate class and there should be
  12966. accessors around this.
  12967. Note that this terminology was introduced when it was assumed that device
  12968. configuration and logging view configuration would be separate. It is likely
  12969. that a future code cleanup will remove this in favor of handling the top level
  12970. of the device configuration hierarchy (under roaster specification) in the same
  12971. way that sub-nodes are handled.
  12972. @<Device configuration members@>=
  12973. QList<NodeInserter *> topLevelNodeInserters;
  12974. @ With this done, we can now produce a window which allows someone to easily
  12975. edit the device configuration.
  12976. @<Class declarations@>=
  12977. class DeviceConfigurationWindow : public QMainWindow
  12978. {
  12979. @[Q_OBJECT@]@;
  12980. public:@/
  12981. DeviceConfigurationWindow();
  12982. @[public slots@]:@/
  12983. void addDevice();
  12984. void removeNode();
  12985. void newSelection(const QModelIndex &index);
  12986. private:@/
  12987. QDomDocument document;
  12988. DeviceTreeModel *model;
  12989. QTreeView *view;
  12990. QScrollArea *configArea;
  12991. };
  12992. @ This window consists of two main panels separated by a splitter. The left
  12993. panel presents a tree view of the current device configuration and a set of
  12994. controls that allows someone to either add a new top level node to the
  12995. configuration or delete any node in the configuration along with all of its
  12996. child nodes.
  12997. The right panel provides a |QScrollArea|. When a node is selected from the tree
  12998. view, the appropriate configuration widget will be inserted into that area.
  12999. When a configuration widget adds a new node to the device model, the parent
  13000. node (which should be the currently selected node but the code does not assume
  13001. this) is expanded to show the new child node if it has not already been
  13002. expanded.
  13003. @<DeviceConfigurationWindow implementation@>=
  13004. DeviceConfigurationWindow::DeviceConfigurationWindow() : QMainWindow(NULL),
  13005. view(new QTreeView), configArea(new QScrollArea)
  13006. {
  13007. QSplitter *splitter = new QSplitter;
  13008. QWidget *leftWidget = new QWidget;
  13009. leftWidget->setMinimumWidth(200);
  13010. QVBoxLayout *left = new QVBoxLayout;
  13011. view->setAnimated(true);
  13012. view->setSelectionMode(QAbstractItemView::SingleSelection);
  13013. document = AppInstance->deviceConfiguration();
  13014. model = new DeviceTreeModel;
  13015. view->setModel(model);
  13016. view->expandAll();
  13017. connect(model, SIGNAL(modelReset()), view, SLOT(expandAll()));
  13018. QHBoxLayout *treeButtons = new QHBoxLayout;
  13019. QToolButton *addDeviceButton = new QToolButton;
  13020. addDeviceButton->setIcon(QIcon::fromTheme("list-add"));
  13021. addDeviceButton->setToolTip(tr("New Roaster"));
  13022. connect(addDeviceButton, SIGNAL(clicked()),
  13023. this, SLOT(addDevice()));
  13024. QToolButton *removeNodeButton = new QToolButton;
  13025. removeNodeButton->setIcon(QIcon::fromTheme("list-remove"));
  13026. removeNodeButton->setToolTip(tr("Delete Selection"));
  13027. connect(removeNodeButton, SIGNAL(clicked()), this, SLOT(removeNode()));
  13028. treeButtons->addWidget(addDeviceButton);
  13029. treeButtons->addWidget(removeNodeButton);
  13030. left->addWidget(view);
  13031. left->addLayout(treeButtons);
  13032. leftWidget->setLayout(left);
  13033. splitter->addWidget(leftWidget);
  13034. configArea->setMinimumWidth(580);
  13035. configArea->setMinimumHeight(460);
  13036. splitter->addWidget(configArea);
  13037. setCentralWidget(splitter);
  13038. connect(view, SIGNAL(activated(QModelIndex)),
  13039. this, SLOT(newSelection(QModelIndex)));
  13040. connect(view, SIGNAL(clicked(QModelIndex)),
  13041. this, SLOT(newSelection(QModelIndex)));
  13042. connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)),
  13043. view, SLOT(expand(QModelIndex)));
  13044. }
  13045. @ Adding a new top level node to the model is just a matter of extracting the
  13046. required information from the signal requesting that addition.
  13047. @<DeviceConfigurationWindow implementation@>=
  13048. void DeviceConfigurationWindow::addDevice()
  13049. {
  13050. model->newNode(tr("New Roaster"), "roaster", QModelIndex());
  13051. }
  13052. @ Removing the currently selected node is also simple.
  13053. @<DeviceConfigurationWindow implementation@>=
  13054. void DeviceConfigurationWindow::removeNode()
  13055. {
  13056. QModelIndex index = view->currentIndex();
  13057. if(index.isValid())
  13058. {
  13059. int row = index.row();
  13060. QModelIndex parent = index.parent();
  13061. model->removeRow(row, parent);
  13062. }
  13063. }
  13064. @ Due to most of the required logic being implemented in
  13065. |Application::deviceConfigurationWidget()|, inserting the proper editor in the
  13066. right area is also trivial.
  13067. @<DeviceConfigurationWindow implementation@>=
  13068. void DeviceConfigurationWindow::newSelection(const QModelIndex &index)
  13069. {
  13070. QWidget *editor = AppInstance->deviceConfigurationWidget(model, index);
  13071. if(editor)
  13072. {
  13073. configArea->setWidget(editor);
  13074. editor->show();
  13075. }
  13076. }
  13077. @ At least for the initial testing of this feature it will be useful if we can
  13078. instantiate this from the host environment. For this we at least require a
  13079. constructor.
  13080. @<Function prototypes for scripting@>=
  13081. QScriptValue constructDeviceConfigurationWindow(QScriptContext *context,
  13082. QScriptEngine *engine);
  13083. @ The constructor is trivial.
  13084. @<Functions for scripting@>=
  13085. QScriptValue constructDeviceConfigurationWindow(QScriptContext *,
  13086. QScriptEngine *engine)
  13087. {
  13088. QScriptValue object = engine->newQObject(new DeviceConfigurationWindow);
  13089. return object;
  13090. }
  13091. @ Finally we inform the host environment of this constructor.
  13092. @<Set up the scripting engine@>=
  13093. constructor = engine->newFunction(constructDeviceConfigurationWindow);
  13094. value = engine->newQMetaObject(&DeviceConfigurationWindow::staticMetaObject,
  13095. constructor);
  13096. engine->globalObject().setProperty("DeviceConfigurationWindow", value);
  13097. @* A Common Base Class for Device Configuration Widgets.
  13098. \noindent There are certain operations that are very commonly required
  13099. among device configuration widgets. These common elements have been implemented
  13100. in a base class.
  13101. @<Class declarations@>=
  13102. class BasicDeviceConfigurationWidget : public QWidget
  13103. {
  13104. @[Q_OBJECT@]@;
  13105. public:@/
  13106. BasicDeviceConfigurationWidget(DeviceTreeModel *model,
  13107. const QModelIndex &index);
  13108. @[public slots@]:@/
  13109. void insertChildNode(const QString &name, const QString &driver);
  13110. void updateAttribute(const QString &name, const QString &value);
  13111. protected:@/
  13112. DeviceTreeModel *deviceModel;
  13113. QModelIndex currentNode;
  13114. };
  13115. @ The constructor just passes its arguments to a pair of protected data
  13116. members. These are commonly required in subclasses but need not be exposed
  13117. outside of this branch of the object hierarchy.
  13118. @<BasicDeviceConfigurationWidget implementation@>=
  13119. BasicDeviceConfigurationWidget::BasicDeviceConfigurationWidget(
  13120. DeviceTreeModel *model, const QModelIndex &index)
  13121. : QWidget(NULL), deviceModel(model), currentNode(index)
  13122. {
  13123. /* Nothing needs to be done here. */
  13124. }
  13125. @ The |updateAttribute()| method sets the value property of an attribute
  13126. element of a given name that is a child of the current node, creating the
  13127. element if it does not exist.
  13128. @<BasicDeviceConfigurationWidget implementation@>=
  13129. void BasicDeviceConfigurationWidget::updateAttribute(const QString &name,
  13130. const QString &value)
  13131. {
  13132. QDomElement referenceElement = deviceModel->referenceElement(
  13133. deviceModel->data(currentNode, Qt::UserRole).toString());
  13134. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  13135. QDomElement node;
  13136. bool found = false;
  13137. for(int i = 0; i < configData.size(); i++)
  13138. {
  13139. node = configData.at(i).toElement();
  13140. if(node.attribute("name") == name)
  13141. {
  13142. node.setAttribute("value", value);
  13143. found = true;
  13144. break;
  13145. }
  13146. }
  13147. if(!found)
  13148. {
  13149. node = AppInstance->deviceConfiguration().createElement("attribute");
  13150. node.setAttribute("name", name);
  13151. node.setAttribute("value", value);
  13152. referenceElement.appendChild(node);
  13153. }
  13154. AppInstance->saveDeviceConfiguration();
  13155. }
  13156. @ The |insertChildNode()| method constructs a new node with the specified name
  13157. and driver as a child of the current node. Node insertion is a generic
  13158. operation that does not require any knowledge of the configuration options that
  13159. will be presented in that node.
  13160. @<BasicDeviceConfigurationWidget implementation@>=
  13161. void BasicDeviceConfigurationWidget::insertChildNode(const QString &name,
  13162. const QString &driver)
  13163. {
  13164. deviceModel->newNode(name, driver, currentNode);
  13165. }
  13166. @** Configuration of Top Level Roaster Nodes.
  13167. \noindent The first configuration widget required is one for defining a coffee
  13168. roaster. This stores the identification number that will be used for machine
  13169. references in the database and also provides controls for adding all of the
  13170. required child nodes for hardware and configurable elements of the logging
  13171. window that may vary from one machine to the next.
  13172. All of the configuration widgets follow a similar pattern. One important detail
  13173. to note is that these configuration widgets are instantiated through Qt's
  13174. meta-object system. All of these constructors take a |DeviceTreeModel *| and a
  13175. |QModelIndex &| as arguments and they are marked as |Q_INVOKABLE|.
  13176. @<Class declarations@>=
  13177. class RoasterConfWidget : public BasicDeviceConfigurationWidget
  13178. {
  13179. @[Q_OBJECT@]@;
  13180. public:@/
  13181. @[Q_INVOKABLE@]@, RoasterConfWidget(DeviceTreeModel *model,
  13182. const QModelIndex &index);
  13183. @[private slots@]:@/
  13184. void updateRoasterId(int id);
  13185. };
  13186. @ Aside from the ID number used to identify the roaster in the database we also
  13187. need controls to add child nodes. In order to limit the number of options in
  13188. menus for adding child nodes, these are organized into groups that are
  13189. available through different controls.
  13190. @<RoasterConfWidget implementation@>=
  13191. RoasterConfWidget::RoasterConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  13192. : BasicDeviceConfigurationWidget(model, index)
  13193. {
  13194. QVBoxLayout *layout = new QVBoxLayout;
  13195. QPushButton *addDeviceButton = new QPushButton(tr("Add Device"));
  13196. QMenu *deviceMenu = new QMenu;
  13197. NodeInserter *insertAction;
  13198. foreach(insertAction, AppInstance->topLevelNodeInserters)
  13199. {
  13200. connect(insertAction, SIGNAL(triggered(QString, QString)),
  13201. this, SLOT(insertChildNode(QString, QString)));
  13202. deviceMenu->addAction(insertAction);
  13203. }
  13204. addDeviceButton->setMenu(deviceMenu);
  13205. layout->addWidget(addDeviceButton);
  13206. QPushButton *addAnnotationControlButton = new QPushButton(tr("Add Annotation Control"));
  13207. QMenu *annotationMenu = new QMenu;
  13208. NodeInserter *basicButtonInserter = new NodeInserter(tr("Annotation Button"), tr("Annotation Button"), "annotationbutton");
  13209. NodeInserter *countingButtonInserter = new NodeInserter(tr("Counting Button"), tr("Counting Button"), "reconfigurablebutton");
  13210. NodeInserter *spinBoxInserter = new NodeInserter(tr("Numeric Entry"), tr("Numeric Entry"), "annotationspinbox");
  13211. annotationMenu->addAction(basicButtonInserter);
  13212. annotationMenu->addAction(countingButtonInserter);
  13213. annotationMenu->addAction(spinBoxInserter);
  13214. connect(basicButtonInserter, SIGNAL(triggered(QString, QString)),
  13215. this, SLOT(insertChildNode(QString, QString)));
  13216. connect(countingButtonInserter, SIGNAL(triggered(QString, QString)),
  13217. this, SLOT(insertChildNode(QString, QString)));
  13218. connect(spinBoxInserter, SIGNAL(triggered(QString, QString)),
  13219. this, SLOT(insertChildNode(QString, QString)));
  13220. addAnnotationControlButton->setMenu(annotationMenu);
  13221. layout->addWidget(addAnnotationControlButton);
  13222. QPushButton *advancedButton = new QPushButton(tr("Advanced Features"));
  13223. QMenu *advancedMenu = new QMenu;
  13224. NodeInserter *linearsplineinserter = new NodeInserter(tr("Linear Spline Interpolated Series"), tr("Linear Spline Interpolated Series"), "linearspline");
  13225. advancedMenu->addAction(linearsplineinserter);
  13226. NodeInserter *translationinserter = new NodeInserter(tr("Profile Translation"), tr("Profile Translation"), "translation");
  13227. advancedMenu->addAction(translationinserter);
  13228. connect(linearsplineinserter, SIGNAL(triggered(QString, QString)), this, SLOT(insertChildNode(QString, QString)));
  13229. connect(translationinserter, SIGNAL(triggered(QString, QString)), this, SLOT(insertChildNode(QString, QString)));
  13230. advancedButton->setMenu(advancedMenu);
  13231. layout->addWidget(advancedButton);
  13232. QHBoxLayout *idLayout = new QHBoxLayout;
  13233. QLabel *idLabel = new QLabel(tr("Machine ID for database:"));
  13234. idLayout->addWidget(idLabel);
  13235. QSpinBox *id = new QSpinBox;
  13236. idLayout->addWidget(id);
  13237. layout->addLayout(idLayout);
  13238. @<Get device configuration data for current node@>@;
  13239. for(int i = 0; i < configData.size(); i++)
  13240. {
  13241. node = configData.at(i).toElement();
  13242. if(node.attribute("name") == "databaseid")
  13243. {
  13244. id->setValue(node.attribute("value").toInt());
  13245. break;
  13246. }
  13247. }
  13248. updateRoasterId(id->value());
  13249. connect(id, SIGNAL(valueChanged(int)), this, SLOT(updateRoasterId(int)));
  13250. setLayout(layout);
  13251. }
  13252. @ Iterating over the configuration data associated with the current node is
  13253. required in nearly every configuration widget. The specifics of the loop
  13254. vary, but there is likely a better way to generalize that. Until then,
  13255. obtaining a |QDomNodeList| with the required data to iterate over has been
  13256. split off as its own chunk to reduce the risk of errors associated with typing
  13257. the same code many times.
  13258. @<Get device configuration data for current node@>=
  13259. QDomElement referenceElement =
  13260. model->referenceElement(model->data(index, Qt::UserRole).toString());
  13261. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  13262. QDomElement node;
  13263. @ We need to propagate changes to the ID number field to the device
  13264. configuration document. The |updateAttribute()| method in the base class
  13265. makes this trivial.
  13266. @<RoasterConfWidget implementation@>=
  13267. void RoasterConfWidget::updateRoasterId(int id)
  13268. {
  13269. updateAttribute("databaseid", QString("%1").arg(id));
  13270. }
  13271. @ Finally we must register the configuration widget so that it can be
  13272. instantiated at the appropriate time.
  13273. @<Register device configuration widgets@>=
  13274. app.registerDeviceConfigurationWidget("roaster", RoasterConfWidget::staticMetaObject);
  13275. @** Configuration for NI-DAQmx Base devices.
  13276. \noindent The primary concern in supporting hardware that communicates through
  13277. NI-DAQmx Base is in configurations using a single NI USB 9211 (for NI-DAQmx
  13278. Base 2.x) or NI USB 9211A (for NI-DAQmx Base 3.x), but if it is reasonable to
  13279. do so I'd like to later add support for multiple device configurations and
  13280. limited support for other devices including the ability to use devices with
  13281. voltage inputs for non-temperature measurement data. The top priority, however,
  13282. is in continuing to support hardware that people are already using with Typica.
  13283. In order to more easily implement these future plans, device configuration is
  13284. handled with three configuration tiers. The top level configuration node
  13285. indicates that we are using NI-DAQmx Base. Here we can add a child node
  13286. representing either a NI USB 9211 or NI USB 9211A. From a configuration
  13287. perspective these are identical with the default node name as the only
  13288. difference. From the device configuration we can specify the device identifier
  13289. and add channels to the device. In the channel nodes we specify the
  13290. thermocouple type.
  13291. @<Class declarations@>=
  13292. class NiDaqMxBaseDriverConfWidget : public BasicDeviceConfigurationWidget
  13293. {
  13294. @[Q_OBJECT@]@;
  13295. public:@/
  13296. @[Q_INVOKABLE@]@, NiDaqMxBaseDriverConfWidget(DeviceTreeModel *model,@|
  13297. const QModelIndex &index);
  13298. };
  13299. @ There is very little to configure here so there isn't much for the
  13300. constructor to do. We do need to keep a reference to the node we are
  13301. configuring so that child nodes can later be added. At present, no real
  13302. configuration data other than the existence of the node is required so
  13303. there is no need to read any configuration data here.
  13304. @<NiDaqMxBaseDriverConfWidget implementation@>=
  13305. NiDaqMxBaseDriverConfWidget::NiDaqMxBaseDriverConfWidget(
  13306. DeviceTreeModel *model, const QModelIndex &index) :
  13307. BasicDeviceConfigurationWidget(model, index)
  13308. {
  13309. QHBoxLayout *layout = new QHBoxLayout;
  13310. QToolButton *addDeviceButton = new QToolButton;
  13311. addDeviceButton->setText(tr("Add Device"));
  13312. NodeInserter *add9211 = new NodeInserter("NI USB 9211", "NI USB 9211",
  13313. "nidaqmxbase9211series");
  13314. NodeInserter *add9211a = new NodeInserter("NI USB 9211A", "NI USB 9211A",
  13315. "nidaqmxbase9211series");
  13316. connect(add9211, SIGNAL(triggered(QString, QString)),
  13317. this, SLOT(insertChildNode(QString, QString)));
  13318. connect(add9211a, SIGNAL(triggered(QString, QString)),
  13319. this, SLOT(insertChildNode(QString, QString)));
  13320. QMenu *deviceMenu = new QMenu;
  13321. deviceMenu->addAction(add9211);
  13322. deviceMenu->addAction(add9211a);
  13323. addDeviceButton->setMenu(deviceMenu);
  13324. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  13325. layout->addWidget(addDeviceButton);
  13326. setLayout(layout);
  13327. }
  13328. @ Both the NI USB 9211 and NI USB 9211A are identical from a configuration
  13329. perspective. The only difference is the version of NI-DAQmx Base required for
  13330. use. As the API does not provide a way of determining which version is
  13331. installed, ensuring that the appropriate software is installed without
  13332. conflicts is left as an exercise for the person attempting to use \pn{}.
  13333. @<Class declarations@>=
  13334. class NiDaqMxBase9211ConfWidget : public BasicDeviceConfigurationWidget
  13335. {
  13336. Q_OBJECT
  13337. public:
  13338. Q_INVOKABLE NiDaqMxBase9211ConfWidget(DeviceTreeModel *device,
  13339. const QModelIndex &index);
  13340. private slots:
  13341. void addChannel();
  13342. void updateDeviceId(const QString &newId);
  13343. };
  13344. @ There are two controls required in a configuration widget for this device.
  13345. The first is the device identifier (for example, "Dev1"), the second is a
  13346. button for adding channels to the device. On a generic device we would also
  13347. need to set the clock rate, but with this hardware it is possible to determine
  13348. the maximum clock rate from the channels defined.
  13349. @<NiDaqMxBase9211ConfWidget implementation@>=
  13350. NiDaqMxBase9211ConfWidget::NiDaqMxBase9211ConfWidget(DeviceTreeModel *model,
  13351. const QModelIndex &index)
  13352. : BasicDeviceConfigurationWidget(model, index)
  13353. {
  13354. QVBoxLayout *layout = new QVBoxLayout;
  13355. QHBoxLayout *deviceIdLayout = new QHBoxLayout;
  13356. QLabel *label = new QLabel(tr("Device ID:"));
  13357. QLineEdit *deviceId = new QLineEdit;
  13358. deviceIdLayout->addWidget(label);
  13359. deviceIdLayout->addWidget(deviceId);
  13360. QPushButton *addChannelButton = new QPushButton(tr("Add Channel"));
  13361. layout->addLayout(deviceIdLayout);
  13362. layout->addWidget(addChannelButton);
  13363. @<Get device configuration data for current node@>@;
  13364. for(int i = 0; i < configData.size(); i++)
  13365. {
  13366. node = configData.at(i).toElement();
  13367. if(node.attribute("name") == "deviceID")
  13368. {
  13369. deviceId->setText(node.attribute("value", "Dev1"));
  13370. break;
  13371. }
  13372. }
  13373. updateDeviceId(deviceId->text());
  13374. connect(addChannelButton, SIGNAL(clicked()),
  13375. this, SLOT(addChannel()));
  13376. connect(deviceId, SIGNAL(textEdited(QString)),
  13377. this, SLOT(updateDeviceId(QString)));
  13378. setLayout(layout);
  13379. }
  13380. @ Updating the attribute tag under the reference element associated with the
  13381. current node is handled in the base class so we just need to pass in the
  13382. appropriate name value pair.
  13383. @<NiDaqMxBase9211ConfWidget implementation@>=
  13384. void NiDaqMxBase9211ConfWidget::updateDeviceId(const QString &newId)
  13385. {
  13386. updateAttribute("deviceID", newId);
  13387. }
  13388. @ Adding channels is just like adding any other sort of node.
  13389. @<NiDaqMxBase9211ConfWidget implementation@>=
  13390. void NiDaqMxBase9211ConfWidget::addChannel()
  13391. {
  13392. insertChildNode(tr("Thermocouple channel"), "ni9211seriestc");
  13393. }
  13394. @ Finally, we need a configuration widget to handle our thermocouple channels.
  13395. Ordinarily we would need three pieces of information for each channel. First
  13396. there is the thermocouple channel. Previously this was left implied by the
  13397. order of requests for a new channel, but more flexible configuration options
  13398. become possible with a more explicit specification. Since this widget is device
  13399. specific, all of the options can be easily enumerated to match markings on the
  13400. device. Next is the thermocouple type. Many options are supported, but I would
  13401. like to ensure that the most commonly used choices are listed first. The other
  13402. piece of information that DAQmx or DAQmx Base require is the measurement unit.
  13403. As all of Typica's internal operations are in Fahrenheit there is no need to
  13404. make this configurable so long as everything else that can display temperature
  13405. measurements can perform the appropriate conversions.
  13406. Note that as there are no configuration differences between the various
  13407. device combinations using an NI 9211 module with regard to thermocouple channel
  13408. configuration, we can use this widget with all device combinations that make
  13409. use of such a module.
  13410. @<Class declarations@>=
  13411. class Ni9211TcConfWidget : public BasicDeviceConfigurationWidget
  13412. {
  13413. @[Q_OBJECT@]@/
  13414. public:@/
  13415. Q_INVOKABLE Ni9211TcConfWidget(DeviceTreeModel *device,
  13416. const QModelIndex &index);
  13417. @[private slots@]:@/
  13418. void updateThermocoupleType(const QString &type);
  13419. void updateColumnName(const QString &name);
  13420. };
  13421. @ This follows the same pattern of previous device configuration widgets. The
  13422. constructor provides the required configuration controls and slot methods
  13423. catch configuration changes and update the underlying XML document
  13424. appropriately.
  13425. @<Ni9211TcConfWidget implementation@>=
  13426. Ni9211TcConfWidget::Ni9211TcConfWidget(DeviceTreeModel *model,
  13427. const QModelIndex &index) :
  13428. BasicDeviceConfigurationWidget(model, index)
  13429. {
  13430. QFormLayout *layout = new QFormLayout;
  13431. QLineEdit *columnName = new QLineEdit;
  13432. layout->addRow(tr("Column Name:"), columnName);
  13433. QComboBox *typeSelector = new QComboBox;
  13434. typeSelector->addItem("J");
  13435. typeSelector->addItem("K");
  13436. typeSelector->addItem("T");
  13437. typeSelector->addItem("B");
  13438. typeSelector->addItem("E");
  13439. typeSelector->addItem("N");
  13440. typeSelector->addItem("R");
  13441. typeSelector->addItem("S");
  13442. layout->addRow(tr("Thermocouple Type:"), typeSelector);
  13443. setLayout(layout);
  13444. @<Get device configuration data for current node@>@;
  13445. for(int i = 0; i < configData.size(); i++)
  13446. {
  13447. node = configData.at(i).toElement();
  13448. if(node.attribute("name") == "type")
  13449. {
  13450. typeSelector->setCurrentIndex(
  13451. typeSelector->findText(node.attribute("value")));
  13452. }
  13453. else if(node.attribute("name") == "columnname")
  13454. {
  13455. columnName->setText(node.attribute("value"));
  13456. }
  13457. }
  13458. updateThermocoupleType(typeSelector->currentText());
  13459. updateColumnName(columnName->text());
  13460. connect(typeSelector, SIGNAL(currentIndexChanged(QString)),
  13461. this, SLOT(updateThermocoupleType(QString)));
  13462. connect(columnName, SIGNAL(textEdited(QString)), this, SLOT(updateColumnName(QString)));
  13463. }
  13464. @ Two slots are used to pass configuration changes back to the underlying XML
  13465. representation.
  13466. @<Ni9211TcConfWidget implementation@>=
  13467. void Ni9211TcConfWidget::updateThermocoupleType(const QString &type)
  13468. {
  13469. updateAttribute("type", type);
  13470. }
  13471. void Ni9211TcConfWidget::updateColumnName(const QString &name)
  13472. {
  13473. updateAttribute("columnname", name);
  13474. }
  13475. @ These three widgets need to be registered so the configuration widget can
  13476. instantiate them when the nodes are selected.
  13477. @<Register device configuration widgets@>=
  13478. app.registerDeviceConfigurationWidget("nidaqmxbase",
  13479. NiDaqMxBaseDriverConfWidget::staticMetaObject);
  13480. app.registerDeviceConfigurationWidget("nidaqmxbase9211series",
  13481. NiDaqMxBase9211ConfWidget::staticMetaObject);
  13482. app.registerDeviceConfigurationWidget("ni9211seriestc",
  13483. Ni9211TcConfWidget::staticMetaObject);
  13484. @ Furthermore, we should create the NodeInserter objects for adding top level
  13485. nodes to the configuration. Preferably we would only allow top level nodes to
  13486. be inserted when all prerequisite software is available.
  13487. @<Register top level device configuration nodes@>=
  13488. NodeInserter *inserter = new NodeInserter(tr("NI DAQmx Base Device"),
  13489. tr("NI DAQmx Base"),
  13490. "nidaqmxbase", NULL);
  13491. topLevelNodeInserters.append(inserter);
  13492. @** Configuration of NI-DAQmx devices.
  13493. \noindent The other main class of hardware currently supported in Typica is a
  13494. small set of devices that require NI-DAQmx. This includes a few combinations of
  13495. the NI 9211 in different carriers and the NI USB TC01. Additional hardware may
  13496. be added to this set in the future.
  13497. The approach here is very similar to the approach used to configure NI-DAQmx
  13498. Base devices, starting with a widget for adding child device nodes.
  13499. @<Class declarations@>=
  13500. class NiDaqMxDriverConfWidget : public BasicDeviceConfigurationWidget
  13501. {
  13502. @[Q_OBJECT@]@;
  13503. public:
  13504. @[Q_INVOKABLE@]@, NiDaqMxDriverConfWidget(DeviceTreeModel *model,
  13505. const QModelIndex &index);
  13506. };
  13507. @ Under our driver node we want to have the ability to insert device specific
  13508. child nodes.
  13509. @<NiDaqMxDriverConfWidget implementation@>=
  13510. NiDaqMxDriverConfWidget::NiDaqMxDriverConfWidget(DeviceTreeModel *model,
  13511. const QModelIndex &index)
  13512. : BasicDeviceConfigurationWidget(model, index)
  13513. {
  13514. QHBoxLayout *layout = new QHBoxLayout;
  13515. QToolButton *addDeviceButton = new QToolButton;
  13516. addDeviceButton->setText(tr("Add Device"));
  13517. NodeInserter *add9211a = new NodeInserter("NI USB 9211A", "NI USB 9211A",
  13518. "nidaqmx9211series");
  13519. NodeInserter *addtc01 = new NodeInserter("NI USB TC01", "NI USB TC01",
  13520. "nidaqmxtc01");
  13521. connect(add9211a, SIGNAL(triggered(QString, QString)),
  13522. this, SLOT(insertChildNode(QString, QString)));
  13523. connect(addtc01, SIGNAL(triggered(QString, QString)),
  13524. this, SLOT(insertChildNode(QString, QString)));
  13525. QMenu *deviceMenu = new QMenu;
  13526. deviceMenu->addAction(add9211a);
  13527. deviceMenu->addAction(addtc01);
  13528. addDeviceButton->setMenu(deviceMenu);
  13529. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  13530. layout->addWidget(addDeviceButton);
  13531. setLayout(layout);
  13532. }
  13533. @ Devices based on the 9211 module are essentially the same aside from device
  13534. naming convention. Configuring these is very similar to configuring similar
  13535. devices when using NI-DAQmx Base.
  13536. @<Class declarations@>=
  13537. class NiDaqMx9211ConfWidget : public BasicDeviceConfigurationWidget
  13538. {
  13539. @[Q_OBJECT@]@;
  13540. public:@/
  13541. @[Q_INVOKABLE@]@, NiDaqMx9211ConfWidget(DeviceTreeModel *model,
  13542. const QModelIndex &index);
  13543. @[private slots@]:@/
  13544. void addChannel();
  13545. void updateDeviceId(const QString &newId);
  13546. };
  13547. @ Implementation is essentially identical to the NI-DAQmx Base class. It is
  13548. likely that there will be differences if this is ever extended to support
  13549. automatic detection of connected hardware. While NI-DAQmx Base does not
  13550. provide a way to query device identifiers, it uses a consistent naming scheme
  13551. by which device identifiers can be discovered. While NI-DAQmx lacks the same
  13552. consistency in device identifiers, it does provide a way to query that
  13553. information.
  13554. @<NiDaqMx9211ConfWidget implementation@>=
  13555. NiDaqMx9211ConfWidget::NiDaqMx9211ConfWidget(DeviceTreeModel *model,
  13556. const QModelIndex &index)
  13557. : BasicDeviceConfigurationWidget(model, index)
  13558. {
  13559. QVBoxLayout *layout = new QVBoxLayout;
  13560. QHBoxLayout *deviceIdLayout = new QHBoxLayout;
  13561. QLabel *label = new QLabel(tr("Device ID:"));
  13562. QLineEdit *deviceId = new QLineEdit;
  13563. deviceIdLayout->addWidget(label);
  13564. deviceIdLayout->addWidget(deviceId);
  13565. QPushButton *addChannelButton = new QPushButton(tr("Add Channel"));
  13566. layout->addLayout(deviceIdLayout);
  13567. layout->addWidget(addChannelButton);
  13568. @<Get device configuration data for current node@>@;
  13569. for(int i = 0; i < configData.size(); i++)
  13570. {
  13571. node = configData.at(i).toElement();
  13572. if(node.attribute("name") == "deviceID")
  13573. {
  13574. deviceId->setText(node.attribute("value","Dev1"));
  13575. break;
  13576. }
  13577. }
  13578. updateDeviceId(deviceId->text());
  13579. connect(addChannelButton, SIGNAL(clicked()), this, SLOT(addChannel()));
  13580. connect(deviceId, SIGNAL(textEdited(QString)),
  13581. this, SLOT(updateDeviceId(QString)));
  13582. setLayout(layout);
  13583. }
  13584. void NiDaqMx9211ConfWidget::updateDeviceId(const QString &newId)
  13585. {
  13586. updateAttribute("deviceID", newId);
  13587. }
  13588. void NiDaqMx9211ConfWidget::addChannel()
  13589. {
  13590. insertChildNode(tr("Thermocouple channel"), "ni9211seriestc");
  13591. }
  13592. @ There is no need to create a configuration widget specific to the 9211 module
  13593. used in NI-DAQmx. The widget already used for NI-DAQmx Base can be used without
  13594. modification.
  13595. Configuring Typica for use with the NI USB-TC01 can be slightly simplified as
  13596. the device only has a single thermocouple channel. We can configure this without
  13597. requiring another node.
  13598. @<Class declarations@>=
  13599. class NiDaqMxTc01ConfWidget : public BasicDeviceConfigurationWidget
  13600. {
  13601. @[Q_OBJECT@]@;
  13602. public:@/
  13603. @[Q_INVOKABLE@]@, NiDaqMxTc01ConfWidget(DeviceTreeModel *model,
  13604. const QModelIndex &index);
  13605. @[private slots@]:@/
  13606. void updateDeviceId(const QString &newId);
  13607. void updateThermocoupleType(const QString &type);
  13608. void updateColumnName(const QString &name);
  13609. };
  13610. @ The implementation is similar to the other configuration widgets.
  13611. @<NiDaqMxTc01ConfWidget implementation@>=
  13612. NiDaqMxTc01ConfWidget::NiDaqMxTc01ConfWidget(DeviceTreeModel *model,
  13613. const QModelIndex &index)
  13614. : BasicDeviceConfigurationWidget(model, index)
  13615. {
  13616. QFormLayout *layout = new QFormLayout;
  13617. QLineEdit *deviceId = new QLineEdit;
  13618. layout->addRow(tr("Device ID:"), deviceId);
  13619. QLineEdit *columnName = new QLineEdit;
  13620. layout->addRow(tr("Column Name:"), columnName);
  13621. QComboBox *typeSelector = new QComboBox;
  13622. typeSelector->addItem("J");
  13623. typeSelector->addItem("K");
  13624. typeSelector->addItem("T");
  13625. typeSelector->addItem("B");
  13626. typeSelector->addItem("E");
  13627. typeSelector->addItem("N");
  13628. typeSelector->addItem("R");
  13629. typeSelector->addItem("S");
  13630. layout->addRow(tr("Thermocouple Type:"), typeSelector);
  13631. @<Get device configuration data for current node@>@;
  13632. for(int i = 0; i < configData.size(); i++)
  13633. {
  13634. node = configData.at(i).toElement();
  13635. if(node.attribute("name") == "deviceID")
  13636. {
  13637. deviceId->setText(node.attribute("value"));
  13638. }
  13639. else if(node.attribute("name") == "type")
  13640. {
  13641. typeSelector->setCurrentIndex(typeSelector->findText(node.attribute("value")));
  13642. }
  13643. else if(node.attribute("name") == "columnname")
  13644. {
  13645. columnName->setText(node.attribute("value"));
  13646. }
  13647. }
  13648. updateDeviceId(deviceId->text());
  13649. updateThermocoupleType(typeSelector->currentText());
  13650. updateColumnName(columnName->text());
  13651. connect(deviceId, SIGNAL(textEdited(QString)), this, SLOT(updateDeviceId(QString)));
  13652. connect(typeSelector, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateThermocoupleType(QString)));
  13653. connect(columnName, SIGNAL(textEdited(QString)), this, SLOT(updateColumnName(QString)));
  13654. setLayout(layout);
  13655. }
  13656. void NiDaqMxTc01ConfWidget::updateDeviceId(const QString &newId)
  13657. {
  13658. updateAttribute("deviceID", newId);
  13659. }
  13660. void NiDaqMxTc01ConfWidget::updateThermocoupleType(const QString &type)
  13661. {
  13662. updateAttribute("type", type);
  13663. }
  13664. void NiDaqMxTc01ConfWidget::updateColumnName(const QString &name)
  13665. {
  13666. updateAttribute("columnname", name);
  13667. }
  13668. @ These configuration widgets need to be registered so they can be instantiated
  13669. in response to node selections.
  13670. @<Register device configuration widgets@>=
  13671. app.registerDeviceConfigurationWidget("nidaqmx", NiDaqMxDriverConfWidget::staticMetaObject);
  13672. app.registerDeviceConfigurationWidget("nidaqmx9211series", NiDaqMx9211ConfWidget::staticMetaObject);
  13673. app.registerDeviceConfigurationWidget("nidaqmxtc01", NiDaqMxTc01ConfWidget::staticMetaObject);
  13674. @ A |NodeInserter| for the driver configuration widget is also needed. Note that
  13675. at present NI DAQmx is only available on Windows so we do not bother to show
  13676. the option on other platforms. It would be generally preferable to replace this
  13677. with a check at runtime to determine if the required library exists. That could
  13678. be done with anything that requires third party installed code, leaving by
  13679. default only those options which have no external dependencies.
  13680. @<Register top level device configuration nodes@>=
  13681. #ifdef Q_OS_WIN32
  13682. inserter = new NodeInserter(tr("NI DAQmx Device"), tr("NI DAQmx"), "nidaqmx", NULL);
  13683. topLevelNodeInserters.append(inserter);
  13684. #endif
  13685. @** Configuration of Serial Port Devices.
  13686. \noindent It is possible to communicate with a number of devices through a
  13687. serial port. To do this, the appropriate settings for opening the port are
  13688. required and the communications protocol understood by the device must be
  13689. known. Serial port communications are provided by QextSerialPort. That
  13690. project was released under the MIT license.\nfnote{See the license text for
  13691. more information.} Additional headers are required.
  13692. @<Header files to include@>=
  13693. #include "qextserialport.h"
  13694. #include "qextserialenumerator.h"
  13695. @ Some custom widgets are provided which allow selecting the relevant
  13696. connection options from combo boxes. First there is a widget for selecting
  13697. the desired serial port. The drop down is pre-populated with any serial ports
  13698. that could be automatically detected, but the field can also be edited to
  13699. other values as may be required if the hardware is not connected during
  13700. configuration.
  13701. @<Class declarations@>=
  13702. class PortSelector : public QComboBox
  13703. {
  13704. Q_OBJECT
  13705. public:
  13706. PortSelector(QWidget *parent = NULL);
  13707. private slots:
  13708. void addDevice(QextPortInfo port);
  13709. private:
  13710. QextSerialEnumerator *lister;
  13711. };
  13712. @ The implementation is trivial.
  13713. @<PortSelector implementation@>=
  13714. PortSelector::PortSelector(QWidget *parent) : QComboBox(parent),
  13715. lister(new QextSerialEnumerator)
  13716. {
  13717. QList<QextPortInfo> ports = QextSerialEnumerator::getPorts();
  13718. QextPortInfo port;
  13719. foreach(port, ports)
  13720. {
  13721. addItem(port.portName);
  13722. }
  13723. lister->setUpNotifications();
  13724. connect(lister, SIGNAL(deviceDiscovered(QextPortInfo)),
  13725. this, SLOT(addDevice(QextPortInfo)));
  13726. setEditable(true);
  13727. }
  13728. void PortSelector::addDevice(QextPortInfo port)
  13729. {
  13730. addItem(port.portName);
  13731. }
  13732. @ Next is a widget which allows selecting the baud rate. Only rates supported
  13733. by the current operating system are available to select.
  13734. A later version of QextSerialPort than is used by \pn{} provides a helper
  13735. class which can be used more conveniently to create this sort of control. As
  13736. this is not yet available to \pn{}, we instead copy the |enum| specifying
  13737. the appropriate values into the class and use Qt's meta-object system to
  13738. populate the combo box based on the values in that |enum|.
  13739. @<Class declarations@>=
  13740. class BaudSelector : public QComboBox
  13741. {
  13742. Q_OBJECT
  13743. Q_ENUMS(BaudRateType)
  13744. public:
  13745. BaudSelector(QWidget *parent = NULL);
  13746. enum BaudRateType
  13747. {
  13748. #if defined(Q_OS_UNIX) || defined(qdoc)
  13749. BAUD50 = 50, //POSIX ONLY
  13750. BAUD75 = 75, //POSIX ONLY
  13751. BAUD134 = 134, //POSIX ONLY
  13752. BAUD150 = 150, //POSIX ONLY
  13753. BAUD200 = 200, //POSIX ONLY
  13754. BAUD1800 = 1800, //POSIX ONLY
  13755. #if defined(B76800) || defined(qdoc)
  13756. BAUD76800 = 76800, //POSIX ONLY
  13757. #endif
  13758. #if (defined(B230400) && defined(B4000000)) || defined(qdoc)
  13759. BAUD230400 = 230400, //POSIX ONLY
  13760. BAUD460800 = 460800, //POSIX ONLY
  13761. BAUD500000 = 500000, //POSIX ONLY
  13762. BAUD576000 = 576000, //POSIX ONLY
  13763. BAUD921600 = 921600, //POSIX ONLY
  13764. BAUD1000000 = 1000000, //POSIX ONLY
  13765. BAUD1152000 = 1152000, //POSIX ONLY
  13766. BAUD1500000 = 1500000, //POSIX ONLY
  13767. BAUD2000000 = 2000000, //POSIX ONLY
  13768. BAUD2500000 = 2500000, //POSIX ONLY
  13769. BAUD3000000 = 3000000, //POSIX ONLY
  13770. BAUD3500000 = 3500000, //POSIX ONLY
  13771. BAUD4000000 = 4000000, //POSIX ONLY
  13772. #endif
  13773. #endif
  13774. #if defined(Q_OS_WIN) || defined(qdoc)
  13775. BAUD14400 = 14400, //WINDOWS ONLY
  13776. BAUD56000 = 56000, //WINDOWS ONLY
  13777. BAUD128000 = 128000, //WINDOWS ONLY
  13778. BAUD256000 = 256000, //WINDOWS ONLY
  13779. #endif
  13780. BAUD110 = 110,
  13781. BAUD300 = 300,
  13782. BAUD600 = 600,
  13783. BAUD1200 = 1200,
  13784. BAUD2400 = 2400,
  13785. BAUD4800 = 4800,
  13786. BAUD9600 = 9600,
  13787. BAUD19200 = 19200,
  13788. BAUD38400 = 38400,
  13789. BAUD57600 = 57600,
  13790. BAUD115200 = 115200
  13791. };
  13792. };
  13793. @ As the |enum| values are identical to the baud rates represented, we only
  13794. the numeric values, ignoring the names which are rather ugly.
  13795. @<BaudSelector implementation@>=
  13796. BaudSelector::BaudSelector(QWidget *parent) : QComboBox(parent)
  13797. {
  13798. QMetaObject meta = BaudSelector::staticMetaObject;
  13799. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("BaudRateType"));
  13800. for(int i = 0; i < type.keyCount(); i++)
  13801. {
  13802. addItem(QString("%1").arg(type.value(i)));
  13803. }
  13804. }
  13805. @ This same technique is used in a widget for selecting parity.
  13806. @<Class declarations@>=
  13807. class ParitySelector : public QComboBox
  13808. {
  13809. Q_OBJECT
  13810. Q_ENUMS(ParityType)
  13811. public:
  13812. ParitySelector(QWidget *parent = NULL);
  13813. enum ParityType
  13814. {
  13815. PAR_NONE,
  13816. PAR_ODD,
  13817. PAR_EVEN,
  13818. #if defined(Q_OS_WIN) || defined(qdoc)
  13819. PAR_MARK, //WINDOWS ONLY
  13820. #endif
  13821. PAR_SPACE
  13822. };
  13823. };
  13824. @ Implementation is similar to |BaudSelector| but as the values have no
  13825. apparent relation to what is represented we present the value names, placing
  13826. the corresponding value in the user data space associated with each entry.
  13827. The names here are ugly and not amenable to localization so this approach
  13828. should be reconsidered later.
  13829. @<ParitySelector implementation@>=
  13830. ParitySelector::ParitySelector(QWidget *parent) : QComboBox(parent)
  13831. {
  13832. QMetaObject meta = ParitySelector::staticMetaObject;
  13833. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("ParityType"));
  13834. for(int i = 0; i < type.keyCount(); i++)
  13835. {
  13836. addItem(QString(type.key(i)), QVariant(type.value(i)));
  13837. }
  13838. }
  13839. @ Similarly, we have a widget for selecting a method for flow control.
  13840. @<Class declarations@>=
  13841. class FlowSelector : public QComboBox
  13842. {
  13843. Q_OBJECT
  13844. Q_ENUMS(FlowType)
  13845. public:
  13846. FlowSelector(QWidget *parent = NULL);
  13847. enum FlowType
  13848. {
  13849. FLOW_OFF,
  13850. FLOW_HARDWARE,
  13851. FLOW_XONXOFF
  13852. };
  13853. };
  13854. @ Implementation follows the same pattern as in |ParitySelector|.
  13855. @<FlowSelector implementation@>=
  13856. FlowSelector::FlowSelector(QWidget *parent) : QComboBox(parent)
  13857. {
  13858. QMetaObject meta = FlowSelector::staticMetaObject;
  13859. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("FlowType"));
  13860. for(int i = 0; i < type.keyCount(); i++)
  13861. {
  13862. addItem(QString(type.key(i)), QVariant(type.value(i)));
  13863. }
  13864. }
  13865. @ We assume that the number of data bits will always be 8, though it may be
  13866. useful to later provide a control for selecting this for use with other devices
  13867. where this may not be assumed or for the sake of completion. This only leaves
  13868. specifying the number of stop bits.
  13869. @<Class declarations@>=
  13870. class StopSelector : public QComboBox
  13871. {
  13872. Q_OBJECT
  13873. Q_ENUMS(StopBitsType)
  13874. public:
  13875. StopSelector(QWidget *parent = NULL);
  13876. enum StopBitsType
  13877. {
  13878. STOP_1,
  13879. #if defined(Q_OS_WIN) || defined(qdoc)
  13880. STOP_1_5, //WINDOWS ONLY
  13881. #endif
  13882. STOP_2
  13883. };
  13884. };
  13885. @ Implementation should be familiar by now.
  13886. @<StopSelector implementation@>=
  13887. StopSelector::StopSelector(QWidget *parent) : QComboBox(parent)
  13888. {
  13889. QMetaObject meta = StopSelector::staticMetaObject;
  13890. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("StopBitsType"));
  13891. for(int i = 0; i < type.keyCount(); i++)
  13892. {
  13893. addItem(QString(type.key(i)), QVariant(type.value(i)));
  13894. }
  13895. }
  13896. @** Configuration of Serial Devices Using Modbus RTU.
  13897. \noindent One protocol that is used across a broad class of devices is called
  13898. Modbus RTU. This protocol allows multiple devices to be chained together on a
  13899. two wire bus which can be connected to a single serial port. The communication
  13900. protocol involves a single message which is sent from a master device (in this
  13901. case the computer running Typica) to a slave device (the device we would like
  13902. to obtain information from) which is followed by a response message from the
  13903. slave to the master. After a brief wait the master can then send another
  13904. message to any slave on the bus and this process repeats. Every outgoing
  13905. message provides a station address to identify which slave on the bus should
  13906. respond, a function code to identify which of a broad class of operations has
  13907. been requested, the required data for the function specified, and a cyclic
  13908. redundancy check to validate the message.
  13909. @** A Spin Box with Hexadecimal Representation.
  13910. \noindent Common convention for communications documentation for devices that
  13911. use Modbus RTU is that relative addresses are specified in hexadecimal
  13912. representation. In order to simplify initial device configuration, it would be
  13913. best that input widgets both accept input in base 16 and display values as a
  13914. four digit hexadecimal value.
  13915. @<Class declarations@>=
  13916. class ShortHexSpinBox : public QSpinBox
  13917. {
  13918. Q_OBJECT
  13919. public:
  13920. ShortHexSpinBox(QWidget *parent = NULL);
  13921. virtual QValidator::State validate(QString &input, int &pos) const;
  13922. protected:
  13923. virtual int valueFromText(const QString &text) const;
  13924. virtual QString textFromValue(int value) const;
  13925. };
  13926. @ For this we can set some new defaults in the constructor and must override
  13927. three methods.
  13928. @<ShortHexSpinBox implementation@>=
  13929. ShortHexSpinBox::ShortHexSpinBox(QWidget *parent) : QSpinBox(parent)
  13930. {
  13931. setMinimum(0);
  13932. setMaximum(0xFFFF);
  13933. setPrefix("0x");
  13934. setMinimumWidth(65);
  13935. }
  13936. QValidator::State ShortHexSpinBox::validate(QString &input, int &) const
  13937. {
  13938. if(input.size() == 2)
  13939. {
  13940. return QValidator::Intermediate;
  13941. }
  13942. bool okay;
  13943. input.toInt(&okay, 16);
  13944. if(okay)
  13945. {
  13946. return QValidator::Acceptable;
  13947. }
  13948. return QValidator::Invalid;
  13949. }
  13950. int ShortHexSpinBox::valueFromText(const QString &text) const
  13951. {
  13952. return text.toInt(NULL, 16);
  13953. }
  13954. QString ShortHexSpinBox::textFromValue(int value) const
  13955. {
  13956. QString retval;
  13957. retval.setNum(value, 16);
  13958. while(retval.size() < 4)
  13959. {
  13960. retval.prepend("0");
  13961. }
  13962. return retval.toUpper();
  13963. }
  13964. @** Configuration Widgets for Modbus RTU Devices.
  13965. \noindent While the top level configuration widgets seen so far have not had
  13966. any configuration details beyond the ability to add devices under the driver,
  13967. in the case of a serial port with Modbus RTU devices it is reasonable to
  13968. provide the connection details which will be shared by all devices on the bus.
  13969. @<Class declarations@>=
  13970. class ModbusRtuPortConfWidget : public BasicDeviceConfigurationWidget
  13971. {
  13972. @[Q_OBJECT@]@;
  13973. public:
  13974. @[Q_INVOKABLE@]@, ModbusRtuPortConfWidget(DeviceTreeModel *model,
  13975. const QModelIndex &index);
  13976. @[private slots@]:@/
  13977. void updatePort(const QString &newPort);
  13978. void updateBaudRate(const QString &newRate);
  13979. void updateParity(const QString &newParity);
  13980. void updateFlowControl(const QString &newFlow);
  13981. void updateStopBits(const QString &newStopBits);
  13982. };
  13983. @ Aside from the extra information compared with other configuration widgets
  13984. previously described, there is nothing surprising about the implementation.
  13985. @<ModbusRtuPortConfWidget implementation@>=
  13986. ModbusRtuPortConfWidget::ModbusRtuPortConfWidget(DeviceTreeModel *model,
  13987. const QModelIndex &index)
  13988. : BasicDeviceConfigurationWidget(model, index)
  13989. {
  13990. QFormLayout *layout = new QFormLayout;
  13991. QToolButton *addDeviceButton = new QToolButton;
  13992. addDeviceButton->setText(tr("Add Device"));
  13993. NodeInserter *addModbusRtuDevice = new NodeInserter("Modbus RTU Device",
  13994. "Modbus RTU Device",
  13995. "modbusrtudevice");
  13996. connect(addModbusRtuDevice, SIGNAL(triggered(QString, QString)),
  13997. this, SLOT(insertChildNode(QString, QString)));
  13998. QMenu *deviceMenu = new QMenu;
  13999. deviceMenu->addAction(addModbusRtuDevice);
  14000. addDeviceButton->setMenu(deviceMenu);
  14001. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  14002. layout->addRow(QString(), addDeviceButton);
  14003. PortSelector *port = new PortSelector;
  14004. layout->addRow(tr("Port:"), port);
  14005. connect(port, SIGNAL(currentIndexChanged(QString)),
  14006. this, SLOT(updatePort(QString)));
  14007. connect(port, SIGNAL(editTextChanged(QString)),
  14008. this, SLOT(updatePort(QString)));
  14009. BaudSelector *rate = new BaudSelector;
  14010. layout->addRow(tr("Baud:"), rate);
  14011. connect(rate, SIGNAL(currentIndexChanged(QString)),
  14012. this, SLOT(updateBaudRate(QString)));
  14013. ParitySelector *parity = new ParitySelector;
  14014. layout->addRow(tr("Parity:"), parity);
  14015. connect(parity, SIGNAL(currentIndexChanged(QString)),
  14016. this, SLOT(updateParity(QString)));
  14017. FlowSelector *flow = new FlowSelector;
  14018. layout->addRow(tr("Flow Control:"), flow);
  14019. connect(flow, SIGNAL(currentIndexChanged(QString)),
  14020. this, SLOT(updateFlowControl(QString)));
  14021. StopSelector *stop = new StopSelector;
  14022. layout->addRow(tr("Stop Bits:"), stop);
  14023. connect(stop, SIGNAL(currentIndexChanged(QString)),
  14024. this, SLOT(updateStopBits(QString)));
  14025. @<Get device configuration data for current node@>@;
  14026. for(int i = 0; i < configData.size(); i++)
  14027. {
  14028. node = configData.at(i).toElement();
  14029. if(node.attribute("name") == "port")
  14030. {
  14031. int j = port->findText(node.attribute("value"));
  14032. if(j >= 0)
  14033. {
  14034. port->setCurrentIndex(j);
  14035. }
  14036. else
  14037. {
  14038. port->insertItem(0, node.attribute("value"));
  14039. port->setCurrentIndex(0);
  14040. }
  14041. }
  14042. else if(node.attribute("name") == "baudrate")
  14043. {
  14044. rate->setCurrentIndex(rate->findText(node.attribute("value")));
  14045. }
  14046. else if(node.attribute("name") == "parity")
  14047. {
  14048. parity->setCurrentIndex(parity->findText(node.attribute("value")));
  14049. }
  14050. else if(node.attribute("name") == "flowcontrol")
  14051. {
  14052. flow->setCurrentIndex(flow->findText(node.attribute("value")));
  14053. }
  14054. else if(node.attribute("name") == "stopbits")
  14055. {
  14056. stop->setCurrentIndex(stop->findText(node.attribute("value")));
  14057. }
  14058. }
  14059. updatePort(port->currentText());
  14060. updateBaudRate(rate->currentText());
  14061. updateParity(parity->currentText());
  14062. updateFlowControl(flow->currentText());
  14063. updateStopBits(stop->currentText());
  14064. setLayout(layout);
  14065. }
  14066. void ModbusRtuPortConfWidget::updatePort(const QString &newPort)
  14067. {
  14068. updateAttribute("port", newPort);
  14069. }
  14070. void ModbusRtuPortConfWidget::updateBaudRate(const QString &newRate)
  14071. {
  14072. updateAttribute("baudrate", newRate);
  14073. }
  14074. void ModbusRtuPortConfWidget::updateParity(const QString &newParity)
  14075. {
  14076. updateAttribute("parity", newParity);
  14077. }
  14078. void ModbusRtuPortConfWidget::updateFlowControl(const QString &newFlow)
  14079. {
  14080. updateAttribute("flowcontrol", newFlow);
  14081. }
  14082. void ModbusRtuPortConfWidget::updateStopBits(const QString &newStopBits)
  14083. {
  14084. updateAttribute("stopbits", newStopBits);
  14085. }
  14086. @ From here we need to provide a widget for configuring a particular device.
  14087. At a minimum this would require setting the station number to a value between
  14088. 0 and 255. Zero is typically the broadcast address which reaches all devices
  14089. on the bus and is not generally recommended for use except in particular
  14090. circumstances. There are, however, a number of settings that influence all of
  14091. the currently supported child nodes and these settings are in the device
  14092. configuration widget instead of requiring that information to be duplicated
  14093. across multiple child nodes.
  14094. The Modbus RTU protocol is very general in scope and leaves many of the
  14095. details of how to do certain things up to the manufacturer. For rudimentary
  14096. support of devices using this protocol, the documentation for several devices
  14097. was consulted and a test rig with one device was set up. There are a number of
  14098. assumptions made for this initial support and to better support additional
  14099. device classes it may become necessary to expand on what is provided initially.
  14100. The primary focus presently is on the use of PID controllers as temperature
  14101. indicators with the ability to modify a set value in the case where this is
  14102. used as a controller rather than just a display.
  14103. All of the devices studied prior to adding this support made use of scaled
  14104. integer representation. In order to correctly determine the measured process
  14105. value it is necessary to know the unit of the measurement and the position of
  14106. the decimal point. It is generally possible to query this information, however
  14107. it may be useful to provide a way to specify fixed values in the event that a
  14108. device exposes these details in a way that is incompatible with my assumptions.
  14109. @<Class declarations@>=
  14110. class ModbusRtuDeviceConfWidget : public BasicDeviceConfigurationWidget
  14111. {
  14112. @[Q_OBJECT@]@;
  14113. public:@/
  14114. @[Q_INVOKABLE@]@, ModbusRtuDeviceConfWidget(DeviceTreeModel *model,
  14115. const QModelIndex &index);
  14116. @[private slots@]:@/
  14117. void updateStationNumber(int newStation);
  14118. void updateFixedUnit(bool newFixed);
  14119. void updateFixedDecimal(bool newFixed);
  14120. void updateUnit(const QString &newUnit);
  14121. void updateUnitAddress(int newAddress);
  14122. void updateValueF(int newValue);
  14123. void updateValueC(int newValue);
  14124. void updatePrecisionAddress(int newAddress);
  14125. void updatePrecisionValue(int newValue);
  14126. private:@/
  14127. QStackedLayout *unitSpecificationLayout;
  14128. QStackedLayout *decimalSpecificationLayout;
  14129. };
  14130. @ This widget has a number of differences from previous configuration widgets.
  14131. Perhaps most significantly there are controls which do not provide a text based
  14132. signal on state change. We also set certain controls as disabled when the
  14133. provided values are not relevant to operations such as when switching between
  14134. fixed decimal position and looking up decimal position from the device. Aside
  14135. from these details the widget operates according to the same principles as the
  14136. other widgets already seen.
  14137. @<ModbusRtuDeviceConfWidget implementation@>=
  14138. ModbusRtuDeviceConfWidget::ModbusRtuDeviceConfWidget(DeviceTreeModel *model,
  14139. const QModelIndex &index)
  14140. : BasicDeviceConfigurationWidget(model, index),
  14141. unitSpecificationLayout(new QStackedLayout),
  14142. decimalSpecificationLayout(new QStackedLayout)
  14143. {
  14144. QVBoxLayout *layout = new QVBoxLayout;
  14145. QToolButton *addChannelButton = new QToolButton;
  14146. addChannelButton->setText(tr("Add Channel"));
  14147. NodeInserter *addTemperaturePV = new NodeInserter("Temperature Process Value",
  14148. "Temperature Process Value",
  14149. "modbustemperaturepv");
  14150. NodeInserter *addTemperatureSV = new NodeInserter("Temperature Set Value",
  14151. "Temperature Set Value",
  14152. "modbustemperaturesv");
  14153. connect(addTemperaturePV, SIGNAL(triggered(QString, QString)),
  14154. this, SLOT(insertChildNode(QString, QString)));
  14155. connect(addTemperatureSV, SIGNAL(triggered(QString, QString)),
  14156. this, SLOT(insertChildNode(QString, QString)));
  14157. QMenu *channelMenu = new QMenu;
  14158. channelMenu->addAction(addTemperaturePV);
  14159. channelMenu->addAction(addTemperatureSV);
  14160. addChannelButton->setMenu(channelMenu);
  14161. addChannelButton->setPopupMode(QToolButton::InstantPopup);
  14162. layout->addWidget(addChannelButton);
  14163. QHBoxLayout *stationLayout = new QHBoxLayout;
  14164. QLabel *stationLabel = new QLabel(tr("Station:"));
  14165. QSpinBox *stationNumber = new QSpinBox;
  14166. stationNumber->setMinimum(0);
  14167. stationNumber->setMaximum(255);
  14168. stationLayout->addWidget(stationLabel);
  14169. stationLayout->addWidget(stationNumber);
  14170. layout->addLayout(stationLayout);
  14171. QCheckBox *fixedUnit = new QCheckBox(tr("Fixed Temperature Unit"));
  14172. layout->addWidget(fixedUnit);
  14173. QWidget *fixedUnitPlaceholder = new QWidget(this);
  14174. QHBoxLayout *fixedUnitLayout = new QHBoxLayout;
  14175. QLabel *fixedUnitLabel = new QLabel(tr("Temperature Unit:"));
  14176. QComboBox *fixedUnitSelector = new QComboBox;
  14177. fixedUnitSelector->addItem("Fahrenheit");
  14178. fixedUnitSelector->addItem("Celsius");
  14179. fixedUnitLayout->addWidget(fixedUnitLabel);
  14180. fixedUnitLayout->addWidget(fixedUnitSelector);
  14181. fixedUnitPlaceholder->setLayout(fixedUnitLayout);
  14182. unitSpecificationLayout->addWidget(fixedUnitPlaceholder);
  14183. QWidget *queriedUnitPlaceholder = new QWidget(this);
  14184. QFormLayout *queriedUnitLayout = new QFormLayout;
  14185. ShortHexSpinBox *unitAddress = new ShortHexSpinBox;
  14186. queriedUnitLayout->addRow(tr("Function 0x03 Unit Address:"), unitAddress);
  14187. QSpinBox *valueF = new QSpinBox;
  14188. valueF->setMinimum(0);
  14189. valueF->setMaximum(65535);
  14190. queriedUnitLayout->addRow(tr("Value for Fahrenheit"), valueF);
  14191. QSpinBox *valueC = new QSpinBox;
  14192. valueC->setMinimum(0);
  14193. valueC->setMaximum(65535);
  14194. queriedUnitLayout->addRow(tr("Value for Celsius"), valueC);
  14195. queriedUnitPlaceholder->setLayout(queriedUnitLayout);
  14196. unitSpecificationLayout->addWidget(queriedUnitPlaceholder);
  14197. layout->addLayout(unitSpecificationLayout);
  14198. QCheckBox *fixedPrecision = new QCheckBox(tr("Fixed Precision"));
  14199. layout->addWidget(fixedPrecision);
  14200. QWidget *fixedPrecisionPlaceholder = new QWidget(this);
  14201. QFormLayout *fixedPrecisionLayout = new QFormLayout;
  14202. QSpinBox *fixedPrecisionValue = new QSpinBox;
  14203. fixedPrecisionValue->setMinimum(0);
  14204. fixedPrecisionValue->setMaximum(9);
  14205. fixedPrecisionLayout->addRow("Places after the decimal point:",
  14206. fixedPrecisionValue);
  14207. fixedPrecisionPlaceholder->setLayout(fixedPrecisionLayout);
  14208. decimalSpecificationLayout->addWidget(fixedPrecisionPlaceholder);
  14209. QWidget *queriedPrecisionPlaceholder = new QWidget(this);
  14210. QFormLayout *queriedPrecisionLayout = new QFormLayout;
  14211. ShortHexSpinBox *precisionAddress = new ShortHexSpinBox;
  14212. queriedPrecisionLayout->addRow("Function 0x03 Decimal Position Address:",
  14213. precisionAddress);
  14214. queriedPrecisionPlaceholder->setLayout(queriedPrecisionLayout);
  14215. decimalSpecificationLayout->addWidget(queriedPrecisionPlaceholder);
  14216. layout->addLayout(decimalSpecificationLayout);
  14217. @<Get device configuration data for current node@>@;
  14218. for(int i = 0; i < configData.size(); i++)
  14219. {
  14220. node = configData.at(i).toElement();
  14221. if(node.attribute("name") == "station")
  14222. {
  14223. stationNumber->setValue(node.attribute("value").toInt());
  14224. }
  14225. else if(node.attribute("name") == "fixedunit")
  14226. {
  14227. if(node.attribute("value") == "true")
  14228. {
  14229. fixedUnit->setCheckState(Qt::Checked);
  14230. }
  14231. else if(node.attribute("value") == "false")
  14232. {
  14233. fixedUnit->setCheckState(Qt::Unchecked);
  14234. }
  14235. }
  14236. else if(node.attribute("name") == "fixedprecision")
  14237. {
  14238. fixedPrecisionValue->setValue(node.attribute("value").toInt());
  14239. }
  14240. else if(node.attribute("name") == "unit")
  14241. {
  14242. fixedUnitSelector->setCurrentIndex(fixedUnitSelector->findText(node.attribute("value")));
  14243. }
  14244. else if(node.attribute("name") == "unitaddress")
  14245. {
  14246. unitAddress->setValue(node.attribute("value").toInt());
  14247. }
  14248. else if(node.attribute("name") == "fvalue")
  14249. {
  14250. valueF->setValue(node.attribute("value").toInt());
  14251. }
  14252. else if(node.attribute("name") == "cvalue")
  14253. {
  14254. valueC->setValue(node.attribute("value").toInt());
  14255. }
  14256. else if(node.attribute("name") == "precisionaddress")
  14257. {
  14258. precisionAddress->setValue(node.attribute("value").toInt());
  14259. }
  14260. else if(node.attribute("name") == "precision")
  14261. {
  14262. fixedPrecisionValue->setValue(node.attribute("value").toInt());
  14263. }
  14264. }
  14265. updateStationNumber(stationNumber->value());
  14266. updateFixedUnit(fixedUnit->isChecked());
  14267. updateFixedDecimal(fixedPrecision->isChecked());
  14268. updateUnit(fixedUnitSelector->currentText());
  14269. updateUnitAddress(unitAddress->value());
  14270. updateValueF(valueF->value());
  14271. updateValueC(valueC->value());
  14272. updatePrecisionAddress(precisionAddress->value());
  14273. updatePrecisionValue(fixedPrecisionValue->value());
  14274. connect(stationNumber, SIGNAL(valueChanged(int)),
  14275. this, SLOT(updateStationNumber(int)));
  14276. connect(fixedUnitSelector, SIGNAL(currentIndexChanged(QString)),
  14277. this, SLOT(updateUnit(QString)));
  14278. connect(unitAddress, SIGNAL(valueChanged(int)),
  14279. this, SLOT(updateUnitAddress(int)));
  14280. connect(valueF, SIGNAL(valueChanged(int)),
  14281. this, SLOT(updateValueF(int)));
  14282. connect(valueC, SIGNAL(valueChanged(int)),
  14283. this, SLOT(updateValueC(int)));
  14284. connect(fixedUnit, SIGNAL(toggled(bool)),
  14285. this, SLOT(updateFixedUnit(bool)));
  14286. connect(fixedPrecision, SIGNAL(toggled(bool)),
  14287. this, SLOT(updateFixedDecimal(bool)));
  14288. connect(fixedPrecisionValue, SIGNAL(valueChanged(int)),
  14289. this, SLOT(updatePrecisionValue(int)));
  14290. connect(precisionAddress, SIGNAL(valueChanged(int)),
  14291. this, SLOT(updatePrecisionAddress(int)));
  14292. setLayout(layout);
  14293. }
  14294. void ModbusRtuDeviceConfWidget::updateStationNumber(int newStation)
  14295. {
  14296. updateAttribute("station", QString("%1").arg(newStation));
  14297. }
  14298. void ModbusRtuDeviceConfWidget::updateFixedUnit(bool newFixed)
  14299. {
  14300. if(newFixed)
  14301. {
  14302. unitSpecificationLayout->setCurrentIndex(0);
  14303. updateAttribute("fixedunit", "true");
  14304. }
  14305. else
  14306. {
  14307. unitSpecificationLayout->setCurrentIndex(1);
  14308. updateAttribute("fixedunit", "false");
  14309. }
  14310. }
  14311. void ModbusRtuDeviceConfWidget::updateFixedDecimal(bool newFixed)
  14312. {
  14313. if(newFixed)
  14314. {
  14315. decimalSpecificationLayout->setCurrentIndex(0);
  14316. updateAttribute("fixedprecision", "true");
  14317. }
  14318. else
  14319. {
  14320. decimalSpecificationLayout->setCurrentIndex(1);
  14321. updateAttribute("fixedprecision", "false");
  14322. }
  14323. }
  14324. void ModbusRtuDeviceConfWidget::updateUnit(const QString &newUnit)
  14325. {
  14326. updateAttribute("unit", newUnit);
  14327. }
  14328. void ModbusRtuDeviceConfWidget::updateUnitAddress(int newAddress)
  14329. {
  14330. updateAttribute("unitaddress", QString("%1").arg(newAddress));
  14331. }
  14332. void ModbusRtuDeviceConfWidget::updateValueF(int newValue)
  14333. {
  14334. updateAttribute("fvalue", QString("%1").arg(newValue));
  14335. }
  14336. void ModbusRtuDeviceConfWidget::updateValueC(int newValue)
  14337. {
  14338. updateAttribute("cvalue", QString("%1").arg(newValue));
  14339. }
  14340. void ModbusRtuDeviceConfWidget::updatePrecisionAddress(int newAddress)
  14341. {
  14342. updateAttribute("precisionaddress", QString("%1").arg(newAddress));
  14343. }
  14344. void ModbusRtuDeviceConfWidget::updatePrecisionValue(int newValue)
  14345. {
  14346. updateAttribute("precision", QString("%1").arg(newValue));
  14347. }
  14348. @ Initial Modbus RTU support is very limited and only considers temperature
  14349. process and set values. While in some cases it would be possible to cleverly
  14350. adapt this support to broader categories this is an area that must be extended
  14351. later to cover at least unitless control values and on/off status values. It
  14352. would be ideal to cover a broad range of useful properties. To read process
  14353. values we need to know the address that the current process value can be read
  14354. from.
  14355. @<Class declarations@>=
  14356. class ModbusRtuDeviceTPvConfWidget : public BasicDeviceConfigurationWidget
  14357. {
  14358. @[Q_OBJECT@]@/
  14359. public:@/
  14360. @[Q_INVOKABLE@]@, ModbusRtuDeviceTPvConfWidget(DeviceTreeModel *model,
  14361. const QModelIndex &index);
  14362. @[private slots@]:@/
  14363. void updateAddress(int newAddress);
  14364. };
  14365. @ This requires only a single field to store the address to query the current
  14366. process value.
  14367. @<ModbusRtuDeviceTPvConfWidget implementation@>=
  14368. ModbusRtuDeviceTPvConfWidget::ModbusRtuDeviceTPvConfWidget(DeviceTreeModel *model,
  14369. const QModelIndex &index)
  14370. : BasicDeviceConfigurationWidget(model, index)
  14371. {
  14372. QFormLayout *layout = new QFormLayout;
  14373. ShortHexSpinBox *address = new ShortHexSpinBox;
  14374. layout->addRow(tr("Function 0x04 Process Value Address"), address);
  14375. @<Get device configuration data for current node@>@;
  14376. for(int i = 0; i < configData.size(); i++)
  14377. {
  14378. node = configData.at(i).toElement();
  14379. if(node.attribute("name") == "address")
  14380. {
  14381. address->setValue(node.attribute("value").toInt());
  14382. break;
  14383. }
  14384. }
  14385. updateAddress(address->value());
  14386. connect(address, SIGNAL(valueChanged(int)), this, SLOT(updateAddress(int)));
  14387. setLayout(layout);
  14388. }
  14389. void ModbusRtuDeviceTPvConfWidget::updateAddress(int newAddress)
  14390. {
  14391. updateAttribute("address", QString("%1").arg(newAddress));
  14392. }
  14393. @ Set values are slightly more complicated as we may want either a fixed range
  14394. or the ability to query the device for its current allowed range, but nothing
  14395. is here that hasn't been seen elsewhere.
  14396. @<Class declarations@>=
  14397. class ModbusRtuDeviceTSvConfWidget : public BasicDeviceConfigurationWidget
  14398. {
  14399. @[Q_OBJECT@]@;
  14400. public:@/
  14401. @[Q_INVOKABLE@]@, ModbusRtuDeviceTSvConfWidget(DeviceTreeModel *model,
  14402. const QModelIndex &index);
  14403. @[private slots@]:@/
  14404. void updateReadAddress(int newAddress);
  14405. void updateWriteAddress(int newAddress);
  14406. void updateFixedRange(bool fixed);
  14407. void updateLower(const QString &lower);
  14408. void updateUpper(const QString &upper);
  14409. void updateLowerAddress(int newAddress);
  14410. void updateUpperAddress(int newAddress);
  14411. private:
  14412. QStackedLayout *boundsLayout;
  14413. };
  14414. @ Upper and lower bounds when operating on a fixed range are still subject to
  14415. decimal position rules in the parent node. It may be a good idea to enforce
  14416. this, however at present the person configuring the system is trusted to know
  14417. what they are doing.
  14418. @<ModbusRtuDeviceTSvConfWidget implementation@>=
  14419. ModbusRtuDeviceTSvConfWidget::ModbusRtuDeviceTSvConfWidget(DeviceTreeModel *model,
  14420. const QModelIndex &index)
  14421. : BasicDeviceConfigurationWidget(model, index), boundsLayout(new QStackedLayout)
  14422. {
  14423. QVBoxLayout *layout = new QVBoxLayout;
  14424. QFormLayout *addressLayout = new QFormLayout;
  14425. ShortHexSpinBox *readAddress = new ShortHexSpinBox;
  14426. ShortHexSpinBox *writeAddress = new ShortHexSpinBox;
  14427. addressLayout->addRow(tr("Function 0x04 Read Set Value Address:"), readAddress);
  14428. addressLayout->addRow(tr("Function 0x06 Write Set Value Address:"), writeAddress);
  14429. layout->addLayout(addressLayout);
  14430. QCheckBox *fixedRange = new QCheckBox(tr("Fixed Set Value Range"));
  14431. layout->addWidget(fixedRange);
  14432. QWidget *queriedRangePlaceholder = new QWidget(this);
  14433. QFormLayout *queriedRangeLayout = new QFormLayout;
  14434. ShortHexSpinBox *lowerAddress = new ShortHexSpinBox;
  14435. ShortHexSpinBox *upperAddress = new ShortHexSpinBox;
  14436. queriedRangeLayout->addRow(tr("Function 0x03 Minimum Set Value Address"),
  14437. lowerAddress);
  14438. queriedRangeLayout->addRow(tr("Function 0x03 Maximum Set Value Address"),
  14439. upperAddress);
  14440. queriedRangePlaceholder->setLayout(queriedRangeLayout);
  14441. boundsLayout->addWidget(queriedRangePlaceholder);
  14442. QWidget *fixedRangePlaceholder = new QWidget(this);
  14443. QFormLayout *fixedRangeLayout = new QFormLayout;
  14444. QLineEdit *fixedLower = new QLineEdit;
  14445. QLineEdit *fixedUpper = new QLineEdit;
  14446. fixedRangeLayout->addRow(tr("Minimum Set Value:"), fixedLower);
  14447. fixedRangeLayout->addRow(tr("Maximum Set Value:"), fixedUpper);
  14448. fixedRangePlaceholder->setLayout(fixedRangeLayout);
  14449. boundsLayout->addWidget(fixedRangePlaceholder);
  14450. layout->addLayout(boundsLayout);
  14451. @<Get device configuration data for current node@>@;
  14452. for(int i = 0; i < configData.size(); i++)
  14453. {
  14454. node = configData.at(i).toElement();
  14455. if(node.attribute("name") == "readaddress")
  14456. {
  14457. readAddress->setValue(node.attribute("value").toInt());
  14458. }
  14459. else if(node.attribute("name") == "writeaddress")
  14460. {
  14461. writeAddress->setValue(node.attribute("value").toInt());
  14462. }
  14463. else if(node.attribute("name") == "fixedrange")
  14464. {
  14465. if(node.attribute("value") == "true")
  14466. {
  14467. fixedRange->setCheckState(Qt::Checked);
  14468. }
  14469. else if(node.attribute("value") == "false")
  14470. {
  14471. fixedRange->setCheckState(Qt::Unchecked);
  14472. }
  14473. }
  14474. else if(node.attribute("name") == "fixedlower")
  14475. {
  14476. fixedLower->setText(node.attribute("value"));
  14477. }
  14478. else if(node.attribute("name") == "fixedupper")
  14479. {
  14480. fixedUpper->setText(node.attribute("value"));
  14481. }
  14482. else if(node.attribute("name") == "loweraddress")
  14483. {
  14484. lowerAddress->setValue(node.attribute("value").toInt());
  14485. }
  14486. else if(node.attribute("name") == "upperaddress")
  14487. {
  14488. upperAddress->setValue(node.attribute("value").toInt());
  14489. }
  14490. }
  14491. updateReadAddress(readAddress->value());
  14492. updateWriteAddress(writeAddress->value());
  14493. updateFixedRange(fixedRange->isChecked());
  14494. updateLower(fixedLower->text());
  14495. updateUpper(fixedUpper->text());
  14496. updateLowerAddress(lowerAddress->value());
  14497. updateUpperAddress(upperAddress->value());
  14498. connect(readAddress, SIGNAL(valueChanged(int)),
  14499. this, SLOT(updateReadAddress(int)));
  14500. connect(writeAddress, SIGNAL(valueChanged(int)),
  14501. this, SLOT(updateWriteAddress(int)));
  14502. connect(fixedRange, SIGNAL(toggled(bool)), this, SLOT(updateFixedRange(bool)));
  14503. connect(fixedLower, SIGNAL(textChanged(QString)),
  14504. this, SLOT(updateLower(QString)));
  14505. connect(fixedUpper, SIGNAL(textChanged(QString)),
  14506. this, SLOT(updateUpper(QString)));
  14507. connect(lowerAddress, SIGNAL(valueChanged(int)),
  14508. this, SLOT(updateLowerAddress(int)));
  14509. connect(upperAddress, SIGNAL(valueChanged(int)),
  14510. this, SLOT(updateUpperAddress(int)));
  14511. setLayout(layout);
  14512. }
  14513. void ModbusRtuDeviceTSvConfWidget::updateReadAddress(int newAddress)
  14514. {
  14515. updateAttribute("readaddress", QString("%1").arg(newAddress));
  14516. }
  14517. void ModbusRtuDeviceTSvConfWidget::updateWriteAddress(int newAddress)
  14518. {
  14519. updateAttribute("writeaddress", QString("%1").arg(newAddress));
  14520. }
  14521. void ModbusRtuDeviceTSvConfWidget::updateFixedRange(bool fixed)
  14522. {
  14523. if(fixed)
  14524. {
  14525. updateAttribute("fixedrange", "true");
  14526. boundsLayout->setCurrentIndex(1);
  14527. }
  14528. else
  14529. {
  14530. updateAttribute("fixedrange", "false");
  14531. boundsLayout->setCurrentIndex(0);
  14532. }
  14533. }
  14534. void ModbusRtuDeviceTSvConfWidget::updateLower(const QString &lower)
  14535. {
  14536. updateAttribute("fixedlower", lower);
  14537. }
  14538. void ModbusRtuDeviceTSvConfWidget::updateUpper(const QString &upper)
  14539. {
  14540. updateAttribute("fixedupper", upper);
  14541. }
  14542. void ModbusRtuDeviceTSvConfWidget::updateLowerAddress(int newAddress)
  14543. {
  14544. updateAttribute("loweraddress", QString("%1").arg(newAddress));
  14545. }
  14546. void ModbusRtuDeviceTSvConfWidget::updateUpperAddress(int newAddress)
  14547. {
  14548. updateAttribute("upperaddress", QString("%1").arg(newAddress));
  14549. }
  14550. @ The configuration widgets need to be registered.
  14551. @<Register device configuration widgets@>=
  14552. app.registerDeviceConfigurationWidget("modbusrtuport", ModbusRtuPortConfWidget::staticMetaObject);
  14553. app.registerDeviceConfigurationWidget("modbusrtudevice", ModbusRtuDeviceConfWidget::staticMetaObject);
  14554. app.registerDeviceConfigurationWidget("modbustemperaturepv", ModbusRtuDeviceTPvConfWidget::staticMetaObject);
  14555. app.registerDeviceConfigurationWidget("modbustemperaturesv", ModbusRtuDeviceTSvConfWidget::staticMetaObject);
  14556. @ A |NodeInserter| for the driver configuration widget is also needed. Note
  14557. that this is temporarily disabled. These configuration widgets will become
  14558. useful when I rearchitect the Modbus RTU support in a future release.
  14559. @<Register top level device configuration nodes@>=
  14560. #if 0
  14561. inserter = new NodeInserter(tr("Modbus RTU Port"), tr("Modbus RTU Port"), "modbusrtuport", NULL);
  14562. topLevelNodeInserters.append(inserter);
  14563. #endif
  14564. @* Configuration of Annotation Controls.
  14565. \noindent Aside from the details of hardware devices, the logging view must
  14566. also be able to set up log annotation controls. A few different control types
  14567. are offered. These include simple push buttons which insert a fixed annotation
  14568. when activated, push buttons which insert a value that includes a number which
  14569. is incremented every time the button is pressed, free text entry fields, and
  14570. numeric entry fields.
  14571. The basic push button control should allow configuration of both the button
  14572. text and the annotation text.
  14573. @<Class declarations@>=
  14574. class AnnotationButtonConfWidget : public BasicDeviceConfigurationWidget
  14575. {
  14576. @[Q_OBJECT@]@;
  14577. public:@/
  14578. @[Q_INVOKABLE@]@, AnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  14579. @[private slots@]:@/
  14580. void updateButtonText(const QString &text);
  14581. void updateAnnotationText(const QString &text);
  14582. };
  14583. @ The constructor sets up the controls for editing this data.
  14584. @<AnnotationButtonConfWidget implementation@>=
  14585. AnnotationButtonConfWidget::AnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  14586. : BasicDeviceConfigurationWidget(model, index)
  14587. {
  14588. QFormLayout *layout = new QFormLayout;
  14589. QLineEdit *buttonTextEdit = new QLineEdit;
  14590. QLineEdit *annotationTextEdit = new QLineEdit;
  14591. layout->addRow(tr("Button Text:"), buttonTextEdit);
  14592. layout->addRow(tr("Annotation Text:"), annotationTextEdit);
  14593. @<Get device configuration data for current node@>@;
  14594. for(int i = 0; i < configData.size(); i++)
  14595. {
  14596. node = configData.at(i).toElement();
  14597. if(node.attribute("name") == "buttontext")
  14598. {
  14599. buttonTextEdit->setText(node.attribute("value"));
  14600. }
  14601. else if(node.attribute("name") == "annotationtext")
  14602. {
  14603. annotationTextEdit->setText(node.attribute("value"));
  14604. }
  14605. }
  14606. updateButtonText(buttonTextEdit->text());
  14607. updateAnnotationText(annotationTextEdit->text());
  14608. connect(buttonTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateButtonText(QString)));
  14609. connect(annotationTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateAnnotationText(QString)));
  14610. setLayout(layout);
  14611. }
  14612. @ The slots are implemented trivially.
  14613. @<AnnotationButtonConfWidget implementation@>=
  14614. void AnnotationButtonConfWidget::updateButtonText(const QString &text)
  14615. {
  14616. updateAttribute("buttontext", text);
  14617. }
  14618. void AnnotationButtonConfWidget::updateAnnotationText(const QString &text)
  14619. {
  14620. updateAttribute("annotationtext", text);
  14621. }
  14622. @ The control must be registered.
  14623. @<Register device configuration widgets@>=
  14624. app.registerDeviceConfigurationWidget("annotationbutton", AnnotationButtonConfWidget::staticMetaObject);
  14625. @ Closely related to the previous control is one which provides parameterized
  14626. text. Technically this is not needed as both this and the previous
  14627. configuration control map to the same widget in the logging view and
  14628. parameterized annotation text can be used with either. The reason for
  14629. separating these is to indicate that it should be possible to change the text
  14630. and reset the number without altering the default configuration or requiring a
  14631. reinitialization of the logging view.
  14632. @<Class declarations@>=
  14633. class ReconfigurableAnnotationButtonConfWidget : public BasicDeviceConfigurationWidget
  14634. {
  14635. @[Q_OBJECT@]@/
  14636. public:@/
  14637. @[Q_INVOKABLE@] ReconfigurableAnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  14638. @[private slots@]:@/
  14639. void updateButtonText(const QString &text);
  14640. void updateAnnotationText(const QString &text);
  14641. };
  14642. @ The key difference in implementation is the addition of some documentation on
  14643. how to specify a numeric placeholder in the annotation text.
  14644. @<AnnotationButtonConfWidget implementation@>=
  14645. ReconfigurableAnnotationButtonConfWidget::ReconfigurableAnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  14646. : BasicDeviceConfigurationWidget(model, index)
  14647. {
  14648. QFormLayout *layout = new QFormLayout;
  14649. QLineEdit *buttonTextEdit = new QLineEdit;
  14650. QLineEdit *annotationTextEdit = new QLineEdit;
  14651. layout->addRow(tr("Button Text:"), buttonTextEdit);
  14652. layout->addRow(tr("Annotation Text:"), annotationTextEdit);
  14653. @<Get device configuration data for current node@>@;
  14654. for(int i = 0; i < configData.size(); i++)
  14655. {
  14656. node = configData.at(i).toElement();
  14657. if(node.attribute("name") == "buttontext")
  14658. {
  14659. buttonTextEdit->setText(node.attribute("value"));
  14660. }
  14661. else if(node.attribute("name") == "annotationtext")
  14662. {
  14663. annotationTextEdit->setText(node.attribute("value"));
  14664. }
  14665. }
  14666. updateButtonText(buttonTextEdit->text());
  14667. updateAnnotationText(annotationTextEdit->text());
  14668. connect(buttonTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateButtonText(QString)));
  14669. connect(annotationTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateAnnotationText(QString)));
  14670. QTextEdit *documentation = new QTextEdit;
  14671. documentation->setHtml(tr("If the <b>Annotation Text</b> contains <tt>%1</tt>, this will be replaced in the annotation with a number that increments each time the button is pressed."));
  14672. documentation->setReadOnly(true);
  14673. layout->addRow("", documentation);
  14674. setLayout(layout);
  14675. }
  14676. void ReconfigurableAnnotationButtonConfWidget::updateButtonText(const QString &text)
  14677. {
  14678. updateAttribute("buttontext", text);
  14679. }
  14680. void ReconfigurableAnnotationButtonConfWidget::updateAnnotationText(const QString &text)
  14681. {
  14682. updateAttribute("annotationtext", text);
  14683. }
  14684. @ The control must be registered as usual.
  14685. @<Register device configuration widgets@>=
  14686. app.registerDeviceConfigurationWidget("reconfigurablebutton", ReconfigurableAnnotationButtonConfWidget::staticMetaObject);
  14687. @ While it is generally better to have all measurements logged automatically,
  14688. many roasters would like to keep track of infrequently altered control
  14689. variables which have not been set up for automated logging. A reading from the
  14690. manometer after a fuel adjustment, for example, is frequently not available by
  14691. automated means. In cases such as this, providing for numeric annotation entry
  14692. may be desired. The |AnnotationSpinBox| provides for this. There are a few
  14693. details that are important in this. First is a label to better indicate to the
  14694. operator what values in this control represent. The range of allowed values and
  14695. the number of decimal places is important. This control also allows the
  14696. specification of text to precede and/or follow the numeric value and this must
  14697. be configurable.
  14698. @<Class declarations@>=
  14699. class NoteSpinConfWidget : public BasicDeviceConfigurationWidget
  14700. {
  14701. @[Q_OBJECT@]@;
  14702. public:@/
  14703. @[Q_INVOKABLE@]@, NoteSpinConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  14704. @[private slots@]:@/
  14705. void updateLabel(const QString &text);
  14706. void updateMinimum(const QString &minimum);
  14707. void updateMaximum(const QString &maximum);
  14708. void updatePrecision(int precision);
  14709. void updatePretext(const QString &text);
  14710. void updatePosttext(const QString &text);
  14711. };
  14712. @ There is nothing new in the implementation of note.
  14713. @<NoteSpinConfWidget implementation@>=
  14714. NoteSpinConfWidget::NoteSpinConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  14715. : BasicDeviceConfigurationWidget(model, index)
  14716. {
  14717. QFormLayout *layout = new QFormLayout;
  14718. QLineEdit *labelEdit = new QLineEdit;
  14719. layout->addRow(tr("Control Label: "), labelEdit);
  14720. QLineEdit *minimumEdit = new QLineEdit;
  14721. layout->addRow(tr("Minimum Value: "), minimumEdit);
  14722. QLineEdit *maximumEdit = new QLineEdit;
  14723. layout->addRow(tr("Maximum Value: "), maximumEdit);
  14724. QSpinBox *precisionEdit = new QSpinBox;
  14725. precisionEdit->setMinimum(0);
  14726. precisionEdit->setMaximum(9);
  14727. layout->addRow(tr("Precision"), precisionEdit);
  14728. QLineEdit *pretext = new QLineEdit;
  14729. layout->addRow(tr("Prefix text"), pretext);
  14730. QLineEdit *posttext = new QLineEdit;
  14731. layout->addRow(tr("Suffix text"), posttext);
  14732. @<Get device configuration data for current node@>@;
  14733. for(int i = 0; i < configData.size(); i++)
  14734. {
  14735. node = configData.at(i).toElement();
  14736. if(node.attribute("name") == "label")
  14737. {
  14738. labelEdit->setText(node.attribute("value"));
  14739. }
  14740. else if(node.attribute("name") == "minimum")
  14741. {
  14742. minimumEdit->setText(node.attribute("value"));
  14743. }
  14744. else if(node.attribute("name") == "maximum")
  14745. {
  14746. maximumEdit->setText(node.attribute("value"));
  14747. }
  14748. else if(node.attribute("name") == "precision")
  14749. {
  14750. precisionEdit->setValue(node.attribute("value").toInt());
  14751. }
  14752. else if(node.attribute("name") == "pretext")
  14753. {
  14754. pretext->setText(node.attribute("value"));
  14755. }
  14756. else if(node.attribute("name") == "posttext")
  14757. {
  14758. posttext->setText(node.attribute("value"));
  14759. }
  14760. }
  14761. updateLabel(labelEdit->text());
  14762. updateMinimum(minimumEdit->text());
  14763. updateMaximum(maximumEdit->text());
  14764. updatePrecision(precisionEdit->value());
  14765. updatePretext(pretext->text());
  14766. updatePosttext(posttext->text());
  14767. connect(labelEdit, SIGNAL(textEdited(QString)), this, SLOT(updateLabel(QString)));
  14768. connect(minimumEdit, SIGNAL(textEdited(QString)), this, SLOT(updateMinimum(QString)));
  14769. connect(maximumEdit, SIGNAL(textEdited(QString)), this, SLOT(updateMaximum(QString)));
  14770. connect(precisionEdit, SIGNAL(valueChanged(int)), this, SLOT(updatePrecision(int)));
  14771. connect(pretext, SIGNAL(textEdited(QString)), this, SLOT(updatePretext(QString)));
  14772. connect(posttext, SIGNAL(textEdited(QString)), this, SLOT(updatePosttext(QString)));
  14773. setLayout(layout);
  14774. }
  14775. void NoteSpinConfWidget::updateLabel(const QString &text)
  14776. {
  14777. updateAttribute("label", text);
  14778. }
  14779. void NoteSpinConfWidget::updateMinimum(const QString &minimum)
  14780. {
  14781. updateAttribute("minimum", minimum);
  14782. }
  14783. void NoteSpinConfWidget::updateMaximum(const QString &maximum)
  14784. {
  14785. updateAttribute("maximum", maximum);
  14786. }
  14787. void NoteSpinConfWidget::updatePrecision(int precision)
  14788. {
  14789. updateAttribute("precision", QString("%1").arg(precision));
  14790. }
  14791. void NoteSpinConfWidget::updatePretext(const QString &text)
  14792. {
  14793. updateAttribute("pretext", text);
  14794. }
  14795. void NoteSpinConfWidget::updatePosttext(const QString &text)
  14796. {
  14797. updateAttribute("posttext", text);
  14798. }
  14799. @ Configuration widget registration is as usual.
  14800. @<Register device configuration widgets@>=
  14801. app.registerDeviceConfigurationWidget("annotationspinbox", NoteSpinConfWidget::staticMetaObject);
  14802. @** Communicating with a Device through Modbus RTU.
  14803. \noindent The classes described here need to be further generalized to support
  14804. communications with multiple devices on the same port. The interface is based
  14805. on the |DAQ| class but extended to support additional functionality.
  14806. @<Class declarations@>=
  14807. class ModbusRTUDevice : public QObject
  14808. {
  14809. @[Q_OBJECT@]@;
  14810. public:@/
  14811. ModbusRTUDevice(DeviceTreeModel *model, const QModelIndex &index);
  14812. ~ModbusRTUDevice();
  14813. void queueMessage(QByteArray request, QObject *object, const char *callback);
  14814. @[Q_INVOKABLE@]@, double SVLower();
  14815. @[Q_INVOKABLE@]@, double SVUpper();
  14816. @[Q_INVOKABLE@]@, int decimals();
  14817. QList<Channel*> channels;
  14818. @[public slots@]:@/
  14819. void outputSV(double sv);
  14820. @[signals@]:@/
  14821. void SVLowerChanged(double);
  14822. void SVUpperChanged(double);
  14823. void SVDecimalChanged(int);
  14824. void queueEmpty();
  14825. @[private slots@]:@/
  14826. void dataAvailable();
  14827. void sendNextMessage();
  14828. void decimalResponse(QByteArray response);
  14829. void unitResponse(QByteArray response);
  14830. void svlResponse(QByteArray response);
  14831. void svuResponse(QByteArray response);
  14832. void requestMeasurement();
  14833. void mResponse(QByteArray response);
  14834. void ignore(QByteArray response);
  14835. private:@/
  14836. QextSerialPort *port;
  14837. QByteArray responseBuffer;
  14838. QList<QByteArray> messageQueue;
  14839. QList<QObject *> retObjQueue;
  14840. QList<char *> callbackQueue;
  14841. quint16 calculateCRC(QByteArray data);
  14842. QTimer *messageDelayTimer;
  14843. int delayTime;
  14844. char station;
  14845. int decimalPosition;
  14846. int valueF;
  14847. int valueC;
  14848. bool unitIsF;
  14849. double outputSVLower;
  14850. double outputSVUpper;
  14851. QByteArray outputSVStub;
  14852. QByteArray pvStub;
  14853. QByteArray svStub;
  14854. QByteArray mStub;
  14855. quint16 pvaddress;
  14856. quint16 svaddress;
  14857. bool svenabled;
  14858. bool readingsv;
  14859. double savedpv;
  14860. bool waiting;
  14861. };
  14862. @ The constructor reads its configuration from the configuration sub-tree of the
  14863. port node. This was adapted from a prototype implementation which used
  14864. |QSettings| to store this data. Note that this will only process the first
  14865. device specified on the port, the first process value on that device, and the
  14866. first set value on that device. A much more versatile architecture has been
  14867. planned for a future release which allows multiple devices per bus and
  14868. arbitrarily many monitored addresses per device. Communications are initiated
  14869. immediately upon construction.
  14870. @<ModbusRTUDevice implementation@>=
  14871. ModbusRTUDevice::ModbusRTUDevice(DeviceTreeModel *model, const QModelIndex &index)
  14872. : QObject(NULL), messageDelayTimer(new QTimer), unitIsF(true), readingsv(false),
  14873. waiting(false)
  14874. {
  14875. QDomElement portReferenceElement = model->referenceElement(model->data(index,
  14876. Qt::UserRole).toString());
  14877. QDomNodeList portConfigData = portReferenceElement.elementsByTagName("attribute");
  14878. QDomElement node;
  14879. QVariantMap attributes;
  14880. for(int i = 0; i < portConfigData.size(); i++)
  14881. {
  14882. node = portConfigData.at(i).toElement();
  14883. attributes.insert(node.attribute("name"), node.attribute("value"));
  14884. }
  14885. port = new QextSerialPort(attributes.value("port").toString(),
  14886. QextSerialPort::EventDriven);
  14887. int baudRate = attributes.value("baud").toInt();
  14888. port->setBaudRate((BaudRateType)baudRate);
  14889. double temp = ((double)(1) / (double)(baudRate)) * 48;
  14890. delayTime = (int)(temp * 3000);
  14891. messageDelayTimer->setSingleShot(true);
  14892. connect(messageDelayTimer, SIGNAL(timeout()), this, SLOT(sendNextMessage()));
  14893. port->setDataBits(DATA_8);
  14894. port->setParity((ParityType)attributes.value("parity").toInt());
  14895. port->setStopBits((StopBitsType)attributes.value("stop").toInt());
  14896. port->setFlowControl((FlowType)attributes.value("flow").toInt());
  14897. connect(port, SIGNAL(readyRead()), this, SLOT(dataAvailable()));
  14898. port->open(QIODevice::ReadWrite);
  14899. station = (char)attributes.value("station").toInt();
  14900. if(attributes.value("decimalQuery") == "true")
  14901. {
  14902. decimalPosition = 0;
  14903. QByteArray message;
  14904. message.append(station);
  14905. message.append((char)0x03);
  14906. quint16 address = (quint16)attributes.value("decimalAddress").toInt();
  14907. char *addressBytes = (char*)&address;
  14908. message.append(addressBytes[1]);
  14909. message.append(addressBytes[0]);
  14910. message.append((char)0x00);
  14911. message.append((char)0x01);
  14912. queueMessage(message, this, "decimalResponse(QByteArray)");
  14913. }
  14914. else
  14915. {
  14916. decimalPosition = attributes.value("decimalPosition").toInt();
  14917. }
  14918. valueF = attributes.value("valueF").toInt();
  14919. valueC = attributes.value("valueC").toInt();
  14920. if(attributes.value("unitQuery") == "true")
  14921. {
  14922. QByteArray message;
  14923. message.append(station);
  14924. message.append((char)0x03);
  14925. quint16 address = (quint16)attributes.value("unitAddress").toInt();
  14926. char *addressBytes = (char*)&address;
  14927. message.append(addressBytes[1]);
  14928. message.append(addressBytes[0]);
  14929. message.append((char)0x00);
  14930. message.append((char)0x01);
  14931. queueMessage(message, this, "unitResponse(QByteArray)");
  14932. }
  14933. else
  14934. {
  14935. if(attributes.value("fixedUnit") == "Celsius")
  14936. {
  14937. unitIsF = false;
  14938. }
  14939. }
  14940. if(attributes.value("sVWritable") == "true")
  14941. {
  14942. if(attributes.value("deviceLimit") == "true")
  14943. {
  14944. QByteArray lmessage;
  14945. lmessage.append(station);
  14946. lmessage.append((char)0x03);
  14947. quint16 laddress = (quint16)attributes.value("sVLowerAddr").toInt();
  14948. char *addressBytes = (char*)&laddress;
  14949. lmessage.append(addressBytes[1]);
  14950. lmessage.append(addressBytes[0]);
  14951. lmessage.append((char)0x00);
  14952. lmessage.append((char)0x01);
  14953. queueMessage(lmessage, this, "svlResponse(QByteArray)");
  14954. QByteArray umessage;
  14955. umessage.append(station);
  14956. umessage.append((char)0x03);
  14957. quint16 uaddress = (quint16)attributes.value("sVUpperAddr").toInt();
  14958. addressBytes = (char*)&uaddress;
  14959. umessage.append(addressBytes[1]);
  14960. umessage.append(addressBytes[0]);
  14961. umessage.append((char)0x00);
  14962. umessage.append((char)0x01);
  14963. queueMessage(umessage, this, "svuResponse(QByteArray)");
  14964. }
  14965. else
  14966. {
  14967. outputSVLower = attributes.value("sVLower").toDouble();
  14968. outputSVUpper = attributes.value("sVUpper").toDouble();
  14969. }
  14970. outputSVStub.append(station);
  14971. outputSVStub.append((char)0x06);
  14972. quint16 address = (quint16)attributes.value("sVOutputAddr").toInt();
  14973. char *addressBytes = (char*)&address;
  14974. outputSVStub.append(addressBytes[1]);
  14975. outputSVStub.append(addressBytes[0]);
  14976. }
  14977. Channel *pv = new Channel;
  14978. channels.append(pv);
  14979. pvStub.append(station);
  14980. pvStub.append((char)0x04);
  14981. pvaddress = (quint16)attributes.value("pVAddress").toInt();
  14982. char *pvac = (char*)&pvaddress;
  14983. pvStub.append(pvac[1]);
  14984. pvStub.append(pvac[0]);
  14985. pvStub.append((char)0x00);
  14986. pvStub.append((char)0x01);
  14987. svenabled = attributes.value("sVEnabled").toBool();
  14988. if(svenabled)
  14989. {
  14990. Channel *sv = new Channel;
  14991. channels.append(sv);
  14992. svStub.append(station);
  14993. svStub.append((char)0x04);
  14994. svaddress = (quint16)attributes.value("sVReadAddress").toInt();
  14995. char *svac = (char*)&svaddress;
  14996. svStub.append(svac[1]);
  14997. svStub.append(svac[0]);
  14998. svStub.append((char)0x00);
  14999. svStub.append((char)0x01);
  15000. if(svaddress - pvaddress == 1)
  15001. {
  15002. mStub.append(station);
  15003. mStub.append((char)0x04);
  15004. mStub.append(pvac[1]);
  15005. mStub.append(pvac[0]);
  15006. mStub.append((char)0x00);
  15007. mStub.append((char)0x02);
  15008. }
  15009. }
  15010. connect(this, SIGNAL(queueEmpty()), this, SLOT(requestMeasurement()));
  15011. requestMeasurement();
  15012. }
  15013. double ModbusRTUDevice::SVLower()
  15014. {
  15015. return outputSVLower;
  15016. }
  15017. double ModbusRTUDevice::SVUpper()
  15018. {
  15019. return outputSVUpper;
  15020. }
  15021. int ModbusRTUDevice::decimals()
  15022. {
  15023. return decimalPosition;
  15024. }
  15025. void ModbusRTUDevice::decimalResponse(QByteArray response)
  15026. {
  15027. quint16 temp;
  15028. char *tchar = (char*)&temp;
  15029. tchar[1] = response.at(3);
  15030. tchar[0] = response.at(4);
  15031. decimalPosition = temp;
  15032. emit SVDecimalChanged(decimalPosition);
  15033. qDebug() << "Received decimal response";
  15034. }
  15035. void ModbusRTUDevice::unitResponse(QByteArray response)
  15036. {
  15037. quint16 temp;
  15038. char *tchar = (char*)&temp;
  15039. tchar[1] = response.at(3);
  15040. tchar[0] = response.at(4);
  15041. int value = temp;
  15042. if(value == valueF)
  15043. {
  15044. unitIsF = true;
  15045. }
  15046. else
  15047. {
  15048. unitIsF = false;
  15049. }
  15050. }
  15051. void ModbusRTUDevice::svlResponse(QByteArray response)
  15052. {
  15053. quint16 temp;
  15054. char *tchar = (char*)&temp;
  15055. tchar[1] = response.at(3);
  15056. tchar[0] = response.at(4);
  15057. outputSVLower = (double)temp;
  15058. for(int i = 0; i < decimalPosition; i++)
  15059. {
  15060. outputSVLower /= 10;
  15061. }
  15062. emit SVLowerChanged(outputSVLower);
  15063. }
  15064. void ModbusRTUDevice::svuResponse(QByteArray response)
  15065. {
  15066. quint16 temp;
  15067. char *tchar = (char*)&temp;
  15068. tchar[1] = response.at(3);
  15069. tchar[0] = response.at(4);
  15070. outputSVUpper = (double)temp;
  15071. for(int i = 0; i < decimalPosition; i++)
  15072. {
  15073. outputSVUpper /= 10;
  15074. }
  15075. emit SVUpperChanged(outputSVUpper);
  15076. }
  15077. void ModbusRTUDevice::requestMeasurement()
  15078. {
  15079. if(mStub.length() > 0)
  15080. {
  15081. queueMessage(mStub, this, "mResponse(QByteArray)");
  15082. }
  15083. else
  15084. {
  15085. queueMessage(pvStub, this, "mResponse(QByteArray)");
  15086. if(svenabled)
  15087. {
  15088. queueMessage(svStub, this, "mResponse(QByteArray)");
  15089. }
  15090. }
  15091. }
  15092. void ModbusRTUDevice::mResponse(QByteArray response)
  15093. {
  15094. QTime time = QTime::currentTime();
  15095. if(response.at(2) == 0x04)
  15096. {
  15097. @<Process PV and SV@>@;
  15098. }
  15099. else
  15100. {
  15101. @<Process PV or SV@>@;
  15102. }
  15103. }
  15104. @ There are two ways that we might request measurement data. All of the
  15105. devices I've seen documented provide function 0x4 addresses for PV and SV
  15106. such that SV can be obtained from the address immediately after the address
  15107. from which we obtain PV. In this case we request both values at the same time.
  15108. @<Process PV and SV@>=
  15109. quint16 pv;
  15110. quint16 sv;
  15111. char *pvBytes = (char*)&pv;
  15112. char *svBytes = (char*)&sv;
  15113. pvBytes[1] = response.at(3);
  15114. pvBytes[0] = response.at(4);
  15115. svBytes[1] = response.at(5);
  15116. svBytes[0] = response.at(6);
  15117. double pvOut = (double)pv;
  15118. double svOut = (double)sv;
  15119. for(int i = 0; i < decimalPosition; i++)
  15120. {
  15121. pvOut /= 10;
  15122. svOut /= 10;
  15123. }
  15124. if(!unitIsF)
  15125. {
  15126. pvOut = pvOut * 9 / 5 + 32;
  15127. svOut = svOut * 9 / 5 + 32;
  15128. }
  15129. Measurement pvm(pvOut, time, Measurement::Fahrenheit);
  15130. Measurement svm(svOut, time, Measurement::Fahrenheit);
  15131. channels.at(0)->input(pvm);
  15132. channels.at(1)->input(svm);
  15133. @ When not measuring PV and SV at the same time, there are two possibilities.
  15134. One possibility is that SV is not enabled and we will only be reading from PV.
  15135. The other possibility is that we are alternating between reading PV and SV.
  15136. @<Process PV or SV@>=
  15137. quint16 value;
  15138. char *valueBytes = (char*)&value;
  15139. valueBytes[1] = response.at(3);
  15140. valueBytes[0] = response.at(4);
  15141. double valueOut = (double)value;
  15142. for(int i = 0; i < decimalPosition; i++)
  15143. {
  15144. valueOut /= 10;
  15145. }
  15146. if(!unitIsF)
  15147. {
  15148. valueOut = valueOut * 9 / 5 + 32;
  15149. }
  15150. if(!svenabled)
  15151. {
  15152. Measurement vm(valueOut, time, Measurement::Fahrenheit);
  15153. channels.at(0)->input(vm);
  15154. }
  15155. else
  15156. {
  15157. if(readingsv)
  15158. {
  15159. Measurement pvm(savedpv, time, Measurement::Fahrenheit);
  15160. Measurement svm(valueOut, time, Measurement::Fahrenheit);
  15161. channels.at(0)->input(pvm);
  15162. channels.at(1)->input(svm);
  15163. readingsv = false;
  15164. }
  15165. else
  15166. {
  15167. savedpv = valueOut;
  15168. readingsv = true;
  15169. }
  15170. }
  15171. @ The destructor should close the port.
  15172. @<ModbusRTUDevice implementation@>=
  15173. ModbusRTUDevice::~ModbusRTUDevice()
  15174. {
  15175. messageDelayTimer->stop();
  15176. port->close();
  15177. }
  15178. @ When data is available it should be read into a buffer. The start of the
  15179. buffer should always be the start of a response and there should never be
  15180. more than one response in the buffer at a time. It is, however, likely that
  15181. this buffer will have incomplete data. This means that we must determine when
  15182. the full response is available before passing the complete response along to
  15183. the appropriate method. If the response has not been received in full, nothing
  15184. is done. We'll be notified of more data shortly.
  15185. When the message we see the response for was queued, a callback was also
  15186. registered to handle the response. Once we have the complete message, we pass
  15187. the response along to the callback that was registered for that message,
  15188. remove the message and callback information from the message queue, and start
  15189. a timer which will trigger sending the next message after a safe amount of
  15190. time has passed.
  15191. @<ModbusRTUDevice implementation@>=
  15192. void ModbusRTUDevice::dataAvailable()
  15193. {
  15194. if(messageDelayTimer->isActive())
  15195. {
  15196. messageDelayTimer->stop();
  15197. }
  15198. responseBuffer.append(port->readAll());
  15199. @<Check Modbus RTU message size@>@;
  15200. if(calculateCRC(responseBuffer) == 0)
  15201. {
  15202. QObject *object = retObjQueue.at(0);
  15203. char *method = callbackQueue.at(0);
  15204. QMetaMethod metamethod = object->metaObject()->
  15205. method(object->metaObject()->
  15206. indexOfMethod(QMetaObject::normalizedSignature(method)));
  15207. metamethod.invoke(object, Qt::QueuedConnection,
  15208. Q_ARG(QByteArray, responseBuffer));
  15209. messageQueue.removeAt(0);
  15210. retObjQueue.removeAt(0);
  15211. callbackQueue.removeAt(0);
  15212. messageDelayTimer->start(delayTime);
  15213. }
  15214. else
  15215. {
  15216. qDebug() << "CRC failed";
  15217. }
  15218. waiting = false;
  15219. responseBuffer.clear();
  15220. }
  15221. @ In Modbus RTU, a response message starts with one byte identifying the device
  15222. the message was sent from, one byte indicating the function, a variable number
  15223. of bytes with the response data, and two bytes used to verify that the response
  15224. was correctly received. In the event of a normal response, messages will be at
  15225. least six bytes long, but in the event of an error it is possible for a message
  15226. to be five bytes long.
  15227. Messages with a function number of 0x01 or 0x02 will be 6 bytes in length.
  15228. Messages with a function number of 0x03 or 0x04 will be at least 7 bytes in
  15229. length with the total length determined by the sum of 5 and the value in the
  15230. fifth byte. Messages with a function number of 0x05, 0x06, or 0x10 will be 8
  15231. bytes in length. Messages with a function number greater than 0x80 will be five
  15232. bytes in length.
  15233. @<Check Modbus RTU message size@>=
  15234. if(responseBuffer.size() < 5)
  15235. {
  15236. return;
  15237. }
  15238. switch(responseBuffer.at(1))
  15239. {
  15240. case 0x01:
  15241. case 0x02:
  15242. if(responseBuffer.size() < 6)
  15243. {
  15244. return;
  15245. }
  15246. responseBuffer = responseBuffer.left(6);
  15247. break;
  15248. case 0x03:
  15249. case 0x04:
  15250. if(responseBuffer.size() < 5 + responseBuffer.at(2))
  15251. {
  15252. return;
  15253. }
  15254. responseBuffer = responseBuffer.left(5 + responseBuffer.at(2));
  15255. break;
  15256. case 0x05:
  15257. case 0x06:
  15258. case 0x10:
  15259. if(responseBuffer.size() < 8)
  15260. {
  15261. return;
  15262. }
  15263. responseBuffer = responseBuffer.left(8);
  15264. break;
  15265. }
  15266. @ When sending and receiving messages, it is necessary to calculate a 16 bit
  15267. cyclic redundancy check code. The algorithm used to calculate this is specified
  15268. by the Modbus RTU protocol documentation. When sending a message, |data| should
  15269. be the message to send except for the CRC bytes which will be appended once
  15270. this method calculates them. When receiving a message, passing the complete
  15271. message back through this method should result in a return value of |0|. Any
  15272. other value indicates an error.
  15273. @<ModbusRTUDevice implementation@>=
  15274. quint16 ModbusRTUDevice::calculateCRC(QByteArray data)
  15275. {
  15276. quint16 retval = 0xFFFF;
  15277. int i = 0;
  15278. while(i < data.size())
  15279. {
  15280. retval ^= 0x00FF & (quint16)data.at(i);
  15281. for(int j = 0; j < 8; j++)
  15282. {
  15283. if(retval & 1)
  15284. {
  15285. retval = (retval >> 1) ^ 0xA001;
  15286. }
  15287. else
  15288. {
  15289. retval >>= 1;
  15290. }
  15291. }
  15292. i++;
  15293. }
  15294. return retval;
  15295. }
  15296. @ When preparing an instance of ModbusRTUDevice, several messages may need to
  15297. be sent to the device in order to determine important details such as how
  15298. measurement data should be interpreted. During normal operation, messages
  15299. might be sent interactively between regular messages to acquire data. When
  15300. queueing a message, we also specify an object and method the response should be
  15301. sent to.
  15302. @<ModbusRTUDevice implementation@>=
  15303. void ModbusRTUDevice::queueMessage(QByteArray request, QObject *object,
  15304. const char *callback)
  15305. {
  15306. messageQueue.append(request);
  15307. retObjQueue.append(object);
  15308. callbackQueue.append(const_cast<char*>(callback));
  15309. if(messageQueue.size() == 1 && !(messageDelayTimer->isActive()))
  15310. {
  15311. sendNextMessage();
  15312. }
  15313. }
  15314. void ModbusRTUDevice::sendNextMessage()
  15315. {
  15316. if(messageQueue.size() > 0 && !waiting)
  15317. {
  15318. QByteArray message = messageQueue.at(0);
  15319. quint16 crc = calculateCRC(message);
  15320. char *check = (char*)&crc;
  15321. message.append(check[0]);
  15322. message.append(check[1]);
  15323. port->write(message);
  15324. messageDelayTimer->start(delayTime);
  15325. waiting = true;
  15326. }
  15327. else
  15328. {
  15329. emit queueEmpty();
  15330. }
  15331. }
  15332. void ModbusRTUDevice::outputSV(double value)
  15333. {
  15334. for(int i = 0; i < decimalPosition; i++)
  15335. {
  15336. value *= 10;
  15337. }
  15338. quint16 outval = (quint16)value;
  15339. QByteArray message(outputSVStub);
  15340. char *valBytes = (char*)&outval;
  15341. message.append(valBytes[1]);
  15342. message.append(valBytes[0]);
  15343. queueMessage(message, this, "ignore(QByteArray)");
  15344. }
  15345. @ We don't care about the response when sending a new SV.
  15346. @<ModbusRTUDevice implementation@>=
  15347. void ModbusRTUDevice::ignore(QByteArray)
  15348. {
  15349. return;
  15350. }
  15351. @ This class must be exposed to the host environment.
  15352. @<Function prototypes for scripting@>=
  15353. QScriptValue constructModbusRTUDevice(QScriptContext *context, QScriptEngine *engine);
  15354. QScriptValue ModbusRTUDevice_pVChannel(QScriptContext *context, QScriptEngine *engine);
  15355. QScriptValue ModbusRTUDevice_sVChannel(QScriptContext *context, QScriptEngine *engine);
  15356. void setModbusRTUDeviceProperties(QScriptValue value, QScriptEngine *engine);
  15357. @ The host environment is informed of the constructor.
  15358. @<Set up the scripting engine@>=
  15359. constructor = engine->newFunction(constructModbusRTUDevice);
  15360. value = engine->newQMetaObject(&ModbusRTUDevice::staticMetaObject, constructor);
  15361. engine->globalObject().setProperty("ModbusRTUDevice", value);
  15362. @ The constructor takes the configuration model and the index to the device of
  15363. interest as arguments rather than provide a large number of property setters to
  15364. handle initialization.
  15365. @<Functions for scripting@>=
  15366. QScriptValue constructModbusRTUDevice(QScriptContext *context, QScriptEngine *engine)
  15367. {
  15368. QScriptValue object;
  15369. if(context->argumentCount() == 2)
  15370. {
  15371. object = engine->newQObject(new ModbusRTUDevice(argument<DeviceTreeModel *>(0, context),
  15372. argument<QModelIndex>(1, context)),
  15373. QScriptEngine::ScriptOwnership);
  15374. setModbusRTUDeviceProperties(object, engine);
  15375. }
  15376. else
  15377. {
  15378. context->throwError("Incorrect number of arguments passed to "@|
  15379. "ModbusRTUDevice constructor. This takes the configuration model "@|
  15380. "and an index.");
  15381. }
  15382. return object;
  15383. }
  15384. @ The host environment needs a way to gain access to the channel objects.
  15385. @<Functions for scripting@>=
  15386. QScriptValue ModbusRTUDevice_pVChannel(QScriptContext *context, QScriptEngine *engine)
  15387. {
  15388. ModbusRTUDevice *self = getself<ModbusRTUDevice *>(context);
  15389. QScriptValue object;
  15390. if(self)
  15391. {
  15392. if(self->channels.size() > 0)
  15393. {
  15394. object = engine->newQObject(self->channels.at(0));
  15395. setChannelProperties(object, engine);
  15396. }
  15397. }
  15398. return object;
  15399. }
  15400. QScriptValue ModbusRTUDevice_sVChannel(QScriptContext *context, QScriptEngine *engine)
  15401. {
  15402. ModbusRTUDevice *self = getself<ModbusRTUDevice *>(context);
  15403. QScriptValue object;
  15404. if(self)
  15405. {
  15406. if(self->channels.size() > 1)
  15407. {
  15408. object = engine->newQObject(self->channels.at(1));
  15409. setChannelProperties(object, engine);
  15410. }
  15411. }
  15412. return object;
  15413. }
  15414. @ These methods are set as properties when the object is created.
  15415. @<Functions for scripting@>=
  15416. void setModbusRTUDeviceProperties(QScriptValue value, QScriptEngine *engine)
  15417. {
  15418. setQObjectProperties(value, engine);
  15419. value.setProperty("pVChannel", engine->newFunction(ModbusRTUDevice_pVChannel));
  15420. value.setProperty("sVChannel", engine->newFunction(ModbusRTUDevice_sVChannel));
  15421. }
  15422. @* Modbus RTU device configuration widget.
  15423. \noindent This class was minimally adapted from a prototype implementation to
  15424. use the new configuration system introduced in \pn{} 1.4.
  15425. With all of the custom widgets for specifying a device configuration in place,
  15426. we can proceed to combine these in a form. As all of the options might use more
  15427. screen space than is available we make this scrollable. Some reorganization of
  15428. this will be done prior to release to enable the use of multiple devices on the
  15429. port which may obviate the need for this, but as there are those who prefer to
  15430. have a small screen it may be better to leave the scroll area in place even
  15431. after such a change.
  15432. @<Class declarations@>=
  15433. class ModbusConfigurator : public BasicDeviceConfigurationWidget
  15434. {
  15435. @[Q_OBJECT@]
  15436. public:@/
  15437. Q_INVOKABLE ModbusConfigurator(DeviceTreeModel *model, const QModelIndex &index);
  15438. @[private slots@]:@/
  15439. void updatePort(const QString &newPort);
  15440. void updateBaudRate(const QString &newRate);
  15441. void updateParity(const QString &newParity);
  15442. void updateFlowControl(const QString &newFlow);
  15443. void updateStopBits(const QString &newStopBits);
  15444. void updateStation(int station);
  15445. void updateFixedDecimal(bool fixed);
  15446. void updateDecimalAddress(int address);
  15447. void updateDecimalPosition(int position);
  15448. void updateFixedUnit(bool fixed);
  15449. void updateUnitAddress(int address);
  15450. void updateValueForF(int value);
  15451. void updateValueForC(int value);
  15452. void updateUnit(const QString &newUnit);
  15453. void updatePVAddress(int address);
  15454. void updateSVEnabled(bool enabled);
  15455. void updateSVReadAddress(int address);
  15456. void updateDeviceLimit(bool query);
  15457. void updateSVLowerAddress(int address);
  15458. void updateSVUpperAddress(int address);
  15459. void updateSVLower(double value);
  15460. void updateSVUpper(double value);
  15461. void updateSVWritable(bool canWriteSV);
  15462. void updateSVWriteAddress(int address);
  15463. void updatePVColumnName(const QString &name);
  15464. void updateSVColumnName(const QString &name);
  15465. private:@/
  15466. PortSelector *port;
  15467. BaudSelector *baud;
  15468. ParitySelector *parity;
  15469. FlowSelector *flow;
  15470. StopSelector *stop;
  15471. QSpinBox *station;
  15472. QCheckBox *decimalQuery;
  15473. ShortHexSpinBox *decimalAddress;
  15474. QSpinBox *decimalPosition;
  15475. QCheckBox *unitQuery;
  15476. ShortHexSpinBox *unitAddress;
  15477. QSpinBox *valueF;
  15478. QSpinBox *valueC;
  15479. QComboBox *fixedUnit;
  15480. ShortHexSpinBox *pVAddress;
  15481. QCheckBox *sVEnabled;
  15482. ShortHexSpinBox *sVReadAddress;
  15483. QCheckBox *deviceLimit;
  15484. ShortHexSpinBox *sVLowerAddr;
  15485. ShortHexSpinBox *sVUpperAddr;
  15486. QDoubleSpinBox *sVLower;
  15487. QDoubleSpinBox *sVUpper;
  15488. QCheckBox *sVWritable;
  15489. ShortHexSpinBox *sVOutputAddr;
  15490. QLineEdit *pVColumnName;
  15491. QLineEdit *sVColumnName;
  15492. };
  15493. @ Implementation.
  15494. @<ModbusConfigurator implementation@>=
  15495. ModbusConfigurator::ModbusConfigurator(DeviceTreeModel *model, const QModelIndex &index)
  15496. : BasicDeviceConfigurationWidget(model, index),
  15497. port(new PortSelector), baud(new BaudSelector), parity(new ParitySelector),
  15498. flow(new FlowSelector), stop(new StopSelector), station(new QSpinBox),
  15499. decimalQuery(new QCheckBox(tr("Enable"))),
  15500. decimalAddress(new ShortHexSpinBox), decimalPosition(new QSpinBox),
  15501. unitQuery(new QCheckBox(tr("Enable"))),
  15502. unitAddress(new ShortHexSpinBox), valueF(new QSpinBox),
  15503. valueC(new QSpinBox), fixedUnit(new QComboBox),
  15504. pVAddress(new ShortHexSpinBox),
  15505. sVEnabled(new QCheckBox(tr("Enable"))),
  15506. sVReadAddress(new ShortHexSpinBox),
  15507. deviceLimit(new QCheckBox(tr("Enable"))),
  15508. sVLowerAddr(new ShortHexSpinBox), sVUpperAddr(new ShortHexSpinBox),
  15509. sVLower(new QDoubleSpinBox), sVUpper(new QDoubleSpinBox),
  15510. sVWritable(new QCheckBox(tr("Enable"))),
  15511. sVOutputAddr(new ShortHexSpinBox),
  15512. pVColumnName(new QLineEdit), sVColumnName(new QLineEdit)
  15513. {
  15514. QHBoxLayout *layout = new QHBoxLayout;
  15515. QWidget *form = new QWidget;
  15516. QHBoxLayout *masterLayout = new QHBoxLayout;
  15517. QVBoxLayout *portAndDeviceLayout = new QVBoxLayout;
  15518. QVBoxLayout *seriesLayout = new QVBoxLayout;
  15519. QFormLayout *serialSection = new QFormLayout;
  15520. serialSection->addRow(QString(tr("Port:")), port);
  15521. serialSection->addRow(QString(tr("Baud rate:")), baud);
  15522. serialSection->addRow(QString(tr("Parity:")), parity);
  15523. serialSection->addRow(QString(tr("Flow control:")), flow);
  15524. serialSection->addRow(QString(tr("Stop bits:")), stop);
  15525. QGroupBox *serialSectionBox = new QGroupBox(tr("Serial Port Configuration"));
  15526. serialSectionBox->setLayout(serialSection);
  15527. portAndDeviceLayout->addWidget(serialSectionBox);
  15528. QFormLayout *deviceSection = new QFormLayout;
  15529. station->setMinimum(1);
  15530. station->setMaximum(255);
  15531. decimalPosition->setMinimum(0);
  15532. decimalPosition->setMaximum(9);
  15533. valueF->setMinimum(0);
  15534. valueF->setMaximum(0xFFFF);
  15535. valueC->setMinimum(0);
  15536. valueC->setMaximum(0xFFFF);
  15537. fixedUnit->addItem(tr("Fahrenheit"), QVariant(QString("F")));
  15538. fixedUnit->addItem(tr("Celsius"), QVariant(QString("C")));
  15539. deviceSection->addRow(tr("Station:"), station);
  15540. deviceSection->addRow(tr("Decimal position from device:"), decimalQuery);
  15541. deviceSection->addRow(tr("Decimal position relative address:"), decimalAddress);
  15542. deviceSection->addRow(tr("Fixed decimal position:"), decimalPosition);
  15543. deviceSection->addRow(tr("Measurement unit from device:"), unitQuery);
  15544. deviceSection->addRow(tr("Current unit relative address:"), unitAddress);
  15545. deviceSection->addRow(tr("Value for Fahrenheit:"), valueF);
  15546. deviceSection->addRow(tr("Value for Celsius:"), valueC);
  15547. deviceSection->addRow(tr("Fixed unit:"), fixedUnit);
  15548. QGroupBox *deviceSectionBox = new QGroupBox(tr("Device Configuration"));
  15549. deviceSectionBox->setLayout(deviceSection);
  15550. portAndDeviceLayout->addWidget(deviceSectionBox);
  15551. QFormLayout *pVSection = new QFormLayout;
  15552. pVSection->addRow(tr("Value relative address:"), pVAddress);
  15553. pVSection->addRow(tr("PV column name:"), pVColumnName);
  15554. QGroupBox *processValueBox = new QGroupBox(tr("Process Value"));
  15555. processValueBox->setLayout(pVSection);
  15556. seriesLayout->addWidget(processValueBox);
  15557. QFormLayout *sVSection = new QFormLayout;
  15558. sVLower->setDecimals(1);
  15559. sVLower->setMinimum(0.0);
  15560. sVLower->setMaximum(999.9);
  15561. sVUpper->setDecimals(1);
  15562. sVUpper->setMinimum(0.0);
  15563. sVUpper->setMaximum(999.9);
  15564. sVSection->addRow(tr("Set value:"), sVEnabled);
  15565. sVSection->addRow(tr("Read relative address:"), sVReadAddress);
  15566. sVSection->addRow(tr("SV column name:"), sVColumnName);
  15567. sVSection->addRow(tr("Limits from device:"), deviceLimit);
  15568. sVSection->addRow(tr("Lower limit relative address:"), sVLowerAddr);
  15569. sVSection->addRow(tr("Upper limit relative address:"), sVUpperAddr);
  15570. sVSection->addRow(tr("Lower limit:"), sVLower);
  15571. sVSection->addRow(tr("Upper limit:"), sVUpper);
  15572. sVSection->addRow(tr("Output set value:"), sVWritable);
  15573. sVSection->addRow(tr("Output relative address:"), sVOutputAddr);
  15574. QGroupBox *setValueBox = new QGroupBox(tr("Set Value"));
  15575. setValueBox->setLayout(sVSection);
  15576. seriesLayout->addWidget(setValueBox);
  15577. masterLayout->addLayout(portAndDeviceLayout);
  15578. masterLayout->addLayout(seriesLayout);
  15579. form->setLayout(masterLayout);
  15580. @<Get device configuration data for current node@>@;
  15581. for(int i = 0; i < configData.size(); i++)
  15582. {
  15583. node = configData.at(i).toElement();
  15584. if(node.attribute("name") == "port")
  15585. {
  15586. QString portname = node.attribute("value");
  15587. int idx = port->findText(portname);
  15588. if(idx >= 0)
  15589. {
  15590. port->setCurrentIndex(idx);
  15591. }
  15592. else
  15593. {
  15594. port->addItem(portname);
  15595. }
  15596. }
  15597. else if(node.attribute("name") == "baud")
  15598. {
  15599. baud->setCurrentIndex(baud->findText(node.attribute("value")));
  15600. }
  15601. else if(node.attribute("name") == "parity")
  15602. {
  15603. parity->setCurrentIndex(parity->findData(node.attribute("value")));
  15604. }
  15605. else if(node.attribute("name") == "flow")
  15606. {
  15607. flow->setCurrentIndex(flow->findData(node.attribute("value")));
  15608. }
  15609. else if(node.attribute("name") == "stop")
  15610. {
  15611. stop->setCurrentIndex(stop->findData(node.attribute("value")));
  15612. }
  15613. else if(node.attribute("name") == "station")
  15614. {
  15615. station->setValue(node.attribute("value").toInt());
  15616. }
  15617. else if(node.attribute("name") == "decimalQuery")
  15618. {
  15619. if(node.attribute("value") == "true")
  15620. {
  15621. decimalQuery->setChecked(true);
  15622. }
  15623. else
  15624. {
  15625. decimalQuery->setChecked(false);
  15626. }
  15627. }
  15628. else if(node.attribute("name") == "decimalAddress")
  15629. {
  15630. decimalAddress->setValue(node.attribute("value").toInt());
  15631. }
  15632. else if(node.attribute("name") == "decimalPosition")
  15633. {
  15634. decimalPosition->setValue(node.attribute("value").toInt());
  15635. }
  15636. else if(node.attribute("name") == "unitQuery")
  15637. {
  15638. if(node.attribute("value") == "true")
  15639. {
  15640. unitQuery->setChecked(true);
  15641. }
  15642. else
  15643. {
  15644. unitQuery->setChecked(false);
  15645. }
  15646. }
  15647. else if(node.attribute("name") == "unitAddress")
  15648. {
  15649. unitAddress->setValue(node.attribute("value").toInt());
  15650. }
  15651. else if(node.attribute("name") == "valueF")
  15652. {
  15653. valueF->setValue(node.attribute("value").toInt());
  15654. }
  15655. else if(node.attribute("name") == "valueC")
  15656. {
  15657. valueC->setValue(node.attribute("value").toInt());
  15658. }
  15659. else if(node.attribute("name") == "fixedUnit")
  15660. {
  15661. fixedUnit->setCurrentIndex(fixedUnit->findText(node.attribute("value")));
  15662. }
  15663. else if(node.attribute("name") == "pVAddress")
  15664. {
  15665. pVAddress->setValue(node.attribute("value").toInt());
  15666. }
  15667. else if(node.attribute("name") == "sVEnabled")
  15668. {
  15669. if(node.attribute("value") == "true")
  15670. {
  15671. sVEnabled->setChecked(true);
  15672. }
  15673. else
  15674. {
  15675. sVEnabled->setChecked(false);
  15676. }
  15677. }
  15678. else if(node.attribute("name") == "sVReadAddress")
  15679. {
  15680. sVReadAddress->setValue(node.attribute("value").toInt());
  15681. }
  15682. else if(node.attribute("name") == "deviceLimit")
  15683. {
  15684. if(node.attribute("value") == "true")
  15685. {
  15686. deviceLimit->setChecked(true);
  15687. }
  15688. else
  15689. {
  15690. deviceLimit->setChecked(false);
  15691. }
  15692. }
  15693. else if(node.attribute("name") == "sVLowerAddr")
  15694. {
  15695. sVLowerAddr->setValue(node.attribute("value").toInt());
  15696. }
  15697. else if(node.attribute("name") == "sVUpperAddr")
  15698. {
  15699. sVUpperAddr->setValue(node.attribute("value").toInt());
  15700. }
  15701. else if(node.attribute("name") == "sVLower")
  15702. {
  15703. sVLower->setValue(node.attribute("value").toDouble());
  15704. }
  15705. else if(node.attribute("name") == "sVUpper")
  15706. {
  15707. sVUpper->setValue(node.attribute("value").toDouble());
  15708. }
  15709. else if(node.attribute("name") == "sVWritable")
  15710. {
  15711. if(node.attribute("value") == "true")
  15712. {
  15713. sVWritable->setChecked(true);
  15714. }
  15715. else
  15716. {
  15717. sVWritable->setChecked(false);
  15718. }
  15719. }
  15720. else if(node.attribute("name") == "sVOutputAddr")
  15721. {
  15722. sVOutputAddr->setValue(node.attribute("value").toInt());
  15723. }
  15724. else if(node.attribute("name") == "pvcolname")
  15725. {
  15726. pVColumnName->setText(node.attribute("value"));
  15727. }
  15728. else if(node.attribute("name") == "svcolname")
  15729. {
  15730. sVColumnName->setText(node.attribute("value"));
  15731. }
  15732. }
  15733. updatePort(port->currentText());
  15734. updateBaudRate(baud->currentText());
  15735. updateParity(parity->itemData(parity->currentIndex()).toString());
  15736. updateFlowControl(flow->itemData(flow->currentIndex()).toString());
  15737. updateStopBits(stop->itemData(stop->currentIndex()).toString());
  15738. updateStation(station->value());
  15739. updateFixedDecimal(decimalQuery->isChecked());
  15740. updateDecimalAddress(decimalAddress->value());
  15741. updateDecimalPosition(decimalPosition->value());
  15742. updateFixedUnit(unitQuery->isChecked());
  15743. updateUnitAddress(unitAddress->value());
  15744. updateValueForF(valueF->value());
  15745. updateValueForC(valueC->value());
  15746. updateUnit(fixedUnit->currentText());
  15747. updatePVAddress(pVAddress->value());
  15748. updateSVEnabled(sVEnabled->isChecked());
  15749. updateSVReadAddress(sVReadAddress->value());
  15750. updateDeviceLimit(deviceLimit->isChecked());
  15751. updateSVLowerAddress(sVLowerAddr->value());
  15752. updateSVUpperAddress(sVUpperAddr->value());
  15753. updateSVLower(sVLower->value());
  15754. updateSVUpper(sVUpper->value());
  15755. updateSVWritable(sVWritable->isChecked());
  15756. updateSVWriteAddress(sVOutputAddr->value());
  15757. updatePVColumnName(pVColumnName->text());
  15758. updateSVColumnName(sVColumnName->text());
  15759. connect(port, SIGNAL(currentIndexChanged(QString)), this, SLOT(updatePort(QString)));
  15760. connect(port, SIGNAL(editTextChanged(QString)), this, SLOT(updatePort(QString)));
  15761. connect(baud, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateBaudRate(QString)));
  15762. connect(parity, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateParity(QString)));
  15763. connect(flow, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateFlowControl(QString)));
  15764. connect(stop, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateStopBits(QString)));
  15765. connect(station, SIGNAL(valueChanged(int)), this, SLOT(updateStation(int)));
  15766. connect(decimalQuery, SIGNAL(toggled(bool)), this, SLOT(updateFixedDecimal(bool)));
  15767. connect(decimalAddress, SIGNAL(valueChanged(int)), this, SLOT(updateDecimalAddress(int)));
  15768. connect(decimalPosition, SIGNAL(valueChanged(int)), this, SLOT(updateDecimalPosition(int)));
  15769. connect(unitQuery, SIGNAL(toggled(bool)), this, SLOT(updateFixedUnit(bool)));
  15770. connect(unitAddress, SIGNAL(valueChanged(int)), this, SLOT(updateUnitAddress(int)));
  15771. connect(valueF, SIGNAL(valueChanged(int)), this, SLOT(updateValueForF(int)));
  15772. connect(valueC, SIGNAL(valueChanged(int)), this, SLOT(updateValueForC(int)));
  15773. connect(fixedUnit, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateUnit(QString)));
  15774. connect(pVAddress, SIGNAL(valueChanged(int)), this, SLOT(updatePVAddress(int)));
  15775. connect(sVEnabled, SIGNAL(toggled(bool)), this, SLOT(updateSVEnabled(bool)));
  15776. connect(sVReadAddress, SIGNAL(valueChanged(int)), this, SLOT(updateSVReadAddress(int)));
  15777. connect(deviceLimit, SIGNAL(toggled(bool)), this, SLOT(updateDeviceLimit(bool)));
  15778. connect(sVLowerAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVLowerAddress(int)));
  15779. connect(sVUpperAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVUpperAddress(int)));
  15780. connect(sVLower, SIGNAL(valueChanged(double)), this, SLOT(updateSVLower(double)));
  15781. connect(sVUpper, SIGNAL(valueChanged(double)), this, SLOT(updateSVUpper(double)));
  15782. connect(sVWritable, SIGNAL(toggled(bool)), this, SLOT(updateSVWritable(bool)));
  15783. connect(sVOutputAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVWriteAddress(int)));
  15784. connect(pVColumnName, SIGNAL(textEdited(QString)), this, SLOT(updatePVColumnName(QString)));
  15785. connect(sVColumnName, SIGNAL(textEdited(QString)), this, SLOT(updateSVColumnName(QString)));
  15786. layout->addWidget(form);
  15787. setLayout(layout);
  15788. }
  15789. void ModbusConfigurator::updatePort(const QString &newPort)
  15790. {
  15791. updateAttribute("port", newPort);
  15792. }
  15793. void ModbusConfigurator::updateBaudRate(const QString &newRate)
  15794. {
  15795. updateAttribute("baud", newRate);
  15796. }
  15797. void ModbusConfigurator::updateParity(const QString &)
  15798. {
  15799. updateAttribute("parity", parity->itemData(parity->currentIndex()).toString());
  15800. }
  15801. void ModbusConfigurator::updateFlowControl(const QString &)
  15802. {
  15803. updateAttribute("flow", flow->itemData(flow->currentIndex()).toString());
  15804. }
  15805. void ModbusConfigurator::updateStopBits(const QString &)
  15806. {
  15807. updateAttribute("stop", stop->itemData(stop->currentIndex()).toString());
  15808. }
  15809. void ModbusConfigurator::updateStation(int station)
  15810. {
  15811. updateAttribute("station", QString("%1").arg(station));
  15812. }
  15813. void ModbusConfigurator::updateFixedDecimal(bool fixed)
  15814. {
  15815. updateAttribute("decimalQuery", fixed ? "true" : "false");
  15816. }
  15817. void ModbusConfigurator::updateDecimalAddress(int address)
  15818. {
  15819. updateAttribute("decimalAddress", QString("%1").arg(address));
  15820. }
  15821. void ModbusConfigurator::updateDecimalPosition(int position)
  15822. {
  15823. updateAttribute("decimalPosition", QString("%1").arg(position));
  15824. }
  15825. void ModbusConfigurator::updateFixedUnit(bool fixed)
  15826. {
  15827. updateAttribute("unitQuery", fixed ? "true" : "false");
  15828. }
  15829. void ModbusConfigurator::updateUnitAddress(int address)
  15830. {
  15831. updateAttribute("unitAddress", QString("%1").arg(address));
  15832. }
  15833. void ModbusConfigurator::updateValueForF(int value)
  15834. {
  15835. updateAttribute("valueF", QString("%1").arg(value));
  15836. }
  15837. void ModbusConfigurator::updateValueForC(int value)
  15838. {
  15839. updateAttribute("valueC", QString("%1").arg(value));
  15840. }
  15841. void ModbusConfigurator::updateUnit(const QString &newUnit)
  15842. {
  15843. updateAttribute("fixedUnit", newUnit);
  15844. }
  15845. void ModbusConfigurator::updatePVAddress(int address)
  15846. {
  15847. updateAttribute("pVAddress", QString("%1").arg(address));
  15848. }
  15849. void ModbusConfigurator::updateSVEnabled(bool enabled)
  15850. {
  15851. updateAttribute("sVEnabled", enabled ? "true" : "false");
  15852. }
  15853. void ModbusConfigurator::updateSVReadAddress(int address)
  15854. {
  15855. updateAttribute("sVReadAddress", QString("%1").arg(address));
  15856. }
  15857. void ModbusConfigurator::updateDeviceLimit(bool query)
  15858. {
  15859. updateAttribute("deviceLimit", query ? "true" : "false");
  15860. }
  15861. void ModbusConfigurator::updateSVLowerAddress(int address)
  15862. {
  15863. updateAttribute("sVLowerAddr", QString("%1").arg(address));
  15864. }
  15865. void ModbusConfigurator::updateSVUpperAddress(int address)
  15866. {
  15867. updateAttribute("sVUpperAddr", QString("%1").arg(address));
  15868. }
  15869. void ModbusConfigurator::updateSVLower(double value)
  15870. {
  15871. updateAttribute("sVLower", QString("%1").arg(value));
  15872. }
  15873. void ModbusConfigurator::updateSVUpper(double value)
  15874. {
  15875. updateAttribute("sVUpper", QString("%1").arg(value));
  15876. }
  15877. void ModbusConfigurator::updateSVWritable(bool canWriteSV)
  15878. {
  15879. updateAttribute("sVWritable", canWriteSV ? "true" : "false");
  15880. }
  15881. void ModbusConfigurator::updateSVWriteAddress(int address)
  15882. {
  15883. updateAttribute("sVOutputAddr", QString("%1").arg(address));
  15884. }
  15885. void ModbusConfigurator::updatePVColumnName(const QString &name)
  15886. {
  15887. updateAttribute("pvcolname", name);
  15888. }
  15889. void ModbusConfigurator::updateSVColumnName(const QString &name)
  15890. {
  15891. updateAttribute("svcolname", name);
  15892. }
  15893. @ This is registered with the configuration system.
  15894. @<Register device configuration widgets@>=
  15895. app.registerDeviceConfigurationWidget("modbusrtu", ModbusConfigurator::staticMetaObject);
  15896. @ A |NodeInserter| for the driver configuration widget is also needed.
  15897. @<Register top level device configuration nodes@>=
  15898. inserter = new NodeInserter(tr("Modbus RTU Device"), tr("Modbus RTU Device"), "modbusrtu", NULL);
  15899. topLevelNodeInserters.append(inserter);
  15900. @* Configuration widget for a calibrated data series.
  15901. \noindent This control is used for adding a |LinearSplineInterpolator| to the
  15902. logging view.
  15903. @<Class declarations@>=
  15904. class LinearSplineInterpolationConfWidget : public BasicDeviceConfigurationWidget
  15905. {
  15906. @[Q_OBJECT@]@/
  15907. public:@/
  15908. @[Q_INVOKABLE@]@, LinearSplineInterpolationConfWidget(DeviceTreeModel *model,
  15909. const QModelIndex &index);
  15910. @[private slots@]:@/
  15911. void updateSourceColumn(const QString &source);
  15912. void updateDestinationColumn(const QString &dest);
  15913. void updateKnots();
  15914. private:@/
  15915. SaltModel *knotmodel;
  15916. };
  15917. @ This is configured by specifying a source column name, a destination column
  15918. name, and a two column table. Note that while we only have one widget handling
  15919. the mapping data, we store each column of the table in its own attribute.
  15920. @<LinearSplineInterpolationConfWidget implementation@>=
  15921. LinearSplineInterpolationConfWidget::LinearSplineInterpolationConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  15922. : BasicDeviceConfigurationWidget(model, index), knotmodel(new SaltModel(2))
  15923. {
  15924. QFormLayout *layout = new QFormLayout;
  15925. QLineEdit *source = new QLineEdit;
  15926. layout->addRow(tr("Source column name:"), source);
  15927. QLineEdit *destination = new QLineEdit;
  15928. layout->addRow(tr("Destination column name:"), destination);
  15929. knotmodel->setHeaderData(0, Qt::Horizontal, "Input");
  15930. knotmodel->setHeaderData(1, Qt::Horizontal, "Output");
  15931. QTableView *mappingTable = new QTableView;
  15932. mappingTable->setModel(knotmodel);
  15933. NumericDelegate *delegate = new NumericDelegate;
  15934. mappingTable->setItemDelegate(delegate);
  15935. layout->addRow(tr("Mapping data:"), mappingTable);
  15936. @<Get device configuration data for current node@>@;
  15937. for(int i = 0; i < configData.size(); i++)
  15938. {
  15939. node = configData.at(i).toElement();
  15940. if(node.attribute("name") == "source")
  15941. {
  15942. source->setText(node.attribute("value"));
  15943. }
  15944. else if(node.attribute("name") == "destination")
  15945. {
  15946. destination->setText(node.attribute("value"));
  15947. }
  15948. else if(node.attribute("name") == "sourcevalues")
  15949. {
  15950. @<Convert numeric array literal to list@>@;
  15951. int column = 0;
  15952. @<Populate model column from list@>@;
  15953. }
  15954. else if(node.attribute("name") == "destinationvalues")
  15955. {
  15956. @<Convert numeric array literal to list@>@;
  15957. int column = 1;
  15958. @<Populate model column from list@>@;
  15959. }
  15960. }
  15961. updateSourceColumn(source->text());
  15962. updateDestinationColumn(destination->text());
  15963. updateKnots();
  15964. connect(source, SIGNAL(textEdited(QString)), this, SLOT(updateSourceColumn(QString)));
  15965. connect(destination, SIGNAL(textEdited(QString)), this, SLOT(updateDestinationColumn(QString)));
  15966. connect(knotmodel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(updateKnots()));
  15967. setLayout(layout);
  15968. }
  15969. @ The saved data will have come from a previous call to
  15970. |SaltModel::arrayLiteral()| to repopulate the model we need to strip off the
  15971. the start and end of the strings and split them back into separate elements.
  15972. @<Convert numeric array literal to list@>=
  15973. QString data = node.attribute("value");
  15974. if(data.length() > 3)
  15975. {
  15976. data.chop(2);
  15977. data = data.remove(0, 2);
  15978. }
  15979. QStringList itemList = data.split(",");
  15980. @ Once the saved string has been split, the values can be inserted into the
  15981. model.
  15982. @<Populate model column from list@>=
  15983. for(int i = 0; i < itemList.size(); i++)
  15984. {
  15985. knotmodel->setData(knotmodel->index(i, column),
  15986. QVariant(itemList.at(i).toDouble()),
  15987. Qt::DisplayRole);
  15988. }
  15989. @ When data in the table is changed we simply overwrite any previously saved
  15990. data with the current data.
  15991. @<LinearSplineInterpolationConfWidget implementation@>=
  15992. void LinearSplineInterpolationConfWidget::updateKnots()
  15993. {
  15994. updateAttribute("sourcevalues", knotmodel->arrayLiteral(0, Qt::DisplayRole));
  15995. updateAttribute("destinationvalues", knotmodel->arrayLiteral(1, Qt::DisplayRole));
  15996. }
  15997. void LinearSplineInterpolationConfWidget::updateSourceColumn(const QString &source)
  15998. {
  15999. updateAttribute("source", source);
  16000. }
  16001. void LinearSplineInterpolationConfWidget::updateDestinationColumn(const QString &dest)
  16002. {
  16003. updateAttribute("destination", dest);
  16004. }
  16005. @ The widget is registered with the configuration system.
  16006. @<Register device configuration widgets@>=
  16007. app.registerDeviceConfigurationWidget("linearspline", LinearSplineInterpolationConfWidget::staticMetaObject);
  16008. @* Profile Translation Configuration Widget.
  16009. \noindent Configuring profile translation requires knowing which column to use
  16010. for matching purposes and the value to match.
  16011. @<Class declarations@>=
  16012. class TranslationConfWidget : public BasicDeviceConfigurationWidget
  16013. {
  16014. @[Q_OBJECT@]@;
  16015. public:@/
  16016. @[Q_INVOKABLE@]@, TranslationConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  16017. @[private slots@]:@/
  16018. void updateMatchingColumn(const QString &column);
  16019. void updateTemperature();
  16020. private:@/
  16021. QDoubleSpinBox *temperatureValue;
  16022. QComboBox *unitSelector;
  16023. };
  16024. @ The constructor sets up our user interface.
  16025. @<TranslationConfWidget implementation@>=
  16026. TranslationConfWidget::TranslationConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  16027. : BasicDeviceConfigurationWidget(model, index),
  16028. temperatureValue(new QDoubleSpinBox), unitSelector(new QComboBox)
  16029. {
  16030. unitSelector->addItem("Fahrenheit");
  16031. unitSelector->addItem("Celsius");
  16032. temperatureValue->setMinimum(0);
  16033. temperatureValue->setMaximum(1000);
  16034. QFormLayout *layout = new QFormLayout;
  16035. QLineEdit *column = new QLineEdit;
  16036. layout->addRow(tr("Column to match:"), column);
  16037. layout->addRow(tr("Unit:"), unitSelector);
  16038. layout->addRow(tr("Value:"), temperatureValue);
  16039. @<Get device configuration data for current node@>@;
  16040. for(int i = 0; i < configData.size(); i++)
  16041. {
  16042. node = configData.at(i).toElement();
  16043. if(node.attribute("name") == "column")
  16044. {
  16045. column->setText(node.attribute("value"));
  16046. }
  16047. else if(node.attribute("name") == "unit")
  16048. {
  16049. unitSelector->setCurrentIndex(unitSelector->findText(node.attribute("value")));
  16050. }
  16051. else if(node.attribute("name") == "value")
  16052. {
  16053. temperatureValue->setValue(node.attribute("value").toDouble());
  16054. }
  16055. }
  16056. updateMatchingColumn(column->text());
  16057. updateTemperature();
  16058. connect(column, SIGNAL(textEdited(QString)), this, SLOT(updateMatchingColumn(QString)));
  16059. connect(unitSelector, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateTemperature()));
  16060. connect(temperatureValue, SIGNAL(valueChanged(double)), this, SLOT(updateTemperature()));
  16061. setLayout(layout);
  16062. }
  16063. @ To update the temperature at which to match we save both the values of the
  16064. two widgets which control this and the value in Fahrenheit so we don't need to
  16065. run unit conversions during view initialization.
  16066. @<TranslationConfWidget implementation@>=
  16067. void TranslationConfWidget::updateTemperature()
  16068. {
  16069. updateAttribute("unit", unitSelector->currentText());
  16070. updateAttribute("value", QString("%1").arg(temperatureValue->value()));
  16071. if(unitSelector->currentText() == "Fahrenheit")
  16072. {
  16073. updateAttribute("FValue", QString("%1").arg(temperatureValue->value()));
  16074. }
  16075. else
  16076. {
  16077. updateAttribute("FValue", QString("%1").arg(temperatureValue->value() * 9 / 5 + 32));
  16078. }
  16079. }
  16080. void TranslationConfWidget::updateMatchingColumn(const QString &column)
  16081. {
  16082. updateAttribute("column", column);
  16083. }
  16084. @ This is registered with the configuration system.
  16085. @<Register device configuration widgets@>=
  16086. app.registerDeviceConfigurationWidget("translation", TranslationConfWidget::staticMetaObject);
  16087. @** Local changes.
  16088. \noindent This is the end of \pn{} as distributed by its author. It is expected
  16089. that some might have need of a program like \pn, but require some modification.
  16090. The patching capabilities of \cweb{} can be used to produce these local
  16091. modifications. This section is provided for those whose change requirements are
  16092. sufficiently extensive to require the introduction of new sections to the
  16093. program.
  16094. @** Index.
  16095. \noindent Following is a list of identifiers used in \pn, with underlined
  16096. entries pointing to where \cweb{} has guessed that the identifier was defined.
  16097. All references are to section numbers instead of page numbers.
  16098. \def\nullsec{--}