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 601KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327
  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.5 \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. As CWEB generates files with the wrong extension, we leave the default
  634. generated file empty.
  635. @c
  636. /* Nothing to see here. */
  637. @ The following is an overview of the structure of \pn:
  638. @(typica.cpp@>=
  639. #define PROGRAM_NAME "Typica"
  640. @<Header files to include@>@/
  641. @<Class declarations@>@/
  642. @<Function prototypes for scripting@>@/
  643. @<Class implementations@>@/
  644. @<Functions for scripting@>@/
  645. @<The main program@>
  646. #include "moc_typica.cpp"
  647. @ \pn{} is made of a number of distinct classes.
  648. @<Class implementations@>=
  649. @<NodeInserter implementation@>@/
  650. @<Measurement implementation@>@/
  651. @<DAQ Implementation@>@/
  652. @<FakeDAQ Implementation@>@/
  653. @<Channel Implementation@>@/
  654. @<TemperatureDisplay Implementation@>@/
  655. @<MeasurementTimeOffset Implementation@>@/
  656. @<ZeroEmitter Implementation@>@/
  657. @<MeasurementAdapter Implementation@>@/
  658. @<GraphView Implementation@>@/
  659. @<ZoomLog Implementation@>@/
  660. @<MeasurementModel Implementation@>@/
  661. @<AnnotationButton Implementation@>@/
  662. @<AnnotationSpinBox Implementation@>@/
  663. @<TimerDisplay Implementation@>@/
  664. @<PackLayout Implementation@>@/
  665. @<SceneButton Implementation@>@/
  666. @<WidgetDecorator Implementation@>@/
  667. @<LogEditWindow Implementation@>@/
  668. @<XMLOutput Implementation@>@/
  669. @<XMLInput Implementation@>@/
  670. @<CSVOutput Implementation@>@/
  671. @<SaltModel Implementation@>@/
  672. @<SqlComboBox Implementation@>@/
  673. @<SqlComboBoxDelegate Implementation@>@/
  674. @<Application Implementation@>@/
  675. @<SqlConnectionSetup implementation@>@/
  676. @<SqlQueryView implementation@>@/
  677. @<SqlQueryConnection implementation@>@/
  678. @<ReportTable implementation@>@/
  679. @<FormArray implementation@>@/
  680. @<ScaleControl implementation@>@/
  681. @<IntensityControl implementation@>@/
  682. @<ThresholdDetector Implementation@>@/
  683. @<PortSelector implementation@>@/
  684. @<BaudSelector implementation@>@/
  685. @<ParitySelector implementation@>@/
  686. @<FlowSelector implementation@>@/
  687. @<StopSelector implementation@>@/
  688. @<ModbusConfigurator implementation@>@/
  689. @<ShortHexSpinBox implementation@>@/
  690. @<ModbusRTUDevice implementation@>@/
  691. @<DeviceTreeModelNode implementation@>@/
  692. @<DeviceTreeModel implementation@>@/
  693. @<BasicDeviceConfigurationWidget implementation@>@/
  694. @<DeviceConfigurationWindow implementation@>@/
  695. @<Ni9211TcConfWidget implementation@>@/
  696. @<NiDaqMxBase9211ConfWidget implementation@>@/
  697. @<NiDaqMxBaseDriverConfWidget implementation@>@/
  698. @<ReportAction implementation@>@/
  699. @<NumericDelegate implementation@>@/
  700. @<NiDaqMxDriverConfWidget implementation@>@/
  701. @<NiDaqMx9211ConfWidget implementation@>@/
  702. @<NiDaqMxTc01ConfWidget implementation@>@/
  703. @<ModbusRtuPortConfWidget implementation@>@/
  704. @<ModbusRtuDeviceConfWidget implementation@>@/
  705. @<ModbusRtuDeviceTPvConfWidget implementation@>@/
  706. @<ModbusRtuDeviceTSvConfWidget implementation@>@/
  707. @<RoasterConfWidget implementation@>@/
  708. @<AnnotationButtonConfWidget implementation@>@/
  709. @<NoteSpinConfWidget implementation@>@/
  710. @<LinearCalibrator Implementation@>@/
  711. @<LinearSplineInterpolator Implementation@>@/
  712. @<LinearSplineInterpolationConfWidget implementation@>@/
  713. @<TranslationConfWidget implementation@>@/
  714. @<FreeAnnotationConfWidget implementation@>@/
  715. @ A few headers are required for various parts of \pn{}. These allow the use of
  716. various Qt modules.
  717. @<Header files to include@>=
  718. #include <QtCore>
  719. #include <QtGui>
  720. #include <QtScript>
  721. #include <QtScriptTools>
  722. #include <QtXml>
  723. #include <QtSql>
  724. #include <QtDebug>
  725. #include <QtXmlPatterns>
  726. #include <QtWebKit>
  727. @ New code is being written in separate files in a long term effort to improve
  728. organization of the code. The result of this is that some additional headers
  729. are required here.
  730. @<Header files to include@>=
  731. #include "helpmenu.h"
  732. @** The Scripting Engine.
  733. \noindent The main enhancement of \pn{} version 1.1 is the introduction of a
  734. scriptable environment. This change allows people to easily customize \pn{}
  735. without having to alter the program code. Instead, the user interface and
  736. program data flow is set up with a small script that runs in an ECMA-262 host
  737. environment\nfnote{Standard ECMA-262, 3$^{\rm{rd}}$ Edition\par\hbox{\indent%
  738. \pdfURL{%
  739. http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf}%
  740. {http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf}}}
  741. which requires
  742. significantly less expertise to modify than \pn{} itself. Such a scripting
  743. environment will be familiar to anybody with experience using JavaScript on web
  744. pages or ActionScript in Flash. \pn{}'s configuration system was later updated
  745. to support running several script fragments found in an XML configuration
  746. document.
  747. Most of the application classes are available from the scripting environment.
  748. The functions that make this possible are presented along with the classes. A
  749. selection of classes provided by Qt are also available. These are presented
  750. here.
  751. This chunk provides two |QScriptValue| objects which are used in other sections
  752. appended to this chunk.
  753. @<Set up the scripting engine@>=
  754. QScriptEngine *engine = new QScriptEngine;
  755. QScriptValue constructor;
  756. QScriptValue value;
  757. @ A common task when working with objects created from a script is finding the
  758. object a method is called on from the current script context. The code for this
  759. is simple, but lengthy. This is shortened with the use of a template function
  760. that obtains the object in question and casts it to the appropriate type. If an
  761. incorrect type is specified, a null pointer or similarly invalid value will be
  762. returned.
  763. @<Functions for scripting@>=
  764. template<class TYPE> TYPE@, getself(QScriptContext *context)
  765. {
  766. TYPE@, self = qobject_cast<TYPE>(context->thisObject().toQObject());
  767. return self;
  768. }
  769. template<> QTime getself(QScriptContext *context)
  770. {
  771. QTime self = context->thisObject().toVariant().toTime();
  772. return self;
  773. }
  774. template<> SqlQueryConnection* getself(QScriptContext *context)
  775. {
  776. SqlQueryConnection *self =@|
  777. (SqlQueryConnection *)qscriptvalue_cast<void *>(context->thisObject());
  778. return self;
  779. }
  780. template<> QXmlQuery* getself(QScriptContext *context)
  781. {
  782. QXmlQuery *self =
  783. (QXmlQuery *)qscriptvalue_cast<void *>(context->thisObject());
  784. return self;
  785. }
  786. template<> QXmlStreamWriter* getself(QScriptContext *context)
  787. {
  788. QXmlStreamWriter *self = @|
  789. (QXmlStreamWriter *)qscriptvalue_cast<void *>(context->thisObject());
  790. return self;
  791. }
  792. template<> QXmlStreamReader* getself(QScriptContext *context)
  793. {
  794. QXmlStreamReader *self = @|
  795. (QXmlStreamReader *)qscriptvalue_cast<void *>(context->thisObject());
  796. return self;
  797. }
  798. @ Another common task is obtaining the arguments of a method call from the
  799. script context and casting these arguments to the proper type. This is once
  800. again done with templates.
  801. @<Functions for scripting@>=
  802. template<class TYPE> TYPE@, argument(int arg, QScriptContext *context)
  803. {
  804. TYPE@, argument = qobject_cast<TYPE>(context->argument(arg).toQObject());
  805. return argument;
  806. }
  807. template<> QString argument(int arg, QScriptContext *context)
  808. {
  809. return context->argument(arg).toString();
  810. }
  811. template<> QVariant argument(int arg, QScriptContext *context)
  812. {
  813. return context->argument(arg).toVariant();
  814. }
  815. template<> int argument(int arg, QScriptContext *context)
  816. {
  817. return context->argument(arg).toInt32();
  818. }
  819. template<> SqlQueryConnection* argument(int arg, QScriptContext *context)
  820. {
  821. return (SqlQueryConnection *)
  822. qscriptvalue_cast<void *>(context->argument(arg));
  823. }
  824. template<> QModelIndex argument(int arg, QScriptContext *context)
  825. {
  826. return qscriptvalue_cast<QModelIndex>(context->argument(arg));
  827. }
  828. @ The scripting engine is informed of a number of classes defined elsewhere in
  829. the program. Code related to scripting these classes is grouped with the code
  830. implementing the classes. Additionally, there are several classes from Qt which
  831. are also made scriptable. These are detailed in the following sections.
  832. @* Exposing an Object Hierarchy to the Host Environment.
  833. \noindent While QtScript does a generally acceptable job of exposing
  834. information about objects that are available through the meta-object system,
  835. some methods require special handling in order to make them fully available to
  836. the host environment. Several functions are provided which provide a
  837. |QScriptValue| with these additional properties. The functions providing these
  838. properties also call other functions providing the properties of any base
  839. classes. In this way, any additional functionality provided to the host
  840. environment for a base class is also provided for any class that inherits that
  841. base class.
  842. For example, a |QBoxLayout| created in a script will have properties from
  843. |QLayout| which in turn brings in properties from |QObject| and |QLayoutItem|.
  844. A |QMainWindow| would bring in properties from |QWidget| which would bring in
  845. properties from |QObject|.
  846. Neither all methods nor all Qt classes are available from the host environment.
  847. When adding functionality to the host environment, there is a priority on
  848. classes and methods that are useful for \pn{}'s intended purpose.
  849. @* Base Classes.
  850. \noindent There are a few classes that are base classes of classes exposed to
  851. the scripting engine. There is no need for the host environment to allow the
  852. creation of these base classes and there may not be methods that must be added
  853. as properties in derived classes, however stub functions are provided so that
  854. in the event that a method from one of these base classes is needed later, it
  855. can be added once for all derived classes.
  856. The first of these is |QObject|.
  857. @<Function prototypes for scripting@>=
  858. void setQObjectProperties(QScriptValue value, QScriptEngine *engine);
  859. @ As there are no properties that need to be set for this class and as this
  860. class does not inherit any other class, nothing needs to be done in this method.
  861. It will, however, be called by subclasses in case this changes in the future.
  862. @<Functions for scripting@>=
  863. void setQObjectProperties(QScriptValue, QScriptEngine *)
  864. {
  865. /* Nothing needs to be done here. */
  866. }
  867. @ The same can be done for |QPaintDevice| and |QLayoutItem|.
  868. @<Function prototypes for scripting@>=
  869. void setQPaintDeviceProperties(QScriptValue value, QScriptEngine *engine);
  870. void setQLayoutItemProperties(QScriptValue value, QScriptEngine *engine);
  871. @ The implementations are similarly empty.
  872. @<Functions for scripting@>=
  873. void setQPaintDeviceProperties(QScriptValue, QScriptEngine *)
  874. {
  875. /* Nothing needs to be done here. */
  876. }
  877. void setQLayoutItemProperties(QScriptValue, QScriptEngine *)
  878. {
  879. /* Nothing needs to be done here. */
  880. }
  881. @* Scripting QWidget.
  882. \noindent The first interesting class in this hierarchy is |QWidget|. This is
  883. mainly used as a base class for other widgets and in such a role it is not
  884. particularly interesting. It is, however, possible to apply a layout to a
  885. |QWidget| and use that to manage the size and position of one or more child
  886. widgets. A few functions are used to accomplish this.
  887. @<Function prototypes for scripting@>=
  888. void setQWidgetProperties(QScriptValue value, QScriptEngine *engine);
  889. QScriptValue constructQWidget(QScriptContext *context, QScriptEngine *engine);
  890. QScriptValue QWidget_setLayout(QScriptContext *context, QScriptEngine *engine);
  891. QScriptValue QWidget_activateWindow(QScriptContext *context,
  892. QScriptEngine *engine);
  893. @ The script constructor must be passed to the scripting engine.
  894. @<Set up the scripting engine@>=
  895. constructor = engine->newFunction(constructQWidget);
  896. value = engine->newQMetaObject(&QWidget::staticMetaObject, constructor);
  897. engine->globalObject().setProperty("QWidget", value);
  898. @ The constructor creates a script value, but uses another function to add
  899. properties that wrap methods we want to make available to subclasses. Note that
  900. properties of the base classes are added before properties of this class. This
  901. procedure ensures that properties added from base classes can be be replaced in
  902. subclasses.
  903. @<Functions for scripting@>=
  904. QScriptValue constructQWidget(QScriptContext *, QScriptEngine *engine)
  905. {
  906. QScriptValue object = engine->newQObject(new QWidget);
  907. setQWidgetProperties(object, engine);
  908. return object;
  909. }
  910. void setQWidgetProperties(QScriptValue value, QScriptEngine *engine)
  911. {
  912. setQObjectProperties(value, engine);
  913. setQPaintDeviceProperties(value, engine);
  914. value.setProperty("setLayout", engine->newFunction(QWidget_setLayout));
  915. value.setProperty("activateWindow",
  916. engine->newFunction(QWidget_activateWindow));
  917. }
  918. @ This just leaves the property implementations. |QWidget::setLayout()| takes
  919. one argument, a |QLayout| and returns |void|. This wrapper duplicates this
  920. interface. |QWidget::activateWindow()| takes no arguments and returns nothing
  921. meaningful.
  922. @<Functions for scripting@>=
  923. QScriptValue QWidget_setLayout(QScriptContext *context, QScriptEngine *)
  924. {
  925. if(context->argumentCount() == 1)
  926. {
  927. QWidget *self = getself<QWidget *>(context);
  928. QLayout *layout = argument<QLayout *>(0, context);
  929. if(layout)
  930. {
  931. self->setLayout(layout);
  932. }
  933. else
  934. {
  935. context->throwError("Incorrect argument type passed to "@|
  936. "QWidget::setLayout(). This method requires "@|
  937. "a QLayout.");
  938. }
  939. }
  940. else
  941. {
  942. context->throwError("Incorrect number of arguments passed to "@|
  943. "QWidget::setLayout(). This method takes one "@|
  944. "QLayout as an argument.");
  945. }
  946. return QScriptValue();
  947. }
  948. QScriptValue QWidget_activateWindow(QScriptContext *context,
  949. QScriptEngine *)
  950. {
  951. QWidget *self = getself<QWidget *>(context);
  952. self->activateWindow();
  953. return QScriptValue();
  954. }
  955. @* Scripting QMainWindow.
  956. \noindent Rather than directly exposing |QMainWindow| to the scripting engine,
  957. we expose a class derived from |QMainWindow| with a minor change allowing the
  958. script to be notified when the window is about to be closed.
  959. This allows us to save settings for objects populating the window. Close
  960. handlers can be established by connecting to the |aboutToClose()| signal which
  961. is emitted in the |closeEvent()| handler. The close event is always accepted
  962. after the script has had a chance to respond, so this cannot be used to present
  963. an, ``Are you sure?'' message without additional modification.
  964. Slots are also provided for saving the size and position of the window to
  965. settings and restoring the window geometry from these settings.
  966. As of version 1.4 window geometry management is provided for all windows. The
  967. |restoreSizeAndPosition()| and |saveSizeAndPosition()| methods should be
  968. considered depreciated.
  969. @<Class declarations@>=
  970. class ScriptQMainWindow : public QMainWindow@/
  971. {@t\1@>@/
  972. Q_OBJECT@;@/
  973. public:@/
  974. ScriptQMainWindow();@/
  975. @t\4@>public slots@t\kern-3pt@>:@/
  976. void show();
  977. void saveSizeAndPosition(const QString &key);
  978. void restoreSizeAndPosition(const QString &key);
  979. void displayStatus(const QString &message = QString());@/
  980. protected:@/
  981. void closeEvent(QCloseEvent *event);
  982. void showEvent(QShowEvent *event);@/
  983. signals:@/
  984. void aboutToClose(void);@t\2@>@/
  985. }@t\kern-3pt@>;
  986. @ The implementation of these functions is simple.
  987. @<Functions for scripting@>=
  988. ScriptQMainWindow::ScriptQMainWindow()@+: QMainWindow(NULL)@/
  989. {
  990. /* Nothing needs to be done here. */
  991. }
  992. void ScriptQMainWindow::saveSizeAndPosition(const QString &key)
  993. {
  994. QSettings settings;
  995. settings.beginGroup(key);
  996. settings.setValue("pos", pos());
  997. settings.setValue("size", size());
  998. settings.endGroup();
  999. }
  1000. void ScriptQMainWindow::restoreSizeAndPosition(const QString &key)
  1001. {
  1002. QSettings settings;
  1003. settings.beginGroup(key);
  1004. if(settings.contains("size"))
  1005. {
  1006. resize(settings.value("size").toSize());
  1007. }
  1008. if(settings.contains("pos"))
  1009. {
  1010. move(settings.value("pos").toPoint());
  1011. }
  1012. settings.endGroup();
  1013. }
  1014. void ScriptQMainWindow::displayStatus(const QString &message)
  1015. {
  1016. statusBar()->showMessage(message);
  1017. }
  1018. void ScriptQMainWindow::showEvent(QShowEvent *event)
  1019. {
  1020. if(!event->spontaneous())
  1021. {
  1022. @<Restore window geometry@>@;
  1023. event->accept();
  1024. }
  1025. else
  1026. {
  1027. event->ignore();
  1028. }
  1029. }
  1030. void ScriptQMainWindow::show()
  1031. {
  1032. QMainWindow::show();
  1033. }
  1034. void ScriptQMainWindow::closeEvent(QCloseEvent *event)
  1035. {
  1036. emit aboutToClose();
  1037. @<Save window geometry@>@;
  1038. event->accept();
  1039. }
  1040. @ Window geometry management from version 1.4 on makes use of the window ID to
  1041. produce an appropriate QSettings key. This decision relies on the ID being set
  1042. before any show or close events are received and it relies on every distinct
  1043. type of window having a unique ID. If this is not the case then other things
  1044. are likely very broken. Note that with this approach multiple instances of the
  1045. same type of window will use the same key. This may not be ideal in all cases,
  1046. but further refinements can be produced if necessary.
  1047. @<Save window geometry@>=
  1048. QSettings settings;
  1049. settings.setValue(QString("geometries/%1").arg(objectName()), saveGeometry());
  1050. @ Restoring saved geometry is performed similarly to saving it.
  1051. @<Restore window geometry@>=
  1052. QSettings settings;
  1053. restoreGeometry(settings.value(QString("geometries/%1").arg(objectName())).
  1054. toByteArray());
  1055. @ Three functions are required to obtain the required functionality from a
  1056. script. A fourth adds properties for the object hierarchy.
  1057. @<Function prototypes for scripting@>=
  1058. QScriptValue constructQMainWindow(QScriptContext *context,
  1059. QScriptEngine *engine);
  1060. QScriptValue QMainWindow_setCentralWidget(QScriptContext *context,@|
  1061. QScriptEngine *engine);
  1062. QScriptValue QMainWindow_menuBar(QScriptContext *context,
  1063. QScriptEngine *engine);
  1064. void setQMainWindowProperties(QScriptValue value, QScriptEngine *engine);
  1065. @ Of these, the engine only needs to be informed of the constructor initially.
  1066. @<Set up the scripting engine@>=
  1067. constructor = engine->newFunction(constructQMainWindow);
  1068. value = engine->newQMetaObject(&ScriptQMainWindow::staticMetaObject,
  1069. constructor);
  1070. engine->globalObject().setProperty("QMainWindow", value);
  1071. @ The constructor calls a function to add the additional properties to the
  1072. newly created value.
  1073. @<Functions for scripting@>=
  1074. QScriptValue constructQMainWindow(QScriptContext *, QScriptEngine *engine)
  1075. {
  1076. QScriptValue object = engine->newQObject(new ScriptQMainWindow);
  1077. setQMainWindowProperties(object, engine);
  1078. return object;
  1079. }
  1080. void setQMainWindowProperties(QScriptValue value, QScriptEngine *engine)
  1081. {
  1082. setQWidgetProperties(value, engine);
  1083. value.setProperty("setCentralWidget",
  1084. engine->newFunction(QMainWindow_setCentralWidget));
  1085. value.setProperty("menuBar", engine->newFunction(QMainWindow_menuBar));
  1086. }
  1087. @ The |"setCentralWidget"| property is used for setting a widget in the main
  1088. area of the window. In \pn{} this will usually be a |QSplitter| object, but it
  1089. could also be a bare |QWidget| with a layout managing multiple widgets or a
  1090. custom widget defined in a local change. This is a simple wrapper around
  1091. |QMainWindow::setCentralWidget()|.
  1092. @<Functions for scripting@>=
  1093. QScriptValue QMainWindow_setCentralWidget(QScriptContext *context,
  1094. QScriptEngine *)
  1095. {
  1096. if(context->argumentCount() == 1)
  1097. {
  1098. QMainWindow *self = getself<QMainWindow *>(context);
  1099. QWidget *widget = argument<QWidget *>(0, context);
  1100. if(widget)
  1101. {
  1102. self->setCentralWidget(widget);
  1103. }
  1104. else
  1105. {
  1106. context->throwError("Incorrect argument type passed to "@|
  1107. "QMainWindow::setCentralWidget(). This "@|
  1108. "method requires a QWidget.");
  1109. }
  1110. }
  1111. else
  1112. {
  1113. context->throwError("Incorrect number of arguments passed to "@|
  1114. "QMainWindow::setCentralWidget(). This method "@|
  1115. "takes one QWidget as an argument.");
  1116. }
  1117. return QScriptValue();
  1118. }
  1119. @ The |"menuBar"| property requires that we expose |QMenuBar| to the scripting
  1120. environment in a limited fashion. We don't need to allow scripts to create a
  1121. new menu bar as it can be obtained from the window, however to add the menus to
  1122. the menu bar, we need to add a property to the |QMenuBar| object before passing
  1123. it back.
  1124. @<Functions for scripting@>=
  1125. QScriptValue QMainWindow_menuBar(QScriptContext *context, QScriptEngine *engine)
  1126. {
  1127. QScriptValue object;
  1128. if(context->argumentCount() == 0)
  1129. {
  1130. QMainWindow *self = getself<@[QMainWindow *@]>(context);
  1131. QMenuBar *bar = self->menuBar();
  1132. object = engine->newQObject(bar);
  1133. setQMenuBarProperties(object, engine);
  1134. }
  1135. else
  1136. {
  1137. context->throwError("Incorrect number of arguments passed to "@|
  1138. "QMainWindow::menuBar(). This method takes no "@|
  1139. "arguments.");
  1140. }
  1141. return object;
  1142. }
  1143. @ The previous function is the only place a new |QMenuBar| is created through
  1144. the host environment. Two functions are used in handling this object creation.
  1145. @<Function prototypes for scripting@>=
  1146. void setQMenuBarProperties(QScriptValue value, QScriptEngine *engine);
  1147. QScriptValue QMenuBar_addMenu(QScriptContext *context, QScriptEngine *engine);
  1148. @ The first of these adds the appropriate properties to the newly created
  1149. object.
  1150. @<Functions for scripting@>=
  1151. void setQMenuBarProperties(QScriptValue value, QScriptEngine *engine)
  1152. {
  1153. setQWidgetProperties(value, engine);
  1154. value.setProperty("addMenu", engine->newFunction(QMenuBar_addMenu));
  1155. }
  1156. @ This function can be used to add new menus to a menu bar. In order to do
  1157. anything with the newly created menus, two properties are added to the |QMenu|
  1158. objects which allow actions to be added as menu items and allow separators to be
  1159. placed between groups of menu items.
  1160. At the time of this writing, there are three |QMenuBar::addMenu()| methods. This
  1161. function wraps |QMenu* QMenuBar::addMenu(const QString &title)|.
  1162. @<Functions for scripting@>=
  1163. QScriptValue QMenuBar_addMenu(QScriptContext *context, QScriptEngine *engine)
  1164. {
  1165. QScriptValue object;
  1166. if(context->argumentCount() == 1)
  1167. {
  1168. QMenuBar *self = getself<@[QMenuBar *@]>(context);
  1169. QString title = argument<QString>(0, context);
  1170. object = engine->newQObject(self->addMenu(title));
  1171. setQMenuProperties(object, engine);
  1172. }
  1173. else
  1174. {
  1175. context->throwError("Incorrect number of arguments passed to "@|
  1176. "QMenuBar::addMenu(). This method takes one "@|
  1177. "string as an argument.");
  1178. }
  1179. return object;
  1180. }
  1181. @ These three functions allow adding items to the menu and adding separators
  1182. between groups of items.
  1183. @<Function prototypes for scripting@>=
  1184. void setQMenuProperties(QScriptValue value, QScriptEngine *engine);
  1185. QScriptValue QMenu_addAction(QScriptContext *context, QScriptEngine *engine);
  1186. QScriptValue QMenu_addSeparator(QScriptContext *context, QScriptEngine *engine);
  1187. @ The first of these add properties to newly created |QMenu| objects.
  1188. @<Functions for scripting@>=
  1189. void setQMenuProperties(QScriptValue value, QScriptEngine *engine)
  1190. {
  1191. setQWidgetProperties(value, engine);
  1192. value.setProperty("addAction", engine->newFunction(QMenu_addAction));
  1193. value.setProperty("addSeparator", engine->newFunction(QMenu_addSeparator));
  1194. }
  1195. @ These functions are simple wrappers around |QMenu| methods.
  1196. @<Functions for scripting@>=
  1197. QScriptValue QMenu_addAction(QScriptContext *context, QScriptEngine *)
  1198. {
  1199. if(context->argumentCount() == 1)
  1200. {
  1201. QMenu *self = getself<@[QMenu *@]>(context);
  1202. QAction *action = argument<QAction *>(0, context);
  1203. if(action)
  1204. {
  1205. self->addAction(action);
  1206. }
  1207. else
  1208. {
  1209. context->throwError("Incorrect argument type passed to "@|
  1210. "QMenu::addAction(). This method requires a "@|
  1211. "QAction.");
  1212. }
  1213. }
  1214. else
  1215. {
  1216. context->throwError("Incorrect number of arguments passed to "@|
  1217. "QMenu::addAction(). This method takes one "@|
  1218. "QAction as an argument.");
  1219. }
  1220. return QScriptValue();
  1221. }
  1222. QScriptValue QMenu_addSeparator(QScriptContext *context, QScriptEngine *)
  1223. {
  1224. if(context->argumentCount() == 0)
  1225. {
  1226. QMenu *self = getself<@[QMenu *@]>(context);
  1227. self->addSeparator();
  1228. }
  1229. else
  1230. {
  1231. context->throwError("Incorrect number of arguments passed to "@|
  1232. "QMenu::addSeparator(). This method takes no "@|
  1233. "arguments.");
  1234. }
  1235. return QScriptValue();
  1236. }
  1237. @* Scripting QFrame.
  1238. \noindent |QFrame| is another class for which little needs to be done. It exists
  1239. as a subclass of |QWidget| and a superclass for |QSplitter|, |QLCDNumber|, and
  1240. |QAbstractScrollArea| among other classes.
  1241. @<Function prototypes for scripting@>=
  1242. void setQFrameProperties(QScriptValue value, QScriptEngine *engine);
  1243. QScriptValue constructQFrame(QScriptContext *context, QScriptEngine *engine);
  1244. @ The constructor must be passed to the scripting engine.
  1245. @<Set up the scripting engine@>=
  1246. constructor = engine->newFunction(constructQFrame);
  1247. value = engine->newQMetaObject(&QFrame::staticMetaObject, constructor);
  1248. engine->globalObject().setProperty("QFrame", value);
  1249. @ The implementation of these functions should seem familiar.
  1250. @<Functions for scripting@>=
  1251. QScriptValue constructQFrame(QScriptContext *, QScriptEngine *engine)
  1252. {
  1253. QScriptValue object = engine->newQObject(new QFrame);
  1254. setQFrameProperties(object, engine);
  1255. return object;
  1256. }
  1257. void setQFrameProperties(QScriptValue value, QScriptEngine *engine)
  1258. {
  1259. setQWidgetProperties(value, engine);
  1260. }
  1261. @* Scripting QLabel.
  1262. \noindent When constructing an interface wholly or partially through dynamic
  1263. means rather than entirely through the XML configuration document it can
  1264. sometimes be desirable to construct |QLabel| instances. This is usually used
  1265. to provide a very small amount of text.
  1266. @<Function prototypes for scripting@>=
  1267. void setQLabelProperties(QScriptValue value, QScriptEngine *engine);
  1268. QScriptValue constructQLabel(QScriptContext *context, QScriptEngine *engine);
  1269. @ The constructor must be passed to the scripting engine.
  1270. @<Set up the scripting engine@>=
  1271. constructor = engine->newFunction(constructQLabel);
  1272. value = engine->newQMetaObject(&QLabel::staticMetaObject, constructor);
  1273. engine->globalObject().setProperty("QLabel", value);
  1274. @ In the constructor we allow an optional argument to specify the text of the
  1275. label.
  1276. @<Functions for scripting@>=
  1277. QScriptValue constructQLabel(QScriptContext *context, QScriptEngine *engine)
  1278. {
  1279. QString text;
  1280. if(context->argumentCount() == 1)
  1281. {
  1282. text = argument<QString>(0, context);
  1283. }
  1284. QScriptValue object = engine->newQObject(new QLabel(text));
  1285. setQLabelProperties(object, engine);
  1286. return object;
  1287. }
  1288. void setQLabelProperties(QScriptValue value, QScriptEngine *engine)
  1289. {
  1290. setQFrameProperties(value, engine);
  1291. }
  1292. @* Scripting QSplitter.
  1293. \noindent The |QSplitter| class is one of the main classes used for user
  1294. interface object layout in \pn{}. To provide this class to the scripting engine,
  1295. we provide five functions: a constructor, a method for adding widgets to the
  1296. splitter, a method for saving the size of each widget in the splitter, a
  1297. method for restoring these saved sizes, and a function for adding these methods
  1298. as properties of newly created |QSplitter| objects.
  1299. @<Function prototypes for scripting@>=
  1300. QScriptValue constructQSplitter(QScriptContext *context, QScriptEngine *engine);
  1301. QScriptValue QSplitter_addWidget(QScriptContext *context,
  1302. QScriptEngine *engine);
  1303. QScriptValue QSplitter_saveState(QScriptContext *context,
  1304. QScriptEngine *engine);
  1305. QScriptValue QSplitter_restoreState(QScriptContext *context,
  1306. QScriptEngine *engine);
  1307. void setQSplitterProperties(QScriptValue value, QScriptEngine *engine);
  1308. @ Of these, the scripting engine must be informed of the constructor.
  1309. @<Set up the scripting engine@>=
  1310. constructor = engine->newFunction(constructQSplitter);
  1311. value = engine->newQMetaObject(&QSplitter::staticMetaObject, constructor);
  1312. engine->globalObject().setProperty("QSplitter", value);
  1313. @ The constructor creates the object and adds the required properties to it.
  1314. @<Functions for scripting@>=
  1315. QScriptValue constructQSplitter(QScriptContext *, QScriptEngine *engine)
  1316. {
  1317. QScriptValue object = engine->newQObject(new QSplitter);
  1318. setQSplitterProperties(object, engine);
  1319. return object;
  1320. }
  1321. void setQSplitterProperties(QScriptValue value, QScriptEngine *engine)
  1322. {
  1323. setQFrameProperties(value, engine);
  1324. value.setProperty("addWidget", engine->newFunction(QSplitter_addWidget));
  1325. value.setProperty("saveState", engine->newFunction(QSplitter_saveState));
  1326. value.setProperty("restoreState",
  1327. engine->newFunction(QSplitter_restoreState));
  1328. }
  1329. @ The |"addWidget"| property is a simple wrapper around
  1330. |QSplitter::addWidget()|.
  1331. @<Functions for scripting@>=
  1332. QScriptValue QSplitter_addWidget(QScriptContext *context, QScriptEngine *)
  1333. {
  1334. if(context->argumentCount() == 1)
  1335. {
  1336. QSplitter *self = getself<QSplitter *>(context);
  1337. QWidget *widget = argument<QWidget *>(0, context);
  1338. if(widget)
  1339. {
  1340. self->addWidget(widget);
  1341. }
  1342. else
  1343. {
  1344. context->throwError("Incorrect argument type passed to "@|
  1345. "QSplitter::addWidget(). This method "@|
  1346. "requires a QWidget.");
  1347. }
  1348. }
  1349. else
  1350. {
  1351. context->throwError("Incorrect number of arguments passed to "@|
  1352. "QSplitter::addWidget(). This method takes one "@|
  1353. "QWidget as an argument.");
  1354. }
  1355. return QScriptValue();
  1356. }
  1357. @ When saving and restoring the state of a splitter, we always want to do this
  1358. through a |QSettings| object. For this, we take an extra argument specifying the
  1359. settings key to read from or write to. Unlike the equivalent functions called
  1360. from native code, neither of these functions called from a script will return
  1361. the data being saved.
  1362. @<Functions for scripting@>=
  1363. QScriptValue QSplitter_saveState(QScriptContext *context, QScriptEngine *)
  1364. {
  1365. if(context->argumentCount() == 1)
  1366. {
  1367. QSplitter *self = getself<QSplitter *>(context);
  1368. QString key = argument<QString>(0, context);
  1369. QSettings settings;
  1370. settings.setValue(key, self->saveState());
  1371. }
  1372. else
  1373. {
  1374. context->throwError("Incorrect number of arguments passed to "@|
  1375. "QSplitter::saveState(). This method takes one "@|
  1376. "string as an argument.");
  1377. }
  1378. return QScriptValue();
  1379. }
  1380. QScriptValue QSplitter_restoreState(QScriptContext *context, QScriptEngine *)
  1381. {
  1382. if(context->argumentCount() == 1)
  1383. {
  1384. QSplitter *self = getself<QSplitter *>(context);
  1385. QString key = argument<QString>(0, context);
  1386. QSettings settings;
  1387. self->restoreState(settings.value(key).toByteArray());
  1388. }
  1389. else
  1390. {
  1391. context->throwError("Incorrect number of arguments passed to "@|
  1392. "QSplitter::restoreState(). This method takes "@|
  1393. "one string as an argument.");
  1394. }
  1395. return QScriptValue();
  1396. }
  1397. @* Scripting Layout classes.
  1398. \noindent Layout classes simplify managing the size and position of widgets in a
  1399. user interface. Qt provides several such classes, including |QBoxLayout| which
  1400. can be used to construct a variety of different interfaces. As widgets
  1401. containing a layout should not really need to care which layout is being used,
  1402. the |QLayout| class acts as an abstract base for all layout classes. A bare
  1403. |QLayout| will never be constructed, however subclasses can make use of the
  1404. |addWidget()| property.
  1405. @<Function prototypes for scripting@>=
  1406. void setQLayoutProperties(QScriptValue value, QScriptEngine *engine);
  1407. QScriptValue QLayout_addWidget(QScriptContext *context, QScriptEngine *engine);
  1408. @ The implementation is trivial.
  1409. @<Functions for scripting@>=
  1410. void setQLayoutProperties(QScriptValue value, QScriptEngine *engine)
  1411. {
  1412. setQLayoutItemProperties(value, engine);
  1413. value.setProperty("addWidget", engine->newFunction(QLayout_addWidget));
  1414. }
  1415. QScriptValue QLayout_addWidget(QScriptContext *context, QScriptEngine *)
  1416. {
  1417. if(context->argumentCount() == 1)
  1418. {
  1419. QLayout *self = getself<QLayout *>(context);
  1420. QWidget *widget = argument<QWidget *>(0, context);
  1421. if(widget)
  1422. {
  1423. self->addWidget(widget);
  1424. }
  1425. else
  1426. {
  1427. context->throwError("Incorrect argument type passed to "@|
  1428. "QLayout::addWidget(). This method requires "@|
  1429. "a QWidget.");
  1430. }
  1431. }
  1432. else
  1433. {
  1434. context->throwError("Incorrect number of arguments passed to "@|
  1435. "QLayout::addWidget(). This method takes one "@|
  1436. "QWidget as an argument.");
  1437. }
  1438. return QScriptValue();
  1439. }
  1440. @ |QBoxLayout| is a more interesting layout class. This allows widgets to be
  1441. arranged in a single row or column and can be used, for example, to arrange a
  1442. row of buttons as in figure \secno.
  1443. \medskip
  1444. \resizebox*{6.3in}{!}{\includegraphics{boxlayoutexample}}
  1445. \smallskip
  1446. \centerline{Figure \secno: Buttons in a |QBoxLayout|.}
  1447. \medskip
  1448. This class makes use of the |addWidget()| method from |QLayout|.
  1449. @<Function prototypes for scripting@>=
  1450. QScriptValue constructQBoxLayout(QScriptContext *context,
  1451. QScriptEngine *engine);
  1452. void setQBoxLayoutProperties(QScriptValue value, QScriptEngine *engine);
  1453. QScriptValue QBoxLayout_addLayout(QScriptContext *context, QScriptEngine *engine);
  1454. QScriptValue QBoxLayout_addWidget(QScriptContext *context, QScriptEngine *engine);
  1455. @ The script constructor must be passed to the scripting engine.
  1456. @<Set up the scripting engine@>=
  1457. constructor = engine->newFunction(constructQBoxLayout);
  1458. value = engine->newQMetaObject(&QBoxLayout::staticMetaObject, constructor);
  1459. engine->globalObject().setProperty("QBoxLayout", value);
  1460. @ The implementation of these functions should seem familiar by now. Note that
  1461. while a horizontal layout is provided by default, this can be changed from the
  1462. script once the layout is created.
  1463. @<Functions for scripting@>=
  1464. QScriptValue constructQBoxLayout(QScriptContext *, QScriptEngine *engine)
  1465. {
  1466. QScriptValue object =
  1467. engine->newQObject(new QBoxLayout(QBoxLayout::LeftToRight));
  1468. setQBoxLayoutProperties(object, engine);
  1469. return object;
  1470. }
  1471. void setQBoxLayoutProperties(QScriptValue value, QScriptEngine *engine)
  1472. {
  1473. setQLayoutProperties(value, engine);
  1474. value.setProperty("addLayout", engine->newFunction(QBoxLayout_addLayout));
  1475. value.setProperty("addWidget", engine->newFunction(QBoxLayout_addWidget));
  1476. }
  1477. QScriptValue QBoxLayout_addLayout(QScriptContext *context, QScriptEngine *)
  1478. {
  1479. if(context->argumentCount() > 0 && context->argumentCount() < 3)
  1480. {
  1481. QBoxLayout *self = getself<QBoxLayout *>(context);
  1482. QLayout *layout = argument<QLayout *>(0, context);
  1483. int stretch = 0;
  1484. if(context->argumentCount() == 2)
  1485. {
  1486. stretch = argument<int>(1, context);
  1487. }
  1488. if(layout)
  1489. {
  1490. self->addLayout(layout, stretch);
  1491. }
  1492. else
  1493. {
  1494. context->throwError("Incorrect argument type passed to "@|
  1495. "QLayout::addLayout(). This method requires "@|
  1496. "a QLayout.");
  1497. }
  1498. }
  1499. else
  1500. {
  1501. context->throwError("Incorrect number of arguments passed to "@|
  1502. "QLayout::addLayout(). This method takes one "@|
  1503. "QLayout as an argument and optionally one integer.");
  1504. }
  1505. return QScriptValue();
  1506. }
  1507. @ We override the base class wrapper for |addWidget| to add two optional
  1508. arguments: one specifies the stretch factor of the widget and the other
  1509. specifies the alignment of the widget within the layout.
  1510. @<Functions for scripting@>=
  1511. QScriptValue QBoxLayout_addWidget(QScriptContext *context, QScriptEngine *)
  1512. {
  1513. if(context->argumentCount() > 0 && context->argumentCount() < 4)
  1514. {
  1515. QBoxLayout *self = getself<QBoxLayout *>(context);
  1516. QWidget *widget = argument<QWidget *>(0, context);
  1517. int stretch = 0;
  1518. Qt::Alignment alignment = 0;
  1519. if(context->argumentCount() > 1)
  1520. {
  1521. stretch = argument<int>(1, context);
  1522. }
  1523. if(context->argumentCount() > 2)
  1524. {
  1525. alignment = (Qt::Alignment)(argument<int>(2, context));
  1526. }
  1527. if(widget)
  1528. {
  1529. self->addWidget(widget, stretch, alignment);
  1530. }
  1531. else
  1532. {
  1533. context->throwError("Incorrect argument type passed to "@|
  1534. "QBoxLayout::addWidget(). This method requires "@|
  1535. "a QWidget.");
  1536. }
  1537. }
  1538. else
  1539. {
  1540. context->throwError("Incorrect number of arguments passed to "@|
  1541. "QBoxLayout::addWidget(). This method takes one "@|
  1542. "QWidget and optionally up to two integers as "@|
  1543. "arguments.");
  1544. }
  1545. return QScriptValue();
  1546. }
  1547. @* Scripting QAction.
  1548. \noindent The |QAction| class is used in \pn{} to create menu items and respond
  1549. to the selection of these items. Three functions are required for our scripting
  1550. needs with regard to this class.
  1551. @<Function prototypes for scripting@>=
  1552. QScriptValue constructQAction(QScriptContext *context, QScriptEngine *engine);
  1553. QScriptValue QAction_setShortcut(QScriptContext *context,
  1554. QScriptEngine *engine);
  1555. void setQActionProperties(QScriptValue value, QScriptEngine *engine);
  1556. @ The scripting engine must be informed of the constructor.
  1557. @<Set up the scripting engine@>=
  1558. constructor = engine->newFunction(constructQAction);
  1559. value = engine->newQMetaObject(&QAction::staticMetaObject, constructor);
  1560. engine->globalObject().setProperty("QAction", value);
  1561. @ The constructor is simple, however some might sensibly question why the
  1562. |"setShortcut"| property is needed at all. Why not have scripts simply set the
  1563. |shortcut| property of the |QAction| directly? The answer to this is that the
  1564. property expects data of the |QKeySequence| type. While this can be created from
  1565. a |QString|, passing a string to the property through the scripting engine did
  1566. not work at the time this was written.
  1567. @<Functions for scripting@>=
  1568. QScriptValue constructQAction(QScriptContext *, QScriptEngine *engine)
  1569. {
  1570. QScriptValue object = engine->newQObject(new QAction(NULL));
  1571. setQActionProperties(object, engine);
  1572. return object;
  1573. }
  1574. void setQActionProperties(QScriptValue value, QScriptEngine *engine)
  1575. {
  1576. setQObjectProperties(value, engine);
  1577. value.setProperty("setShortcut", engine->newFunction(QAction_setShortcut));
  1578. }
  1579. QScriptValue QAction_setShortcut(QScriptContext *context, QScriptEngine *)
  1580. {
  1581. if(context->argumentCount() == 1)
  1582. {
  1583. QAction *self = getself<@[QAction *@]>(context);
  1584. self->setShortcut(argument<QString>(0, context));
  1585. }
  1586. else
  1587. {
  1588. context->throwError("Incorrect number of arguments passed to "@|
  1589. "QAction::setShortcut(). This method takes one "@|
  1590. "string as an argument.");
  1591. }
  1592. return QScriptValue();
  1593. }
  1594. @* Scripting QFileDialog.
  1595. \noindent |QFileDialog| provides two static member functions which is all that
  1596. we need. The objects returned from these methods are built on the |QDialog|
  1597. abstract base class.
  1598. @<Function prototypes for scripting@>=
  1599. QScriptValue QFileDialog_getOpenFileName(QScriptContext *context,
  1600. QScriptEngine *engine);
  1601. QScriptValue QFileDialog_getSaveFileName(QScriptContext *context,
  1602. QScriptEngine *engine);
  1603. void setQFileDialogProperties(QScriptValue value, QScriptEngine *engine);
  1604. void setQDialogProperties(QScriptValue value, QScriptEngine *engine);
  1605. @ The scripting engine must be informed of the wrapper functions for the static
  1606. methods.
  1607. @<Set up the scripting engine@>=
  1608. value = engine->newQMetaObject(&QFileDialog::staticMetaObject);
  1609. value.setProperty("getOpenFileName",
  1610. engine->newFunction(QFileDialog_getOpenFileName));
  1611. value.setProperty("getSaveFileName",
  1612. engine->newFunction(QFileDialog_getSaveFileName));
  1613. engine->globalObject().setProperty("QFileDialog", value);
  1614. @ This function is just a simple wrapper around the |QFileDialog| method, but
  1615. the object returned has any properties added to the base class available.
  1616. @<Functions for scripting@>=
  1617. QScriptValue QFileDialog_getOpenFileName(QScriptContext *context,
  1618. QScriptEngine *engine)
  1619. {
  1620. QScriptValue retval;
  1621. if(context->argumentCount() == 3)
  1622. {
  1623. QWidget *widget = argument<QWidget *>(0, context);
  1624. if(widget)
  1625. {
  1626. QString caption = argument<QString>(1, context);
  1627. QString dir = argument<QString>(2, context);
  1628. retval = QScriptValue(engine,
  1629. QFileDialog::getOpenFileName(widget, caption,
  1630. dir, "", 0, 0));
  1631. setQFileDialogProperties(retval, engine);
  1632. }
  1633. else
  1634. {
  1635. context->throwError("Incorrect argument type passed to "@|
  1636. "QFileDialog::getOpenFileName(). The first "@|
  1637. "argument to this method must be a QWidget.");
  1638. }
  1639. }
  1640. else
  1641. {
  1642. context->throwError("Incorrect number of arguments passed to "@|
  1643. "QFileDialog::getOpenFileName(). This method "@|
  1644. "takes one QWidget followed by two strings for a "@|
  1645. "total of three arguments.");
  1646. }
  1647. return retval;
  1648. }
  1649. @ Similarly, this just wraps |QFileDialog::getSaveFileName()|.
  1650. @<Functions for scripting@>=
  1651. QScriptValue QFileDialog_getSaveFileName(QScriptContext *context,
  1652. QScriptEngine *engine)
  1653. {
  1654. QScriptValue retval;
  1655. if(context->argumentCount() == 3)
  1656. {
  1657. QWidget *widget = argument<QWidget *>(0, context);
  1658. if(widget)
  1659. {
  1660. QString caption = argument<QString>(1, context);
  1661. QString dir = argument<QString>(2, context);
  1662. retval = QScriptValue(engine,
  1663. QFileDialog::getSaveFileName(widget, caption,
  1664. dir, "", 0, 0));
  1665. setQFileDialogProperties(retval, engine);
  1666. }
  1667. else
  1668. {
  1669. context->throwError("Incorrect argument type passed to "@|
  1670. "QFileDialog::getSaveFileName(). The first "@|
  1671. "argument to this method must be a QWidget.");
  1672. }
  1673. }
  1674. else
  1675. {
  1676. context->throwError("Incorrect number of arguments passed to "@|
  1677. "QFileDialog::getSaveFileName(). This method "@|
  1678. "takes one QWidget followed by two strings for a "@|
  1679. "total of three arguments.");
  1680. }
  1681. return retval;
  1682. }
  1683. @ Adding object hierarchy properties to the objects created above is simple.
  1684. @<Functions for scripting@>=
  1685. void setQFileDialogProperties(QScriptValue value, QScriptEngine *engine)
  1686. {
  1687. setQDialogProperties(value, engine);
  1688. }
  1689. void setQDialogProperties(QScriptValue value, QScriptEngine *engine)
  1690. {
  1691. setQWidgetProperties(value, engine);
  1692. }
  1693. @* Scripting QFile.
  1694. \noindent When using a |QFile| in a script, we only need the constructor and two
  1695. functions for hooking it in with the rest of the object hierarchy.
  1696. @<Function prototypes for scripting@>=
  1697. QScriptValue constructQFile(QScriptContext *context, QScriptEngine *engine);
  1698. void setQFileProperties(QScriptValue value, QScriptEngine *engine);
  1699. QScriptValue QFile_remove(QScriptContext *context, QScriptEngine *engine);
  1700. void setQIODeviceProperties(QScriptValue value, QScriptEngine *engine);
  1701. QScriptValue QIODevice_open(QScriptContext *context, QScriptEngine *engine);
  1702. QScriptValue QIODevice_close(QScriptContext *context, QScriptEngine *engine);
  1703. QScriptValue QIODevice_readToString(QScriptContext *context,
  1704. QScriptEngine *engine);
  1705. @ This function is passed to the scripting engine.
  1706. @<Set up the scripting engine@>=
  1707. constructor = engine->newFunction(constructQFile);
  1708. value = engine->newQMetaObject(&QFile::staticMetaObject, constructor);
  1709. engine->globalObject().setProperty("QFile", value);
  1710. @ The implementation is trivial.
  1711. @<Functions for scripting@>=
  1712. QScriptValue constructQFile(QScriptContext *context, QScriptEngine *engine)
  1713. {
  1714. QScriptValue object =
  1715. engine->newQObject(new QFile(argument<QString>(0, context)));@/
  1716. setQFileProperties(object, engine);
  1717. return object;
  1718. }
  1719. @ |QFile| gets a wrapper around |remove()| to support deleting temporary files.
  1720. @<Functions for scripting@>=
  1721. void setQFileProperties(QScriptValue value, QScriptEngine *engine)
  1722. {
  1723. setQIODeviceProperties(value, engine);
  1724. value.setProperty("remove", engine->newFunction(QFile_remove));
  1725. }
  1726. QScriptValue QFile_remove(QScriptContext *context, QScriptEngine *engine)
  1727. {
  1728. QFile *self = getself<QFile *>(context);
  1729. bool retval = self->remove();
  1730. return QScriptValue(engine, retval);
  1731. }
  1732. @ Although we aren't going to create any instances of |QIODevice| directly,
  1733. subclasses such as |QFile| and |QBuffer| get two additional properties for
  1734. opening and closing the device.
  1735. In order to solve some class interoperability issues, a convenience method is
  1736. also added which is equivalent to creating a |QString| from the |QByteArray|
  1737. returned from the |readAll()| method.
  1738. @<Functions for scripting@>=
  1739. void setQIODeviceProperties(QScriptValue value, QScriptEngine *engine)
  1740. {
  1741. setQObjectProperties(value, engine);
  1742. value.setProperty("open", engine->newFunction(QIODevice_open));
  1743. value.setProperty("close", engine->newFunction(QIODevice_close));
  1744. value.setProperty("readToString",
  1745. engine->newFunction(QIODevice_readToString));
  1746. }
  1747. @ These are simple wrappers. In the case of the |open()| property, one argument
  1748. may be passed specifying the mode used for opening. The supported values for
  1749. this are 1 (Read Only), 2 (Write Only), and 3 (Read Write). If this argument is
  1750. not passed, it is assumed that the user wants read and write access.
  1751. @<Functions for scripting@>=
  1752. QScriptValue QIODevice_open(QScriptContext *context, QScriptEngine *)
  1753. {
  1754. QIODevice *self = getself<QIODevice *>(context);
  1755. if(context->argumentCount() == 1)
  1756. {
  1757. switch(argument<int>(0, context))
  1758. {
  1759. case 1:
  1760. self->open(QIODevice::ReadOnly);
  1761. break;
  1762. case 2:
  1763. self->open(QIODevice::WriteOnly);
  1764. break;
  1765. case 3:
  1766. self->open(QIODevice::ReadWrite);
  1767. break;
  1768. default:
  1769. break;
  1770. }
  1771. }
  1772. else
  1773. {
  1774. self->open(QIODevice::ReadWrite);
  1775. }
  1776. return QScriptValue();
  1777. }
  1778. QScriptValue QIODevice_close(QScriptContext *context, QScriptEngine *)
  1779. {
  1780. QIODevice *self = getself<QIODevice *>(context);
  1781. self->close();
  1782. return QScriptValue();
  1783. }
  1784. @ The |readToString()| method is a simple extension of |QIODevice::readAll()| to
  1785. interface with classes that expect document data in the form of a string. Most
  1786. notably, this includes |QWebView|.
  1787. @<Functions for scripting@>=
  1788. QScriptValue QIODevice_readToString(QScriptContext *context, QScriptEngine *)
  1789. {
  1790. QIODevice *self = getself<QIODevice *>(context);
  1791. self->reset();
  1792. return QScriptValue(QString(self->readAll()));
  1793. }
  1794. @* Scripting QBuffer.
  1795. \noindent Sometimes it is desirable to load a roast profile from a file. At
  1796. other times, it is more useful to load that profile from a byte array stored in
  1797. a database. The |XMLInput| class takes data from a |QIODevice| object, which
  1798. means that we can choose from a |QFile| when we want the former or a |QBuffer|
  1799. when we want the latter.
  1800. @<Function prototypes for scripting@>=
  1801. QScriptValue constructQBuffer(QScriptContext *context, QScriptEngine *engine);
  1802. void setQBufferProperties(QScriptValue value, QScriptEngine *engine);
  1803. QScriptValue QBuffer_setData(QScriptContext *context, QScriptEngine *engine);
  1804. @ The host environment needs to be aware of the constructor.
  1805. @<Set up the scripting engine@>=
  1806. constructor = engine->newFunction(constructQBuffer);
  1807. value = engine->newQMetaObject(&QBuffer::staticMetaObject, constructor);
  1808. engine->globalObject().setProperty("QBuffer", value);
  1809. @ The implementation is trivial.
  1810. @<Functions for scripting@>=
  1811. QScriptValue constructQBuffer(QScriptContext *context, QScriptEngine *engine)
  1812. {
  1813. QByteArray *array = new QByteArray(argument<QString>(0, context).toAscii());
  1814. QScriptValue object = engine->newQObject(new QBuffer(array));
  1815. setQBufferProperties(object, engine);
  1816. return object;
  1817. }
  1818. void setQBufferProperties(QScriptValue value, QScriptEngine *engine)
  1819. {
  1820. setQIODeviceProperties(value, engine);
  1821. value.setProperty("setData", engine->newFunction(QBuffer_setData));
  1822. }
  1823. QScriptValue QBuffer_setData(QScriptContext *context, QScriptEngine *)
  1824. {
  1825. QBuffer *self = getself<QBuffer *>(context);
  1826. self->setData(argument<QString>(0, context).toAscii());
  1827. return QScriptValue();
  1828. }
  1829. @* Scripting QXmlQuery.
  1830. \noindent Sometimes we have some XML data in a file or a buffer and we would
  1831. like to extract certain information from that data in the host environment.
  1832. Rather than write complicated string manipulation routines in an attempt to deal
  1833. with this sensibly, we can use the XQuery language to extract the information we
  1834. want. One common use case for this is extracting all measurements from a roast
  1835. profile that are associated with an annotation.
  1836. @<Function prototypes for scripting@>=
  1837. QScriptValue constructXQuery(QScriptContext *context, QScriptEngine *engine);
  1838. QScriptValue XQuery_bind(QScriptContext *context, QScriptEngine *engine);
  1839. QScriptValue XQuery_exec(QScriptContext *context, QScriptEngine *engine);
  1840. QScriptValue XQuery_setQuery(QScriptContext *context, QScriptEngine *engine);
  1841. void setXQueryProperties(QScriptValue value, QScriptEngine *engine);
  1842. @ The constructor must be registered with the host environment. This is done a
  1843. bit differently from most classes as |QXmlQuery| is not a |QObject|.
  1844. @<Set up the scripting engine@>=
  1845. constructor = engine->newFunction(constructXQuery);
  1846. engine->globalObject().setProperty("XQuery", constructor);
  1847. @ The constructor just needs to make sure the functions we want to make
  1848. available are applied.
  1849. @<Functions for scripting@>=
  1850. QScriptValue constructXQuery(QScriptContext *, QScriptEngine *engine)
  1851. {
  1852. QScriptValue object = engine->toScriptValue<void *>(new QXmlQuery);
  1853. setXQueryProperties(object, engine);
  1854. return object;
  1855. }
  1856. void setXQueryProperties(QScriptValue value, QScriptEngine *engine)
  1857. {
  1858. value.setProperty("bind", engine->newFunction(XQuery_bind));
  1859. value.setProperty("exec", engine->newFunction(XQuery_exec));
  1860. value.setProperty("setQuery", engine->newFunction(XQuery_setQuery));
  1861. }
  1862. @ The |bind()| property can be used to specify a |QIODevice| to be referenced by
  1863. a variable within a query.
  1864. @<Functions for scripting@>=
  1865. QScriptValue XQuery_bind(QScriptContext *context, QScriptEngine *)
  1866. {
  1867. QXmlQuery *self = getself<QXmlQuery *>(context);
  1868. QIODevice *buffer = argument<QIODevice *>(1, context);
  1869. self->bindVariable(argument<QString>(0, context), buffer);
  1870. return QScriptValue();
  1871. }
  1872. @ A method is also required for setting the query we wish to conduct.
  1873. @<Functions for scripting@>=
  1874. QScriptValue XQuery_setQuery(QScriptContext *context, QScriptEngine *)
  1875. {
  1876. QXmlQuery *self = getself<QXmlQuery *>(context);
  1877. self->setQuery(argument<QString>(0, context));
  1878. return QScriptValue();
  1879. }
  1880. @ This method runs the previously specified query.
  1881. @<Functions for scripting@>=
  1882. QScriptValue XQuery_exec(QScriptContext *context, QScriptEngine *)
  1883. {
  1884. QXmlQuery *self = getself<QXmlQuery *>(context);
  1885. QString result;
  1886. self->evaluateTo(&result);
  1887. return QScriptValue(result);
  1888. }
  1889. @* Scripting QXmlStreamWriter.
  1890. \noindent There are some cases where it may be desirable to produce XML from the
  1891. host environment. While there are several ways to accomplish this, the
  1892. |QXmlStreamWriter| class greatly simplifies generating complex XML documents.
  1893. This class is not related to |QObject|, so several functions are needed to
  1894. expose the functionality of this class to the host environment.
  1895. @<Function prototypes for scripting@>=
  1896. QScriptValue constructXmlWriter(QScriptContext *context, QScriptEngine *engine);
  1897. QScriptValue XmlWriter_setDevice(QScriptContext *context,
  1898. QScriptEngine *engine);
  1899. QScriptValue XmlWriter_writeAttribute(QScriptContext *context,
  1900. QScriptEngine *engine);
  1901. QScriptValue XmlWriter_writeCDATA(QScriptContext *context,
  1902. QScriptEngine *engine);
  1903. QScriptValue XmlWriter_writeCharacters(QScriptContext *context,
  1904. QScriptEngine *engine);
  1905. QScriptValue XmlWriter_writeDTD(QScriptContext *context, QScriptEngine *engine);
  1906. QScriptValue XmlWriter_writeEmptyElement(QScriptContext *context,
  1907. QScriptEngine *engine);
  1908. QScriptValue XmlWriter_writeEndDocument(QScriptContext *context,
  1909. QScriptEngine *engine);
  1910. QScriptValue XmlWriter_writeEndElement(QScriptContext *context,
  1911. QScriptEngine *engine);
  1912. QScriptValue XmlWriter_writeEntityReference(QScriptContext *context,
  1913. QScriptEngine *engine);
  1914. QScriptValue XmlWriter_writeProcessingInstruction(QScriptContext *context,
  1915. QScriptEngine *engine);
  1916. QScriptValue XmlWriter_writeStartDocument(QScriptContext *context,
  1917. QScriptEngine *engine);
  1918. QScriptValue XmlWriter_writeStartElement(QScriptContext *context,
  1919. QScriptEngine *engine);
  1920. QScriptValue XmlWriter_writeTextElement(QScriptContext *context,
  1921. QScriptEngine *engine);
  1922. void setXmlWriterProperties(QScriptValue value, QScriptEngine *engine);
  1923. @ The constructor must be registered with the host environment.
  1924. @<Set up the scripting engine@>=
  1925. constructor = engine->newFunction(constructXmlWriter);
  1926. engine->globalObject().setProperty("XmlWriter", constructor);
  1927. @ The constructor takes an optional argument allowing the output device to be
  1928. specified.
  1929. @<Functions for scripting@>=
  1930. QScriptValue constructXmlWriter(QScriptContext *context, QScriptEngine *engine)
  1931. {
  1932. QXmlStreamWriter *retval;
  1933. if(context->argumentCount() == 1)
  1934. {
  1935. retval = new QXmlStreamWriter(argument<QIODevice *>(0, context));
  1936. }
  1937. else
  1938. {
  1939. retval = new QXmlStreamWriter;
  1940. }
  1941. QScriptValue object = engine->toScriptValue<void *>(retval);
  1942. setXmlWriterProperties(object, engine);
  1943. return object;
  1944. }
  1945. void setXmlWriterProperties(QScriptValue value, QScriptEngine *engine)
  1946. {
  1947. value.setProperty("setDevice", engine->newFunction(XmlWriter_setDevice));
  1948. value.setProperty("writeAttribute",
  1949. engine->newFunction(XmlWriter_writeAttribute));
  1950. value.setProperty("writeCDATA", engine->newFunction(XmlWriter_writeCDATA));
  1951. value.setProperty("writeCharacters",
  1952. engine->newFunction(XmlWriter_writeCharacters));
  1953. value.setProperty("writeDTD", engine->newFunction(XmlWriter_writeDTD));
  1954. value.setProperty("writeEmptyElement",
  1955. engine->newFunction(XmlWriter_writeEmptyElement));
  1956. value.setProperty("writeEndDocument",
  1957. engine->newFunction(XmlWriter_writeEndDocument));
  1958. value.setProperty("writeEndElement",
  1959. engine->newFunction(XmlWriter_writeEndElement));
  1960. value.setProperty("writeEntityReference",
  1961. engine->newFunction(XmlWriter_writeEntityReference));
  1962. value.setProperty("writeProcessingInstruction",
  1963. engine->newFunction(XmlWriter_writeProcessingInstruction));
  1964. value.setProperty("writeStartDocument",
  1965. engine->newFunction(XmlWriter_writeStartDocument));
  1966. value.setProperty("writeStartElement",
  1967. engine->newFunction(XmlWriter_writeStartElement));
  1968. value.setProperty("writeTextElement",
  1969. engine->newFunction(XmlWriter_writeTextElement));
  1970. }
  1971. @ If the output device needs to be changed or if one is not passed to the
  1972. constructor, the |setDevice()| method can be used.
  1973. @<Functions for scripting@>=
  1974. QScriptValue XmlWriter_setDevice(QScriptContext *context, QScriptEngine *)
  1975. {
  1976. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  1977. QIODevice *device = argument<QIODevice *>(0, context);
  1978. self->setDevice(device);
  1979. return QScriptValue();
  1980. }
  1981. @ The remaining functions are simple wrappers used for writing various types of
  1982. data. After creating a writer and setting the output device, the start of the
  1983. document should be written. One argument is required containing the XML version
  1984. number. Another function handles writing the end of the document.
  1985. @<Functions for scripting@>=
  1986. QScriptValue XmlWriter_writeStartDocument(QScriptContext *context,
  1987. QScriptEngine *)
  1988. {
  1989. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  1990. self->writeStartDocument(argument<QString>(0, context));
  1991. return QScriptValue();
  1992. }
  1993. QScriptValue XmlWriter_writeEndDocument(QScriptContext *context,
  1994. QScriptEngine *)
  1995. {
  1996. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  1997. self->writeEndDocument();
  1998. return QScriptValue();
  1999. }
  2000. @ After the start of the document, a DTD is commonly needed.
  2001. @<Functions for scripting@>=
  2002. QScriptValue XmlWriter_writeDTD(QScriptContext *context, QScriptEngine *)
  2003. {
  2004. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2005. self->writeDTD(argument<QString>(0, context));
  2006. return QScriptValue();
  2007. }
  2008. @ After this, elements need to be written. For this, we write the start
  2009. element, any attributes needed, character data, and the end element.
  2010. @<Functions for scripting@>=
  2011. QScriptValue XmlWriter_writeStartElement(QScriptContext *context,
  2012. QScriptEngine *)
  2013. {
  2014. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2015. self->writeStartElement(argument<QString>(0, context));
  2016. return QScriptValue();
  2017. }
  2018. QScriptValue XmlWriter_writeAttribute(QScriptContext *context, QScriptEngine *)
  2019. {
  2020. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2021. self->writeAttribute(argument<QString>(0, context),
  2022. argument<QString>(1, context));
  2023. return QScriptValue();
  2024. }
  2025. QScriptValue XmlWriter_writeCharacters(QScriptContext *context, QScriptEngine *)
  2026. {
  2027. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2028. self->writeCharacters(argument<QString>(0, context));
  2029. return QScriptValue();
  2030. }
  2031. QScriptValue XmlWriter_writeEndElement(QScriptContext *context, QScriptEngine *)
  2032. {
  2033. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2034. self->writeEndElement();
  2035. return QScriptValue();
  2036. }
  2037. @ For convenience, two other methods are provided for writing elements. Elements
  2038. which do not require anything between the start and end elements can be created
  2039. with |writeEmptyElement()|. Elements which do not require attributes, but do
  2040. contain text can be created with |writeTextElement()|.
  2041. @<Functions for scripting@>=
  2042. QScriptValue XmlWriter_writeEmptyElement(QScriptContext *context,
  2043. QScriptEngine *)
  2044. {
  2045. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2046. self->writeEmptyElement(argument<QString>(0, context));
  2047. return QScriptValue();
  2048. }
  2049. QScriptValue XmlWriter_writeTextElement(QScriptContext *context,
  2050. QScriptEngine *)
  2051. {
  2052. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2053. self->writeTextElement(argument<QString>(0, context),
  2054. argument<QString>(1, context));
  2055. return QScriptValue();
  2056. }
  2057. @ Less commonly needed are functions for writing CDATA sections, entity
  2058. references, and processing instructions.
  2059. @<Functions for scripting@>=
  2060. QScriptValue XmlWriter_writeCDATA(QScriptContext *context, QScriptEngine *)
  2061. {
  2062. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2063. self->writeCDATA(argument<QString>(0, context));
  2064. return QScriptValue();
  2065. }
  2066. QScriptValue XmlWriter_writeEntityReference(QScriptContext *context,
  2067. QScriptEngine *)
  2068. {
  2069. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2070. self->writeEntityReference(argument<QString>(0, context));
  2071. return QScriptValue();
  2072. }
  2073. QScriptValue XmlWriter_writeProcessingInstruction(QScriptContext *context,
  2074. QScriptEngine *)
  2075. {
  2076. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2077. self->writeProcessingInstruction(argument<QString>(0, context),
  2078. argument<QString>(1, context));
  2079. return QScriptValue();
  2080. }
  2081. @* Scripting QXmlStreamReader.
  2082. \noindent When a serializer is written using |QXmlStreamWriter|, a corresponding
  2083. deserializer should also be written. While there are several possible ways to do
  2084. this, using |QXmlStreamReader| is often the best choice. \pn{} provides a subset
  2085. of the functionality from this class which should be adequate for most purposes.
  2086. @<Function prototypes for scripting@>=
  2087. QScriptValue constructXmlReader(QScriptContext *context, QScriptEngine *engine);
  2088. QScriptValue XmlReader_atEnd(QScriptContext *context, QScriptEngine *engine);
  2089. QScriptValue XmlReader_attribute(QScriptContext *context,
  2090. QScriptEngine *engine);
  2091. QScriptValue XmlReader_hasAttribute(QScriptContext *context,
  2092. QScriptEngine *engine);
  2093. QScriptValue XmlReader_isDTD(QScriptContext *context, QScriptEngine *engine);
  2094. QScriptValue XmlReader_isStartElement(QScriptContext *context,
  2095. QScriptEngine *engine);
  2096. QScriptValue XmlReader_name(QScriptContext *context, QScriptEngine *engine);
  2097. QScriptValue XmlReader_readElementText(QScriptContext *context,
  2098. QScriptEngine *engine);
  2099. QScriptValue XmlReader_readNext(QScriptContext *context, QScriptEngine *engine);
  2100. QScriptValue XmlReader_text(QScriptContext *context, QScriptEngine *engine);
  2101. void setXmlReaderProperties(QScriptValue value, QScriptEngine *engine);
  2102. @ The constructor must be registered with the host environment.
  2103. @<Set up the scripting engine@>=
  2104. constructor = engine->newFunction(constructXmlReader);
  2105. engine->globalObject().setProperty("XmlReader", constructor);
  2106. @ The constructor requires an argument specifying the output device. This can be
  2107. any |QIODevice|. The |open()| method must be called on the device before passing
  2108. it as an argument to this function.
  2109. @<Functions for scripting@>=
  2110. QScriptValue constructXmlReader(QScriptContext *context, QScriptEngine *engine)
  2111. {
  2112. QXmlStreamReader *retval =
  2113. new QXmlStreamReader(argument<QIODevice *>(0, context));
  2114. QScriptValue object = engine->toScriptValue<void *>(retval);
  2115. setXmlReaderProperties(object, engine);
  2116. return object;
  2117. }
  2118. void setXmlReaderProperties(QScriptValue value, QScriptEngine *engine)
  2119. {
  2120. value.setProperty("atEnd", engine->newFunction(XmlReader_atEnd));
  2121. value.setProperty("attribute", engine->newFunction(XmlReader_attribute));
  2122. value.setProperty("hasAttribute",
  2123. engine->newFunction(XmlReader_hasAttribute));
  2124. value.setProperty("isDTD", engine->newFunction(XmlReader_isDTD));
  2125. value.setProperty("isStartElement",
  2126. engine->newFunction(XmlReader_isStartElement));
  2127. value.setProperty("name", engine->newFunction(XmlReader_name));
  2128. value.setProperty("readElementText",
  2129. engine->newFunction(XmlReader_readElementText));
  2130. value.setProperty("readNext",
  2131. engine->newFunction(XmlReader_readNext));
  2132. value.setProperty("text", engine->newFunction(XmlReader_text));
  2133. }
  2134. @ Most of the functions are simple member function wrappers. Two of these
  2135. properties are not. These are the |attribute()| and |hasAttribute()| properties.
  2136. @<Functions for scripting@>=
  2137. QScriptValue XmlReader_attribute(QScriptContext *context, QScriptEngine *)
  2138. {
  2139. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2140. QString retval =
  2141. self->attributes().value(argument<QString>(0, context)).toString();
  2142. return QScriptValue(retval);
  2143. }
  2144. QScriptValue XmlReader_hasAttribute(QScriptContext *context, QScriptEngine *)
  2145. {
  2146. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2147. bool retval =
  2148. self->attributes().hasAttribute(argument<QString>(0, context));
  2149. return QScriptValue(retval);
  2150. }
  2151. @ Other properties can be used for determining how to proceed with the
  2152. processing.
  2153. @<Functions for scripting@>=
  2154. QScriptValue XmlReader_atEnd(QScriptContext *context, QScriptEngine *)
  2155. {
  2156. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2157. return QScriptValue(self->atEnd());
  2158. }
  2159. QScriptValue XmlReader_isDTD(QScriptContext *context, QScriptEngine *)
  2160. {
  2161. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2162. return QScriptValue(self->isDTD());
  2163. }
  2164. QScriptValue XmlReader_isStartElement(QScriptContext *context, QScriptEngine *)
  2165. {
  2166. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2167. return QScriptValue(self->isStartElement());
  2168. }
  2169. @ We move from one element to the next with the |readNext()| property.
  2170. @<Functions for scripting@>=
  2171. QScriptValue XmlReader_readNext(QScriptContext *context, QScriptEngine *)
  2172. {
  2173. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2174. self->readNext();
  2175. return QScriptValue();
  2176. }
  2177. @ The remaining properties return the element name and text.
  2178. @<Functions for scripting@>=
  2179. QScriptValue XmlReader_name(QScriptContext *context, QScriptEngine *)
  2180. {
  2181. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2182. return QScriptValue(self->name().toString());
  2183. }
  2184. QScriptValue XmlReader_readElementText(QScriptContext *context, QScriptEngine *)
  2185. {
  2186. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2187. return QScriptValue(self->readElementText());
  2188. }
  2189. QScriptValue XmlReader_text(QScriptContext *context, QScriptEngine *)
  2190. {
  2191. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2192. return QScriptValue(self->text().toString());
  2193. }
  2194. @* Scripting QSettings.
  2195. \noindent Rather than have a script create a |QSettings| object when it needs to
  2196. save or load settings, the object is provided along with properties for getting
  2197. and setting values. Two functions are needed for this along with a third which
  2198. ensures any properties added to |QObject| are also available to |QSettings| from
  2199. the host environment.
  2200. @<Function prototypes for scripting@>=
  2201. QScriptValue QSettings_value(QScriptContext *context, QScriptEngine *engine);
  2202. QScriptValue QSettings_setValue(QScriptContext *context, QScriptEngine *engine);
  2203. void setQSettingsProperties(QScriptValue value, QScriptEngine *engine);
  2204. @ The object with properties for these functions is passed to the scripting
  2205. engine.
  2206. @<Set up the scripting engine@>=
  2207. value = engine->newQObject(&settings);
  2208. setQSettingsProperties(value, engine);
  2209. engine->globalObject().setProperty("QSettings", value);
  2210. @ Adding properties to the |QSettings| object should seem familiar.
  2211. @<Functions for scripting@>=
  2212. void setQSettingsProperties(QScriptValue value, QScriptEngine *engine)
  2213. {
  2214. setQObjectProperties(value, engine);
  2215. value.setProperty("value", engine->newFunction(QSettings_value));
  2216. value.setProperty("setValue", engine->newFunction(QSettings_setValue));
  2217. }
  2218. @ When getting a value from saved settings, there is the possibility that there
  2219. will not be a value saved for the requested key. An optional second argument can
  2220. be used to supply a default value.
  2221. @<Functions for scripting@>=
  2222. QScriptValue QSettings_value(QScriptContext *context, QScriptEngine *engine)
  2223. {
  2224. QScriptValue object;
  2225. if(context->argumentCount() == 1 || context->argumentCount() == 2)
  2226. {
  2227. QSettings settings;
  2228. QString key = argument<QString>(0, context);
  2229. QVariant value;
  2230. QVariant retval;
  2231. if(context->argumentCount() > 1)
  2232. {
  2233. value = argument<QVariant>(1, context);
  2234. retval = settings.value(key, value);
  2235. }
  2236. else
  2237. {
  2238. retval = settings.value(key);
  2239. }
  2240. object = engine->newVariant(retval);
  2241. }
  2242. else
  2243. {
  2244. context->throwError("Incorrect number of arguments passed to "@|
  2245. "QSettings::value(). This method takes one "@|
  2246. "string and one optional variant type.");
  2247. }
  2248. return object;
  2249. }
  2250. QScriptValue QSettings_setValue(QScriptContext *context, QScriptEngine *)
  2251. {
  2252. if(context->argumentCount() == 2)
  2253. {
  2254. QSettings settings;
  2255. QString key = argument<QString>(0, context);
  2256. QVariant value = argument<QVariant>(1, context);
  2257. settings.setValue(key, value);
  2258. }
  2259. else
  2260. {
  2261. context->throwError("Incorrect number of arguments passed to "@|
  2262. "QSettings::setValue(). This method takes one "@|
  2263. "string and one variant type for a total of two "@|
  2264. "arguments.");
  2265. }
  2266. return QScriptValue();
  2267. }
  2268. @* Scripting QLCDNumber.
  2269. \noindent |QLCDNumber| is used as a base class for \pn{}'s |TemperatureDisplay|
  2270. and |TimerDisplay| classes, but it can also be used on its own for the display
  2271. of mainly numeric information.
  2272. @<Function prototypes for scripting@>=
  2273. QScriptValue constructQLCDNumber(QScriptContext *context,
  2274. QScriptEngine *engine);
  2275. void setQLCDNumberProperties(QScriptValue value, QScriptEngine *engine);
  2276. @ The constructor must be passed to the scripting engine.
  2277. @<Set up the scripting engine@>=
  2278. constructor = engine->newFunction(constructQLCDNumber);
  2279. value = engine->newQMetaObject(&QLCDNumber::staticMetaObject, constructor);
  2280. engine->globalObject().setProperty("QLCDNumber", value);
  2281. @ There is nothing special about the implementation.
  2282. @<Functions for scripting@>=
  2283. QScriptValue constructQLCDNumber(QScriptContext *, QScriptEngine *engine)
  2284. {
  2285. QScriptValue object = engine->newQObject(new QLCDNumber());
  2286. setQLCDNumberProperties(object, engine);
  2287. return object;
  2288. }
  2289. void setQLCDNumberProperties(QScriptValue value, QScriptEngine *engine)
  2290. {
  2291. setQFrameProperties(value, engine);
  2292. }
  2293. @* Scripting QTime.
  2294. \noindent |QTime| is a little different from the classes examined so far. This
  2295. class can be used for synchonizing time among various objects by creating a
  2296. common base reference time. This should not be needed as ECMA-262 already
  2297. specifies a |Date| class, however this has historically been troublesome to use.
  2298. One thing that makes this class different is that it is not related to
  2299. |QObject|. This makes usefully exposing it to the scripting engine a little more
  2300. difficult.
  2301. @<Function prototypes for scripting@>=
  2302. QScriptValue constructQTime(QScriptContext *context, QScriptEngine *engine);
  2303. QScriptValue QTime_addMSecs(QScriptContext *context, QScriptEngine *engine);
  2304. QScriptValue QTime_addSecs(QScriptContext *context, QScriptEngine *engine);
  2305. QScriptValue QTime_elapsed(QScriptContext *context, QScriptEngine *engine);
  2306. QScriptValue QTime_hour(QScriptContext *context, QScriptEngine *engine);
  2307. QScriptValue QTime_isNull(QScriptContext *context, QScriptEngine *engine);
  2308. QScriptValue QTime_isValid(QScriptContext *context, QScriptEngine *engine);
  2309. QScriptValue QTime_minute(QScriptContext *context, QScriptEngine *engine);
  2310. QScriptValue QTime_msec(QScriptContext *context, QScriptEngine *engine);
  2311. QScriptValue QTime_msecsTo(QScriptContext *context, QScriptEngine *engine);
  2312. QScriptValue QTime_restart(QScriptContext *context, QScriptEngine *engine);
  2313. QScriptValue QTime_second(QScriptContext *context, QScriptEngine *engine);
  2314. QScriptValue QTime_secsTo(QScriptContext *context, QScriptEngine *engine);
  2315. QScriptValue QTime_setHMS(QScriptContext *context, QScriptEngine *engine);
  2316. QScriptValue QTime_start(QScriptContext *context, QScriptEngine *engine);
  2317. QScriptValue QTime_toString(QScriptContext *context, QScriptEngine *engine);
  2318. QScriptValue QTime_currentTime(QScriptContext *context, QScriptEngine *engine);
  2319. QScriptValue QTime_fromString(QScriptContext *context, QScriptEngine *engine);
  2320. QScriptValue QTime_valueOf(QScriptContext *context, QScriptEngine *engine);
  2321. void setQTimeProperties(QScriptValue value, QScriptEngine *engine);
  2322. @ We must tell the script engine about the constructor. This is not done in
  2323. quite the same way as is done for |QObject| derived types.
  2324. @<Set up the scripting engine@>=
  2325. constructor = engine->newFunction(constructQTime);
  2326. engine->globalObject().setProperty("QTime", constructor);
  2327. @ The constructor has a couple interesting twists. The first is the ability to
  2328. accept a variable number of integer arguments. The other is that |QTime| is not
  2329. derived from |QObject|. The lack of |break| statements in the |switch| is
  2330. intended.
  2331. @<Functions for scripting@>=
  2332. QScriptValue constructQTime(QScriptContext *context,
  2333. QScriptEngine *engine)
  2334. {
  2335. QScriptValue object;
  2336. if(context->argumentCount() == 0 ||
  2337. (context->argumentCount() >= 2 && context->argumentCount() <= 4))@/
  2338. {
  2339. int arg1 = 0;
  2340. int arg2 = 0;
  2341. int arg3 = 0;
  2342. int arg4 = 0;
  2343. switch(context->argumentCount())
  2344. {@t\1@>@/
  2345. case 4:@/
  2346. arg4 = argument<int>(3, context);
  2347. case 3:@/
  2348. arg3 = argument<int>(2, context);
  2349. case 2:@/
  2350. arg2 = argument<int>(1, context);
  2351. arg1 = argument<int>(0, context);
  2352. default:@/
  2353. break;@t\2@>@/
  2354. }
  2355. if(context->argumentCount())
  2356. {
  2357. object = engine->toScriptValue<QTime>(QTime(arg1, arg2, arg3,
  2358. arg4));
  2359. }
  2360. else
  2361. {
  2362. object = engine->toScriptValue<QTime>(QTime());
  2363. }
  2364. setQTimeProperties(object, engine);
  2365. }
  2366. else
  2367. {
  2368. context->throwError("Incorrect number of arguments passed to "@|
  2369. "QTime::QTime(). This method takes zero, two, "@|
  2370. "three, or four integer arguments.");
  2371. }
  2372. return object;
  2373. }
  2374. @ In order to use the various |QTime| methods, we must add wrapper functions as
  2375. properties of newly created script objects. The last two of these should really
  2376. be callable without starting from an existing |QTime|.
  2377. @<Functions for scripting@>=
  2378. void setQTimeProperties(QScriptValue value, QScriptEngine *engine)
  2379. {
  2380. value.setProperty("addMSecs", engine->newFunction(QTime_addMSecs));
  2381. value.setProperty("addSecs", engine->newFunction(QTime_addSecs));
  2382. value.setProperty("elapsed", engine->newFunction(QTime_elapsed));
  2383. value.setProperty("hour", engine->newFunction(QTime_hour));
  2384. value.setProperty("isNull", engine->newFunction(QTime_isNull));
  2385. value.setProperty("isValid", engine->newFunction(QTime_isValid));
  2386. value.setProperty("minute", engine->newFunction(QTime_minute));
  2387. value.setProperty("msec", engine->newFunction(QTime_msec));
  2388. value.setProperty("msecsTo", engine->newFunction(QTime_msecsTo));
  2389. value.setProperty("restart", engine->newFunction(QTime_restart));
  2390. value.setProperty("second", engine->newFunction(QTime_second));
  2391. value.setProperty("secsTo", engine->newFunction(QTime_secsTo));
  2392. value.setProperty("setHMS", engine->newFunction(QTime_setHMS));
  2393. value.setProperty("start", engine->newFunction(QTime_start));
  2394. value.setProperty("toString", engine->newFunction(QTime_toString));
  2395. value.setProperty("currentTime", engine->newFunction(QTime_currentTime));
  2396. value.setProperty("fromString", engine->newFunction(QTime_fromString));
  2397. value.setProperty("valueOf", engine->newFunction(QTime_valueOf));
  2398. }
  2399. @ The |valueOf()| method exposes a numeric representation of the time
  2400. suitable for use in comparing two time values. With this it is possible to
  2401. take two |QTime| values in script code {\tt t1} and {\tt t2} and get the
  2402. expected results from {\tt t1 == t2}, {\tt t1 < t2}, {\tt t1 > t2} and
  2403. similar comparative operations.
  2404. @<Functions for scripting@>=
  2405. QScriptValue QTime_valueOf(QScriptContext *context, QScriptEngine *)
  2406. {
  2407. QTime self = getself<QTime>(context);
  2408. int retval = (self.hour() * 60 * 60 * 1000) + (self.minute() * 60 * 1000) +
  2409. (self.second() * 1000) + self.msec();
  2410. return QScriptValue(retval);
  2411. }
  2412. @ These functions are effectively wrapper functions around existing |QTime|
  2413. functionality with some error checking for the scripting engine.
  2414. The |addMSecs()| and |addSecs()| methods return a new |QTime| object.
  2415. @<Functions for scripting@>=
  2416. QScriptValue QTime_addMSecs(QScriptContext *context, QScriptEngine *engine)
  2417. {
  2418. QTime time;
  2419. QScriptValue retval;
  2420. if(context->argumentCount() == 1)
  2421. {
  2422. QTime self = getself<QTime>(context);
  2423. time = self.addMSecs(argument<int>(0, context));
  2424. retval = engine->toScriptValue<QTime>(time);
  2425. setQTimeProperties(retval, engine);
  2426. }
  2427. else
  2428. {
  2429. context->throwError("Incorrect number of arguments passed to "@|
  2430. "QTime::addMSecs(). This method takes one "@|
  2431. "integer as an argument.");
  2432. }
  2433. return retval;
  2434. }
  2435. QScriptValue QTime_addSecs(QScriptContext *context, QScriptEngine *engine)
  2436. {
  2437. QTime time;
  2438. QScriptValue retval;
  2439. if(context->argumentCount() == 1)
  2440. {
  2441. QTime self = getself<QTime>(context);
  2442. time = self.addSecs(argument<int>(0, context));
  2443. retval = engine->toScriptValue<QTime>(time);
  2444. setQTimeProperties(retval, engine);
  2445. }
  2446. else
  2447. {
  2448. context->throwError("Incorrect number of arguments passed to "@|
  2449. "QTime::addSecs(). This method takes one "@|
  2450. "integer as an argument.");
  2451. }
  2452. return retval;
  2453. }
  2454. @ The |elapsed()| method returns an integer value.
  2455. @<Functions for scripting@>=
  2456. QScriptValue QTime_elapsed(QScriptContext *context, QScriptEngine *engine)
  2457. {
  2458. QScriptValue retval;
  2459. if(context->argumentCount() == 0)
  2460. {
  2461. QTime self = getself<QTime>(context);
  2462. retval = QScriptValue(engine, self.elapsed());
  2463. }
  2464. else
  2465. {
  2466. context->throwError("Incorrect number of arguments passed to "@|
  2467. "QTime::elapsed(). This method takes no "@|
  2468. "arguments.");
  2469. }
  2470. return retval;
  2471. }
  2472. @ The |hour()|, |minute()|, |second()| and |msec()| methods return an integer
  2473. with various parts of the time. The |hour()| method is typical of these methods.
  2474. @<Functions for scripting@>=
  2475. QScriptValue QTime_hour(QScriptContext *context, QScriptEngine *engine)
  2476. {
  2477. QScriptValue retval;
  2478. if(context->argumentCount() == 0)
  2479. {
  2480. QTime self = getself<QTime>(context);
  2481. retval = QScriptValue(engine, self.hour());
  2482. }
  2483. else
  2484. {
  2485. context->throwError("Incorrect number of arguments passed to "@|
  2486. "QTime::hour(). This method takes no "@|
  2487. "arguments.");
  2488. }
  2489. return retval;
  2490. }
  2491. @ The |minute()|, |second()|, and |msec()| methods are implemented similarly.
  2492. @<Functions for scripting@>=
  2493. QScriptValue QTime_minute(QScriptContext *context, QScriptEngine *engine)
  2494. {
  2495. QScriptValue retval;
  2496. if(context->argumentCount() == 0)
  2497. {
  2498. QTime self = getself<QTime>(context);
  2499. retval = QScriptValue(engine, self.minute());
  2500. }
  2501. else
  2502. {
  2503. context->throwError("Incorrect number of arguments passed to "@|
  2504. "QTime::minute(). This method takes no "@|
  2505. "arguments.");
  2506. }
  2507. return retval;
  2508. }
  2509. QScriptValue QTime_second(QScriptContext *context, QScriptEngine *engine)
  2510. {
  2511. QScriptValue retval;
  2512. if(context->argumentCount() == 0)
  2513. {
  2514. QTime self = getself<QTime>(context);
  2515. retval = QScriptValue(engine, self.second());
  2516. }
  2517. else
  2518. {
  2519. context->throwError("Incorrect number of arguments passed to "@|
  2520. "QTime::second(). This method takes no "@|
  2521. "arguments.");
  2522. }
  2523. return retval;
  2524. }
  2525. QScriptValue QTime_msec(QScriptContext *context, QScriptEngine *engine)
  2526. {
  2527. QScriptValue retval;
  2528. if(context->argumentCount() == 0)
  2529. {
  2530. QTime self = getself<QTime>(context);
  2531. retval = QScriptValue(engine, self.msec());
  2532. }
  2533. else
  2534. {
  2535. context->throwError("Incorrect number of arguments passed to "@|
  2536. "QTime::msec(). This method takes no "@|
  2537. "arguments.");
  2538. }
  2539. return retval;
  2540. }
  2541. @ The |isNull()| and |isValid()| methods return a boolean value. A |QTime| is
  2542. considered null if it was created with a constructor with no arguments. It is
  2543. considered invalid if it is null or if part of the time is out of range.
  2544. @<Functions for scripting@>=
  2545. QScriptValue QTime_isNull(QScriptContext *context, QScriptEngine *engine)
  2546. {
  2547. QScriptValue retval;
  2548. if(context->argumentCount() == 0)
  2549. {
  2550. QTime self = getself<QTime>(context);
  2551. retval = QScriptValue(engine, self.isNull());
  2552. }
  2553. else
  2554. {
  2555. context->throwError("Incorrect number of arguments passed to "@|
  2556. "QTime::isNull(). This method takes no "@|
  2557. "arguments.");
  2558. }
  2559. return retval;
  2560. }
  2561. QScriptValue QTime_isValid(QScriptContext *context, QScriptEngine *engine)
  2562. {
  2563. QScriptValue retval;
  2564. if(context->argumentCount() == 0)
  2565. {
  2566. QTime self = getself<QTime>(context);
  2567. retval = QScriptValue(engine, self.isValid());
  2568. }
  2569. else
  2570. {
  2571. context->throwError("Incorrect number of arguments passed to "@|
  2572. "QTime::isValid(). This method takes no "@|
  2573. "arguments.");
  2574. }
  2575. return retval;
  2576. }
  2577. @ The |secsTo()| and |msecsTo()| methods return an integer value indicating the
  2578. number of seconds or milliseconds until a |QTime| argument.
  2579. @<Functions for scripting@>=
  2580. QScriptValue QTime_msecsTo(QScriptContext *context, QScriptEngine *engine)
  2581. {
  2582. QScriptValue retval;
  2583. if(context->argumentCount() == 1)
  2584. {
  2585. QTime self = getself<QTime>(context);
  2586. QTime arg = argument<QVariant>(0, context).toTime();
  2587. retval = QScriptValue(engine, self.msecsTo(arg));
  2588. }
  2589. else
  2590. {
  2591. context->throwError("Incorrect number of arguments passed to "@|
  2592. "QTime::msecsTo(). This method takes one QTime.");
  2593. }
  2594. return retval;
  2595. }
  2596. QScriptValue QTime_secsTo(QScriptContext *context, QScriptEngine *engine)
  2597. {
  2598. QScriptValue retval;
  2599. if(context->argumentCount() == 1)
  2600. {
  2601. QTime self = getself<QTime>(context);
  2602. QTime arg = argument<QVariant>(0, context).toTime();
  2603. retval = QScriptValue(engine, self.secsTo(arg));
  2604. }
  2605. else
  2606. {
  2607. context->throwError("Incorrect number of arguments passed to "@|
  2608. "QTime::secsTo(). This method takes one QTime.");
  2609. }
  2610. return retval;
  2611. }
  2612. @ The |start()| and |restart()| methods each set the value of the |QTime()| to
  2613. the current time. The |restart()| method additionally returns the same value as
  2614. the |elapsed()| method.
  2615. @<Functions for scripting@>=
  2616. QScriptValue QTime_restart(QScriptContext *context, QScriptEngine *engine)
  2617. {
  2618. QScriptValue retval;
  2619. if(context->argumentCount() == 0)
  2620. {
  2621. QTime self = getself<QTime>(context);
  2622. retval = QScriptValue(engine, self.restart());
  2623. }
  2624. else
  2625. {
  2626. context->throwError("Incorrect number of arguments passed to "@|
  2627. "QTime::restart(). This method takes no "@|
  2628. "arguments.");
  2629. }
  2630. return retval;
  2631. }
  2632. QScriptValue QTime_start(QScriptContext *context, QScriptEngine *)
  2633. {
  2634. if(context->argumentCount() == 0)
  2635. {
  2636. QTime self = getself<QTime>(context);
  2637. self.start();
  2638. }
  2639. else
  2640. {
  2641. context->throwError("Incorrect number of arguments passed to "@|
  2642. "QTime::start(). This method takes no arguments.");
  2643. }
  2644. return QScriptValue();
  2645. }
  2646. @ The slightly inappropriately named |setHMS()| method changes the current value
  2647. of the time and returns a boolean to indicate if the new time value is valid.
  2648. @<Functions for scripting@>=
  2649. QScriptValue QTime_setHMS(QScriptContext *context, QScriptEngine *engine)
  2650. {
  2651. QScriptValue retval;
  2652. if(context->argumentCount() == 3 || context->argumentCount() == 4)
  2653. {
  2654. QTime self = getself<QTime>(context);
  2655. int arg1 = 0;
  2656. int arg2 = 0;
  2657. int arg3 = 0;
  2658. int arg4 = 0;
  2659. switch(context->argumentCount())@/
  2660. {@t\1@>@/
  2661. case 4:@/
  2662. arg4 = argument<int>(3, context);
  2663. case 3:@/
  2664. arg3 = argument<int>(2, context);
  2665. arg2 = argument<int>(1, context);
  2666. arg1 = argument<int>(0, context);
  2667. default:@/
  2668. break;@t\2@>@/
  2669. }
  2670. retval = QScriptValue(engine, self.setHMS(arg1, arg2, arg3, arg4));
  2671. }
  2672. else
  2673. {
  2674. context->throwError("Incorrect number of arguments passed to "@|
  2675. "QTime::setHMS(). This method takes three or "@|
  2676. "four integer arguments.");
  2677. }
  2678. return retval;
  2679. }
  2680. @ The |toString()| method returns a string representation of the time. See the
  2681. Qt documentation for instructions on creating a valid format string.
  2682. @<Functions for scripting@>=
  2683. QScriptValue QTime_toString(QScriptContext *context, QScriptEngine *engine)
  2684. {
  2685. QScriptValue retval;
  2686. if(context->argumentCount() == 1)
  2687. {
  2688. QTime self = getself<QTime>(context);
  2689. retval = QScriptValue(engine, self.toString(argument<QString>(0, context)));
  2690. }
  2691. else
  2692. {
  2693. context->throwError("Incorrect number of arguments passed to "@|
  2694. "QTime::toString(). This method takes one QString "@|
  2695. "as an argument.");
  2696. }
  2697. return retval;
  2698. }
  2699. @ The |currentTime()| and |fromString()| methods return a new |QTime| object.
  2700. These methods make no reference to the any other existing |QTime|.
  2701. @<Functions for scripting@>=
  2702. QScriptValue QTime_currentTime(QScriptContext *, QScriptEngine *engine)
  2703. {
  2704. QScriptValue object;
  2705. object = engine->toScriptValue<QTime>(QTime::currentTime());
  2706. setQTimeProperties(object, engine);
  2707. return object;
  2708. }
  2709. QScriptValue QTime_fromString(QScriptContext *context, QScriptEngine *engine)
  2710. {
  2711. QScriptValue object;
  2712. if(context->argumentCount() == 2)
  2713. {
  2714. QString time = argument<QString>(0, context);
  2715. QString format = argument<QString>(1, context);
  2716. object = engine->toScriptValue<QTime>(QTime::fromString(time, format));
  2717. setQTimeProperties(object, engine);
  2718. }
  2719. else
  2720. {
  2721. context->throwError("Incorrect number of arguments passed to "@|
  2722. "QTime::fromString(). This method takes two "@|
  2723. "string arguments.");
  2724. }
  2725. return object;
  2726. }
  2727. @* Scripting Item View Classes.
  2728. \noindent |QAbstractScrollArea| is a |QFrame| that serves as the base class for
  2729. classes such as |QGraphicsView| and |QAbstractItemView|. Objects from this class
  2730. are not created directly.
  2731. @<Function prototypes for scripting@>=
  2732. void setQAbstractScrollAreaProperties(QScriptValue value,
  2733. QScriptEngine *engine);
  2734. @ The implementation of this is simple.
  2735. @<Functions for scripting@>=
  2736. void setQAbstractScrollAreaProperties(QScriptValue value, QScriptEngine *engine)
  2737. {
  2738. setQFrameProperties(value, engine);
  2739. }
  2740. @ This class is used by the |QAbstractItemView| class. This is another class
  2741. that we do not need a script constructor for.
  2742. @<Function prototypes for scripting@>=
  2743. void setQAbstractItemViewProperties(QScriptValue value, QScriptEngine *engine);
  2744. @ This function has another simple implementation.
  2745. @<Functions for scripting@>=
  2746. void setQAbstractItemViewProperties(QScriptValue value, QScriptEngine *engine)
  2747. {
  2748. setQAbstractScrollAreaProperties(value, engine);
  2749. }
  2750. @ The |QGraphicsView| and |QTableView| classes form the base of \pn{} classes.
  2751. @<Function prototypes for scripting@>=
  2752. void setQGraphicsViewProperties(QScriptValue value, QScriptEngine *engine);
  2753. void setQTableViewProperties(QScriptValue value, QScriptEngine *engine);
  2754. @ Again, the implementations are boring.
  2755. @<Functions for scripting@>=
  2756. void setQGraphicsViewProperties(QScriptValue value, QScriptEngine *engine)
  2757. {
  2758. setQAbstractScrollAreaProperties(value, engine);
  2759. }
  2760. void setQTableViewProperties(QScriptValue value, QScriptEngine *engine)
  2761. {
  2762. setQAbstractItemViewProperties(value, engine);
  2763. }
  2764. @* Scripting Button Classes.
  2765. \noindent \pn{} provides an |AnnotationButton| class which is a special kind of
  2766. |QPushButton| which in turn comes from |QAbstractButton|. While
  2767. |AnnotationButton| can be used in exactly the same way as a |QPushButton|, if
  2768. an annotation is not needed, there is little reason not to use the base class.
  2769. @<Function prototypes for scripting@>=
  2770. void setQAbstractButtonProperties(QScriptValue value, QScriptEngine *engine);
  2771. void setQPushButtonProperties(QScriptValue value, QScriptEngine *engine);
  2772. QScriptValue constructQPushButton(QScriptContext *context,
  2773. QScriptEngine *engine);
  2774. @ The constructor for |QPushButton| should be passed to the scripting engine.
  2775. @<Set up the scripting engine@>=
  2776. constructor = engine->newFunction(constructQPushButton);
  2777. value = engine->newQMetaObject(&QPushButton::staticMetaObject, constructor);
  2778. engine->globalObject().setProperty("QPushButton", value);
  2779. @ The implementation should seem familiar.
  2780. @<Functions for scripting@>=
  2781. QScriptValue constructQPushButton(QScriptContext *, QScriptEngine *engine)
  2782. {
  2783. QScriptValue object = engine->newQObject(new QPushButton());
  2784. setQPushButtonProperties(object, engine);
  2785. return object;
  2786. }
  2787. void setQPushButtonProperties(QScriptValue value, QScriptEngine *engine)
  2788. {
  2789. setQAbstractButtonProperties(value, engine);
  2790. }
  2791. void setQAbstractButtonProperties(QScriptValue value, QScriptEngine *engine)
  2792. {
  2793. setQWidgetProperties(value, engine);
  2794. }
  2795. @* Scripting QSqlQuery.
  2796. \noindent With this class exposed to the host environment, it becomes possible
  2797. for script code to execute SQL queries and evaluate the result.
  2798. Rather than use |QSqlQuery| directly, however, we use a proxy \nfnote{Erich
  2799. Gamma, Richard Helm, Raph Johnson, and John
  2800. Vlissides,\par\indent\underbar{Design Patterns: elements of reusable
  2801. object-oriented software} (1995) pp. 207--217} class. This class obtains its own
  2802. database connection and handles properly closing and removing these connections
  2803. when the query object is destroyed.
  2804. @<Class declarations@>=
  2805. class SqlQueryConnection : public QSqlQuery@/
  2806. {
  2807. public:@/
  2808. SqlQueryConnection(const QString &query = QString());
  2809. ~SqlQueryConnection();
  2810. QSqlQuery* operator->();
  2811. private:@/
  2812. QString connection;
  2813. QSqlQuery *q;
  2814. };
  2815. @ The constructor can be somewhat simplified from the four forms of |QSqlQuery|.
  2816. We are not interested in creating an object from a |QSqlResult| or from another
  2817. |QSqlQuery|. The database connection is managed by the class itself so the
  2818. constructor only needs an optional string containing a query. This is used to
  2819. initialize a real |QSqlQuery| object.
  2820. @<SqlQueryConnection implementation@>=
  2821. SqlQueryConnection::SqlQueryConnection(const QString &query)
  2822. {
  2823. QSqlDatabase database = AppInstance->database();
  2824. database.open();
  2825. q = new QSqlQuery(query, database);
  2826. connection = database.connectionName();
  2827. }
  2828. @ The destructor handles removing the |QSqlQuery| and the database connection
  2829. associated with it. The extra brackets introduce a new scope for the
  2830. |QSqlDatabase| so that it is out of scope when the connection is removed.
  2831. @<SqlQueryConnection implementation@>=
  2832. SqlQueryConnection::~SqlQueryConnection()
  2833. {
  2834. delete q;
  2835. {
  2836. QSqlDatabase database = QSqlDatabase::database(connection);
  2837. database.close();
  2838. }
  2839. QSqlDatabase::removeDatabase(connection);
  2840. }
  2841. @ For all other functionality, we simply forward the request to our |QSqlQuery|
  2842. object.
  2843. @<SqlQueryConnection implementation@>=
  2844. QSqlQuery* SqlQueryConnection::operator->()
  2845. {
  2846. return q;
  2847. }
  2848. @ In order to use this new class in the host environment, a number of functions
  2849. are needed.
  2850. @<Function prototypes for scripting@>=
  2851. void setQSqlQueryProperties(QScriptValue value, QScriptEngine *engine);
  2852. QScriptValue constructQSqlQuery(QScriptContext *context, QScriptEngine *engine);
  2853. QScriptValue QSqlQuery_bind(QScriptContext *context, QScriptEngine *engine);
  2854. QScriptValue QSqlQuery_bindDeviceData(QScriptContext *context,
  2855. QScriptEngine *engine);
  2856. QScriptValue QSqlQuery_bindFileData(QScriptContext *context,
  2857. QScriptEngine *engine);
  2858. QScriptValue QSqlQuery_exec(QScriptContext *context,
  2859. QScriptEngine *engine);
  2860. QScriptValue QSqlQuery_executedQuery(QScriptContext *context,
  2861. QScriptEngine *engine);
  2862. QScriptValue QSqlQuery_invalidate(QScriptContext *context, QScriptEngine *engine);
  2863. QScriptValue QSqlQuery_next(QScriptContext *context, QScriptEngine *engine);
  2864. QScriptValue QSqlQuery_prepare(QScriptContext *context, QScriptEngine *engine);
  2865. QScriptValue QSqlQuery_value(QScriptContext *context, QScriptEngine *engine);
  2866. @ For conceptual convenience we simply pretend that we are working with a real
  2867. |QSqlQuery| object.
  2868. @<Set up the scripting engine@>=
  2869. constructor = engine->newFunction(constructQSqlQuery);
  2870. engine->globalObject().setProperty("QSqlQuery", constructor);
  2871. @ With connection creation no longer needed in the constructor, all that is
  2872. needed is object creation and applying the appropriate properties to the script
  2873. value.
  2874. @<Functions for scripting@>=
  2875. QScriptValue constructQSqlQuery(QScriptContext *, QScriptEngine *engine)
  2876. {
  2877. QScriptValue object =
  2878. engine->toScriptValue<void *>(new SqlQueryConnection());
  2879. setQSqlQueryProperties(object, engine);
  2880. return object;
  2881. }
  2882. @ As this class does not derive from |QObject|, we must wrap all of the methods
  2883. we might want to use.
  2884. @<Functions for scripting@>=
  2885. void setQSqlQueryProperties(QScriptValue value, QScriptEngine *engine)
  2886. {
  2887. value.setProperty("bind", engine->newFunction(QSqlQuery_bind));
  2888. value.setProperty("bindFileData",
  2889. engine->newFunction(QSqlQuery_bindFileData));
  2890. value.setProperty("bindDeviceData",
  2891. engine->newFunction(QSqlQuery_bindDeviceData));
  2892. value.setProperty("exec", engine->newFunction(QSqlQuery_exec));
  2893. value.setProperty("executedQuery", engine->newFunction(QSqlQuery_executedQuery));
  2894. value.setProperty("invalidate", engine->newFunction(QSqlQuery_invalidate));
  2895. value.setProperty("next", engine->newFunction(QSqlQuery_next));
  2896. value.setProperty("prepare", engine->newFunction(QSqlQuery_prepare));
  2897. value.setProperty("value", engine->newFunction(QSqlQuery_value));
  2898. }
  2899. @ Most of these properties are wrappers around existing |QSqlQuery| functions.
  2900. @<Functions for scripting@>=
  2901. QScriptValue QSqlQuery_exec(QScriptContext *context, QScriptEngine *engine)
  2902. {
  2903. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2904. QScriptValue retval;
  2905. if(context->argumentCount() == 1)
  2906. {
  2907. retval = QScriptValue(engine,
  2908. query->exec(argument<QString>(0, context)));
  2909. }
  2910. else
  2911. {
  2912. retval = QScriptValue(engine, query->exec());
  2913. }
  2914. if(query->lastError().isValid())
  2915. {
  2916. qDebug() << query->lastQuery();
  2917. qDebug() << query->lastError().text();
  2918. }
  2919. return retval;
  2920. }
  2921. QScriptValue QSqlQuery_executedQuery(QScriptContext *context, QScriptEngine *)
  2922. {
  2923. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2924. return QScriptValue(query->lastQuery());
  2925. }
  2926. QScriptValue QSqlQuery_next(QScriptContext *context, QScriptEngine *engine)
  2927. {
  2928. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2929. return QScriptValue(engine, query->next());
  2930. }
  2931. QScriptValue QSqlQuery_value(QScriptContext *context, QScriptEngine *engine)
  2932. {
  2933. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2934. return QScriptValue(engine,
  2935. query->value(argument<int>(0, context)).toString());
  2936. }
  2937. @ For prepared queries, we support binding variables available to the script,
  2938. data available in a named file, or data from any open |QIODevice|.
  2939. @<Functions for scripting@>=
  2940. QScriptValue QSqlQuery_prepare(QScriptContext *context, QScriptEngine *engine)
  2941. {
  2942. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2943. return QScriptValue(engine, query->prepare(argument<QString>(0, context)));
  2944. }
  2945. QScriptValue QSqlQuery_bind(QScriptContext *context, QScriptEngine *)
  2946. {
  2947. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2948. query->bindValue(argument<QString>(0, context),
  2949. argument<QVariant>(1, context));
  2950. return QScriptValue();
  2951. }
  2952. QScriptValue QSqlQuery_bindFileData(QScriptContext *context,
  2953. QScriptEngine *)
  2954. {
  2955. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2956. QString placeholder = argument<QString>(0, context);
  2957. QString filename = argument<QString>(1, context);
  2958. QFile file(filename);
  2959. QByteArray data;
  2960. if(file.open(QIODevice::ReadOnly))
  2961. {
  2962. data = file.readAll();
  2963. file.close();
  2964. }
  2965. query->bindValue(placeholder, data);
  2966. return QScriptValue();
  2967. }
  2968. QScriptValue QSqlQuery_bindDeviceData(QScriptContext *context,
  2969. QScriptEngine *)
  2970. {
  2971. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2972. QString placeholder = argument<QString>(0, context);
  2973. QIODevice *device = argument<QIODevice *>(1, context);
  2974. device->reset();
  2975. QByteArray data;
  2976. data = device->readAll();
  2977. query->bindValue(placeholder, data);
  2978. return QScriptValue();
  2979. }
  2980. @ To avoid leaking database connections, we add the |invalidate()| property
  2981. which destroys our object. The object on which this method is called must not be
  2982. used after calling this method. In script code this will typically be used as in
  2983. the following example:
  2984. {\tt query = query.invalidate();}
  2985. @<Functions for scripting@>=
  2986. QScriptValue QSqlQuery_invalidate(QScriptContext *context, QScriptEngine *)
  2987. {
  2988. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  2989. delete query;
  2990. return QScriptValue::UndefinedValue;
  2991. }
  2992. @* Other scripting functions.
  2993. \noindent There are a few functions that are exposed to the scripting engine
  2994. that are not associated with any class. Two functions are used for extracting
  2995. information from file names. Another is used to construct array values from SQL
  2996. array values. There is also a function for setting the default font for the
  2997. application or some part of the application.
  2998. @<Function prototypes for scripting@>=
  2999. QScriptValue baseName(QScriptContext *context, QScriptEngine *engine);
  3000. QScriptValue dir(QScriptContext *context, QScriptEngine *engine);
  3001. QScriptValue sqlToArray(QScriptContext *context, QScriptEngine *engine);
  3002. QScriptValue setFont(QScriptContext *context, QScriptEngine *engine);
  3003. QScriptValue annotationFromRecord(QScriptContext *context,
  3004. QScriptEngine *engine);
  3005. QScriptValue setTabOrder(QScriptContext *context, QScriptEngine *engine);
  3006. @ These functions are passed to the scripting engine.
  3007. @<Set up the scripting engine@>=
  3008. engine->globalObject().setProperty("baseName", engine->newFunction(baseName));
  3009. engine->globalObject().setProperty("dir", engine->newFunction(dir));
  3010. engine->globalObject().setProperty("sqlToArray",
  3011. engine->newFunction(sqlToArray));
  3012. engine->globalObject().setProperty("setFont", engine->newFunction(setFont));
  3013. engine->globalObject().setProperty("annotationFromRecord",
  3014. engine->newFunction(annotationFromRecord));
  3015. engine->globalObject().setProperty("setTabOrder", engine->newFunction(setTabOrder));
  3016. @ These functions are not part of an object. They expect a string specifying
  3017. the path to a file and return a string with either the name of the file without
  3018. the path and extension or the path of the directory containing the file.
  3019. @<Functions for scripting@>=
  3020. QScriptValue baseName(QScriptContext *context, QScriptEngine *engine)
  3021. {
  3022. QFileInfo info(argument<QString>(0, context));
  3023. QScriptValue retval(engine, info.baseName());
  3024. return retval;
  3025. }
  3026. QScriptValue dir(QScriptContext *context, QScriptEngine *engine)
  3027. {
  3028. QFileInfo info(argument<QString>(0, context));
  3029. QDir dir = info.dir();
  3030. QScriptValue retval(engine, dir.path());
  3031. return retval;
  3032. }
  3033. @ This function takes a string representing a SQL array and returns an array
  3034. value.
  3035. @<Functions for scripting@>=
  3036. QScriptValue sqlToArray(QScriptContext *context, QScriptEngine *engine)
  3037. {
  3038. QString source = argument<QString>(0, context);
  3039. source.remove(0, 1);
  3040. source.chop(1);
  3041. QStringList elements = source.split(",");
  3042. QString element;
  3043. QScriptValue dest = engine->newArray(elements.size());
  3044. int i = 0;
  3045. foreach(element, elements)
  3046. {
  3047. if(element.startsWith("\"") && element.endsWith("\""))
  3048. {
  3049. element.chop(1);
  3050. element = element.remove(0, 1);
  3051. }
  3052. dest.setProperty(i, QScriptValue(engine, element));
  3053. i++;
  3054. }
  3055. return dest;
  3056. }
  3057. @ This function can be used to set the default font for the application or on
  3058. a per-class hierarchy basis.
  3059. @<Functions for scripting@>=
  3060. QScriptValue setFont(QScriptContext *context, QScriptEngine *)
  3061. {
  3062. QString font = argument<QString>(0, context);
  3063. QString classname;
  3064. if(context->argumentCount() > 1)
  3065. {
  3066. classname = argument<QString>(1, context);
  3067. QApplication::setFont(QFont(font), classname.toLatin1().constData());
  3068. }
  3069. else
  3070. {
  3071. QApplication::setFont(QFont(font));
  3072. }
  3073. return QScriptValue();
  3074. }
  3075. @ This function was briefly used prior to adding support for |QXmlQuery| in the
  3076. host environment. The function is now depreciated and should not be used.
  3077. @<Functions for scripting@>=
  3078. QScriptValue annotationFromRecord(QScriptContext *context, QScriptEngine *)
  3079. {
  3080. SqlQueryConnection query;
  3081. QString q = "SELECT file FROM files WHERE id = :file";
  3082. query.prepare(q);
  3083. query.bindValue(":file", argument<int>(0, context));
  3084. query.exec();
  3085. query.next();
  3086. QByteArray array = query.value(0).toByteArray();
  3087. QBuffer buffer(&array);
  3088. buffer.open(QIODevice::ReadOnly);
  3089. QXmlQuery xquery;
  3090. xquery.bindVariable("profile", &buffer);
  3091. QString xq;
  3092. xq = "for $b in doc($profile) //tuple where exists($b/annotation) return $b";
  3093. xquery.setQuery(xq);
  3094. QString result;
  3095. xquery.evaluateTo(&result);
  3096. return QScriptValue(result);
  3097. }
  3098. @ This function can be used to change the tab order for controls in Typica.
  3099. Changes to the example configuration in \pn{} 1.4 made the default handling
  3100. of tab controls in the logging window unacceptable.
  3101. @<Functions for scripting@>=
  3102. QScriptValue setTabOrder(QScriptContext *context, QScriptEngine *)
  3103. {
  3104. QWidget::setTabOrder(argument<QWidget*>(0, context),
  3105. argument<QWidget*>(1, context));
  3106. return QScriptValue();
  3107. }
  3108. @** Application Configuration.
  3109. \noindent While \pn{} is intended as a data logging application, the diversity
  3110. of equipment and supporting technology precludes the option of providing a
  3111. single interface for common tasks. It is important that the application can be
  3112. configured to work with different roasting equipment, databases, and the like.
  3113. To accomplish this, \pn{} utilizes an XML description of the desired application
  3114. configuration and provides an ECMA-262 host environment which allows application
  3115. dataflow to be configured.
  3116. The scripting environment provides access to elements of the XML file and also
  3117. allows access to most of the application classes. A selection of classes
  3118. provided by Qt is also available. See the section on The Scripting Engine for
  3119. more details.
  3120. \danger While the code is the ultimate documentation of what is possible with
  3121. this interface, additional documentation should be provided to document the
  3122. meaning of supported elements and the objects available through the scripting
  3123. engine.\endanger
  3124. The application configuration is loaded when the program is started.
  3125. Starting with version 1.4, we check for a command line option with the path to
  3126. the configuration file and load that instead of prompting for the information
  3127. if possible.
  3128. @<Load the application configuration@>=
  3129. QStringList arguments = QCoreApplication::arguments();
  3130. int position = arguments.indexOf("-c");
  3131. QString filename = QString();
  3132. if(position != -1)
  3133. {
  3134. if(arguments.size() >= position + 1)
  3135. {
  3136. filename = arguments.at(position + 1);
  3137. }
  3138. }
  3139. if(filename.isEmpty())
  3140. {
  3141. filename = QFileDialog::getOpenFileName(NULL, "Open Configuration File",
  3142. settings.value("config", "").toString());
  3143. }
  3144. QDir directory;
  3145. if(!filename.isEmpty())
  3146. {
  3147. QFile file(filename);
  3148. QFileInfo info(filename);
  3149. directory = info.dir();
  3150. settings.setValue("config", directory.path());
  3151. if(file.open(QIODevice::ReadOnly))
  3152. {
  3153. app.configuration()->setContent(&file, true);
  3154. }
  3155. }
  3156. @<Substitute included fragments@>@;
  3157. @ The {\tt <application>} element can contain an arbitrary number of
  3158. {\tt <include>} elements. These elements should not appear in the DOM. Instead,
  3159. the element should be replaced by the content of the specified document.
  3160. @<Substitute included fragments@>=
  3161. QDomElement root = app.configuration()->documentElement();
  3162. QDomNodeList children = root.childNodes();
  3163. QString replacementDoc;
  3164. QDomDocument includedDoc;
  3165. QDomDocumentFragment fragment;
  3166. for(int i = 0; i < children.size(); i++)
  3167. {
  3168. QDomNode currentNode = children.at(i);
  3169. QDomElement currentElement;
  3170. if(currentNode.nodeName() == "include")
  3171. {
  3172. currentElement = currentNode.toElement();
  3173. if(currentElement.hasAttribute("src"))
  3174. {
  3175. replacementDoc = directory.path();
  3176. replacementDoc.append('/');
  3177. replacementDoc.append(currentElement.attribute("src"));
  3178. QFile doc(replacementDoc);
  3179. if(doc.open(QIODevice::ReadOnly))
  3180. {
  3181. includedDoc.setContent(&doc, true);
  3182. fragment = includedDoc.createDocumentFragment();
  3183. fragment.appendChild(includedDoc.documentElement());
  3184. root.replaceChild(fragment, currentNode);
  3185. doc.close();
  3186. }
  3187. }
  3188. }
  3189. }
  3190. @ Simply loading the configuration document does not display a user interface or
  3191. set up any objects that allow the program to do anything. To do this, a script
  3192. obtained from the configuration document is run. The root element of the
  3193. document should be {\tt <application>}. This element should have a number of
  3194. child elements including {\tt <window>} elements which describe the various
  3195. windows that can be opened in the application and {\tt <program>} elements
  3196. containing script code. These {\tt <program>} elements can occur in a number of
  3197. different contexts including within {\tt <window>} elements which would indicate
  3198. that such scripts should be evaluated when the window being described is
  3199. created. After the configuration document is loaded, all {\tt <program>}
  3200. elements that are direct children of the {\tt <application>} element are
  3201. concatenated and the script is run.
  3202. Before the script is run and user interface elements are drawn, we also check
  3203. for {\tt <style>} elements which can be used to set up a stylesheet for the
  3204. application.
  3205. @<Find and evaluate starting script@>=
  3206. QString styleText;
  3207. QString programText;
  3208. QDomElement currentElement;
  3209. for(int i = 0; i < children.size(); i++)
  3210. {
  3211. QDomNode currentNode = children.at(i);
  3212. if(currentNode.nodeName() == "style")
  3213. {
  3214. currentElement = currentNode.toElement();
  3215. styleText.append(currentElement.text());
  3216. }
  3217. else if(currentNode.nodeName() == "program")
  3218. {
  3219. currentElement = currentNode.toElement();
  3220. programText.append(currentElement.text());
  3221. }
  3222. }
  3223. app.setStyleSheet(styleText);
  3224. QScriptValue result = engine->evaluate(programText);
  3225. @<Report scripting errors@>
  3226. @ When a script is evaluated, there is a chance that there will be some error in
  3227. the execution of that script. If this occurs, we want to report that.
  3228. @<Report scripting errors@>=
  3229. if(engine->hasUncaughtException())
  3230. {
  3231. int line = engine->uncaughtExceptionLineNumber();
  3232. qDebug() << "Uncaught excpetion at line " << line << " : " <<
  3233. result.toString();
  3234. QString trace;
  3235. foreach(trace, engine->uncaughtExceptionBacktrace())
  3236. {
  3237. qDebug() << trace;
  3238. }
  3239. }
  3240. @* Creating a window.
  3241. \noindent When a configuration document is loaded, none of the {\tt <window>}
  3242. elements are interpreted or used to create a graphical user interface. Instead,
  3243. any {\tt <program>} elements that are immediate children of the
  3244. {\tt <application>} element are interpreted. In order to convert a
  3245. {\tt <window>} element into a window displayed on screen, the script in the
  3246. {\tt <program>} elements must call a function to display a specified window.
  3247. \danger This design works, but it's not particularly good design. It was written
  3248. under severe time constraints and should be redesigned or at least cleaned up
  3249. and reorganized.\endanger
  3250. @<Function prototypes for scripting@>=
  3251. QScriptValue createWindow(QScriptContext *context, QScriptEngine *engine);
  3252. void addLayoutToWidget(QDomElement element, QStack<QWidget*> *widgetStack,
  3253. QStack<QLayout*> *layoutStack);
  3254. void addLayoutToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3255. QStack<QLayout *> *layoutStack);
  3256. void addSplitterToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3257. QStack<QLayout *> *layoutStack);
  3258. void addSplitterToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  3259. QStack<QLayout *> *layoutStack);
  3260. void populateGridLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3261. QStack<QLayout *> *layoutStack);
  3262. void populateBoxLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3263. QStack<QLayout *> *layoutStack);
  3264. void populateSplitter(QDomElement element, QStack<QWidget *> *widgetStack,@|
  3265. QStack<QLayout *> *layoutStack);
  3266. void populateWidget(QDomElement element, QStack<QWidget *> *widgetStack,@|
  3267. QStack<QLayout *> *layoutStack);
  3268. void populateStackedLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3269. QStack<QLayout *> *layoutStack);
  3270. void addTemperatureDisplayToSplitter(QDomElement element,@|
  3271. QStack<QWidget *> *widgetStack,
  3272. QStack<QLayout *> *layoutStack);
  3273. void addTemperatureDisplayToLayout(QDomElement element,@|
  3274. QStack<QWidget *> *widgetStack,
  3275. QStack<QLayout *> *layoutStack);
  3276. void addTimerDisplayToSplitter(QDomElement element,@|
  3277. QStack<QWidget *> *widgetStack,
  3278. QStack<QLayout *> *layoutStack);
  3279. void addTimerDisplayToLayout(QDomElement element,@|
  3280. QStack<QWidget *> *widgetStack,
  3281. QStack<QLayout *> *layoutStack);
  3282. void addDecorationToSplitter(QDomElement element,@|
  3283. QStack<QWidget *> *widgetStack,
  3284. QStack<QLayout *> *layoutStack);
  3285. void addDecorationToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3286. QStack<QLayout *> *layoutStack);
  3287. void addWidgetToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  3288. QStack<QLayout *> *layoutStack);
  3289. void addButtonToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3290. QStack<QLayout *> *layoutStack);
  3291. void addZoomLogToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  3292. QStack<QLayout *> *layoutStack);
  3293. void addGraphToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  3294. QStack<QLayout *> *layoutStack);
  3295. void addSqlDropToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3296. QStack<QLayout *> *layoutStack);
  3297. void addSaltToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  3298. QStack<QLayout *> *layoutStack);
  3299. void addLineToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  3300. QStack<QLayout *> *layoutStack);
  3301. void addTextToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  3302. QStack<QLayout *> *layoutStack);
  3303. void addSqlQueryViewToLayout(QDomElement element,
  3304. QStack<QWidget *> *widgetStack,
  3305. QStack<QLayout *> *layoutStack);
  3306. void addCalendarToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3307. QStack<QLayout *> *layoutStack);
  3308. void addSpinBoxToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3309. QStack<QLayout *> *layoutStack);
  3310. @ The function for creating the window must be made available to the scripting
  3311. engine.
  3312. @<Set up the scripting engine@>=
  3313. engine->globalObject().setProperty("createWindow",
  3314. engine->newFunction(createWindow));
  3315. @ This function must examine the configuration document in search of the
  3316. appropriate window element, parse the contents of that element, and create a
  3317. multitude of objects, all of which must be passed to the scripting engine.
  3318. @<Functions for scripting@>=
  3319. QScriptValue createWindow(QScriptContext *context, QScriptEngine *engine)@/
  3320. {
  3321. QString targetID = argument<QString>(0, context);
  3322. QDomNode element;
  3323. QScriptValue object;
  3324. @<Find the window element@>@;
  3325. if(!element.isNull())
  3326. {
  3327. @<Display the window@>@;
  3328. }
  3329. return object;
  3330. }
  3331. @ First we must locate the {\tt <window>} element. The most sensible way to do
  3332. this would require that each {\tt <window>} element has an ID attribute and
  3333. search the DOM tree for that ID. Unfortunately, as of this writing,
  3334. |QDomDocument::elementByID()| always returns a null element, so that won't work.
  3335. Instead, we search the tree for all {\tt <window>} elements and then examine
  3336. the resulting list to find the element with the appropriate ID.
  3337. @<Find the window element@>=
  3338. QDomNodeList windows =
  3339. AppInstance->configuration()->documentElement().elementsByTagName("window");
  3340. QDomNode nullNode;
  3341. int i = 0;
  3342. element = nullNode;
  3343. while(i < windows.count())
  3344. {
  3345. element = windows.at(i);
  3346. QDomNamedNodeMap attributes = element.attributes();
  3347. if(attributes.contains("id"))
  3348. {
  3349. if(attributes.namedItem("id").toAttr().value() == targetID)
  3350. {
  3351. break;
  3352. }
  3353. }
  3354. element = nullNode;
  3355. i++;
  3356. }
  3357. @ In order to display a window, we start by creating a new |ScriptQMainWindow|
  3358. and set the central widget of that window to a new |QWidget|. After this, we see
  3359. if the window element has any children and proceed to populate the window.
  3360. When creating child elements, care must be taken that all objects are descended
  3361. from the window. If an object is descended from the window and has an object
  3362. name, it will be possible for script code to recover the created object.
  3363. As of version 1.4, the window itself is given the value of its {\tt id}
  3364. attribute as an object name to facilitate automatic window geometry management.
  3365. @<Display the window@>=
  3366. ScriptQMainWindow *window = new ScriptQMainWindow;
  3367. window->setObjectName(targetID);
  3368. object = engine->newQObject(window);
  3369. setQMainWindowProperties(object, engine);
  3370. QWidget *central = new(QWidget);
  3371. central->setParent(window);
  3372. central->setObjectName("centralWidget");
  3373. window->setCentralWidget(central);
  3374. if(element.hasChildNodes())
  3375. {
  3376. @<Process window children@>@;
  3377. }
  3378. @<Insert help menu@>@;
  3379. window->show();
  3380. @ Three element types make sense as top level children of a {\tt <window>}
  3381. element. An element representing a layout element can be used to apply that
  3382. layout to the central widget. An element representing a menu can be used to add
  3383. a menu to the window. A {\tt <program>} element can be used to specify a script
  3384. to be run after the window has been assembled.
  3385. \danger As the window comes with a blank central widget, elements representing
  3386. a widget to be used as the central widget of the window cannot be used directly
  3387. here. If only one widget is needed in the window, there is a need to create a
  3388. layout element and place that widget in the layout. Also note that there is not
  3389. enough error checking in the following code. Provide invalid input at your
  3390. peril.\endanger
  3391. Program fragments pulled from the window description are executed with the
  3392. newly created window available as {\tt this}. When such a fragment is run, the
  3393. entire description of the window will have already been evaluated and any
  3394. necessary objects created. Obtaining a child object of the window can be done
  3395. by calling |findChildObject()|.
  3396. @<Process window children@>=
  3397. QStack<QWidget*> widgetStack;
  3398. QStack<QLayout*> layoutStack;
  3399. QString windowScript;
  3400. widgetStack.push(central);
  3401. QDomNodeList windowChildren = element.childNodes();
  3402. int i = 0;
  3403. while(i < windowChildren.count())
  3404. {
  3405. QDomNode current;
  3406. QDomElement element;
  3407. current = windowChildren.at(i);
  3408. if(current.isElement())
  3409. {
  3410. element = current.toElement();
  3411. if(element.tagName() == "program")
  3412. {
  3413. windowScript.append(element.text());
  3414. }
  3415. else if(element.tagName() == "layout")
  3416. {
  3417. addLayoutToWidget(element, &widgetStack, &layoutStack);
  3418. }
  3419. else if(element.tagName() == "menu")
  3420. {
  3421. @<Process menus@>@;
  3422. }
  3423. }
  3424. i++;
  3425. }
  3426. QScriptValue oldThis = context->thisObject();
  3427. context->setThisObject(object);
  3428. QScriptValue result = engine->evaluate(windowScript);
  3429. @<Report scripting errors@>@;
  3430. context->setThisObject(oldThis);
  3431. @ Elements representing menus may provide a number of child elements
  3432. representing the items in that menu. The XML portion of the configuration will
  3433. not provide any information on what these menu items do. The contents of the
  3434. {\tt <program>} element for the window will need to request the |QAction|
  3435. objects and connect a signal from that object to the desired functionality.
  3436. One special consideration is the Reports menu. This menu will populate itself
  3437. according to its own logic and will have a {\tt type} property of
  3438. {\tt "reports"} and a {\tt src} property indicating the directory where reports
  3439. can be found.
  3440. @<Process menus@>=
  3441. QMenuBar *bar = window->menuBar();
  3442. bar->setParent(window);
  3443. bar->setObjectName("menuBar");
  3444. if(element.hasAttribute("name"))
  3445. {
  3446. QMenu *menu = bar->addMenu(element.attribute("name"));
  3447. menu->setParent(bar);
  3448. if(element.hasAttribute("type"))
  3449. {
  3450. if(element.attribute("type") == "reports")
  3451. {
  3452. if(element.hasAttribute("src"))
  3453. {
  3454. @<Populate reports menu@>@;
  3455. }
  3456. }
  3457. }
  3458. if(element.hasChildNodes())
  3459. {
  3460. @<Process menu items@>@;
  3461. }
  3462. }
  3463. @ To add items to a menu, we check for {\tt <item>} elements under the
  3464. {\tt <menu>} element and create a |QAction| for each item.
  3465. @<Process menu items@>=
  3466. QDomNodeList menuItems = element.childNodes();
  3467. int j = 0;
  3468. while(j < menuItems.count())
  3469. {
  3470. QDomNode item = menuItems.at(j);
  3471. if(item.isElement())
  3472. {
  3473. QDomElement itemElement = item.toElement();
  3474. if(itemElement.tagName() == "item")
  3475. {
  3476. QAction *itemAction = new QAction(itemElement.text(), menu);
  3477. if(itemElement.hasAttribute("id"))
  3478. {
  3479. itemAction->setObjectName(itemElement.attribute("id"));
  3480. }
  3481. if(itemElement.hasAttribute("shortcut"))
  3482. {
  3483. itemAction->setShortcut(itemElement.attribute("shortcut"));
  3484. }
  3485. menu->addAction(itemAction);
  3486. }
  3487. else if(itemElement.tagName() == "separator")
  3488. {
  3489. menu->addSeparator();
  3490. }
  3491. }
  3492. j++;
  3493. }
  3494. @i helpmenu.w
  3495. @ A layout can contain a number of different elements including a variety of
  3496. widget types and other layouts. This function is responsible for applying any
  3497. layout class to the widget currently being populated and processing children of
  3498. the {\tt <layout>} element to populate that layout. External stacks are used to
  3499. keep track of which widgets and layouts are currently being populated. The
  3500. {\tt type} attribute is used to determine what sort of layout should be created.
  3501. Currently, {\tt horizontal}, {\tt vertical}, {\tt grid}, and {\tt stack} types
  3502. are supported. The first two resolve to |QBoxLayout| layouts, {\tt grid}
  3503. resolves to a |QGridLayout|, and {\tt stack} resolves to a |QStackedLayout|.
  3504. @<Functions for scripting@>=
  3505. void addLayoutToWidget(QDomElement element, QStack<QWidget*> *widgetStack,
  3506. QStack<QLayout*> *layoutStack)
  3507. {
  3508. if(element.hasAttribute("type"))
  3509. {
  3510. @<Create and populate layout@>@;
  3511. QWidget *widget = widgetStack->top();
  3512. if(layout)
  3513. {
  3514. widget->setLayout(layout);
  3515. }
  3516. layoutStack->pop();
  3517. }
  3518. }
  3519. @ As there are multiple places where a {\tt <layout>} element is parsed with
  3520. slightly different semantics, the code for creating and populating the layout is
  3521. broken out so that code written to support additional layout types only needs to
  3522. be written once.
  3523. @<Create and populate layout@>=
  3524. QLayout *layout;
  3525. QString layoutType = element.attribute("type");
  3526. if(layoutType == "horizontal")
  3527. {
  3528. layout = new QHBoxLayout;
  3529. layoutStack->push(layout);
  3530. populateBoxLayout(element, widgetStack, layoutStack);
  3531. }
  3532. else if(layoutType == "vertical")
  3533. {
  3534. layout = new QVBoxLayout;
  3535. layoutStack->push(layout);
  3536. populateBoxLayout(element, widgetStack, layoutStack);
  3537. }
  3538. else if(layoutType == "grid")
  3539. {
  3540. layout = new QGridLayout;
  3541. layoutStack->push(layout);
  3542. populateGridLayout(element, widgetStack, layoutStack);
  3543. }
  3544. else if(layoutType == "stack")
  3545. {
  3546. layout = new QStackedLayout;
  3547. layoutStack->push(layout);
  3548. populateStackedLayout(element, widgetStack, layoutStack);
  3549. }
  3550. if(element.hasAttribute("id"))
  3551. {
  3552. layout->setObjectName(element.attribute("id"));
  3553. }
  3554. @ Stacked layouts are a bit different from the other types. A stacked layout has
  3555. an arbitrary number of {\tt <page>} children which are just a |QWidget| which
  3556. can have the same child elements as {\tt <widget>} elements elsewhere. Only the
  3557. first page will be visible initially, however it is possible to use script code
  3558. to set the currently visible page provided that an ID is set for the layout.
  3559. @<Functions for scripting@>=
  3560. void populateStackedLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3561. QStack<QLayout *> *layoutStack)
  3562. {
  3563. QDomNodeList children = element.childNodes();
  3564. QStackedLayout *layout = qobject_cast<QStackedLayout *>(layoutStack->top());
  3565. for(int i = 0; i < children.count(); i++)
  3566. {
  3567. QDomNode current;
  3568. QDomElement currentElement;
  3569. current = children.at(i);
  3570. if(current.isElement())
  3571. {
  3572. currentElement = current.toElement();
  3573. if(currentElement.tagName() == "page")
  3574. {
  3575. QWidget *widget = new QWidget;
  3576. layout->addWidget(widget);
  3577. widgetStack->push(widget);
  3578. populateWidget(currentElement, widgetStack, layoutStack);
  3579. widgetStack->pop();
  3580. }
  3581. }
  3582. }
  3583. }
  3584. @ Using a grid layout is a bit different from using a box layout. Child elements
  3585. with various attributes are required to take full advantage of this layout type.
  3586. All direct children of a grid layout element should be {\tt <row>} elements
  3587. which may have optional {\tt height} and {\tt stretch} attributes which apply to
  3588. that row.
  3589. @<Functions for scripting@>=
  3590. void populateGridLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3591. QStack<QLayout *> *layoutStack)
  3592. {
  3593. QDomNodeList children = element.childNodes();
  3594. int row = -1;
  3595. QGridLayout *layout = qobject_cast<QGridLayout *>(layoutStack->top());
  3596. for(int i = 0; i < children.count(); i++)
  3597. {
  3598. QDomNode current;
  3599. QDomElement currentElement;
  3600. current = children.at(i);
  3601. if(current.isElement())
  3602. {
  3603. currentElement = current.toElement();
  3604. if(currentElement.tagName() == "row")
  3605. {
  3606. row++;
  3607. if(currentElement.hasAttribute("height"))
  3608. {
  3609. layout->setRowMinimumHeight(row,
  3610. currentElement.attribute("height").toInt());
  3611. }
  3612. if(currentElement.hasAttribute("stretch"))
  3613. {
  3614. layout->setRowStretch(row,
  3615. currentElement.attribute("stretch").toInt());
  3616. }
  3617. @<Populate grid layout row@>@;
  3618. }
  3619. }
  3620. }
  3621. }
  3622. @ Each {\tt <row>} may have arbitrarily many {\tt <column>} children. A row with
  3623. nothing in it or that is entirely populated by spanning cells from previous rows
  3624. might have no children.
  3625. The {\tt <column>} element supports several optional attributes. The
  3626. {\tt column} attribute can be used to specify which column the element refers
  3627. to. Sibling {\tt <column>} elements will refer to columns farther right unless
  3628. a lower column number is specified. This does mean that it is possible to
  3629. specify the same column more than once, however actually doing so is not
  3630. recommended. The {\tt width} attribute specifies the minimum width of the
  3631. column. If multiple cells in a column specify this attribute, the last one takes
  3632. priority. Similarly, the {\tt stretch} attribute specifies the column stretch.
  3633. The {\tt rowspan} and {\tt colspan} attributes can be used for cells that span
  3634. more than one row or column. A value of |-1| can be used to have the cell span
  3635. to the last row or column in the layout.
  3636. Once the attributes of the cell are known, a |QHBoxLayout| is added to the
  3637. layout at the appropriate location in the grid and it is this layout which is
  3638. further populated by child elements. Anything that can be placed under a
  3639. {\tt <layout>} element with {\tt "horizontal"} or {\tt "vertical"} {\tt type}
  3640. attribute can be a child of a {\tt <column>} element in this context.
  3641. @<Populate grid layout row@>=
  3642. int column = -1;
  3643. QDomNodeList rowChildren = currentElement.childNodes();
  3644. for(int j = 0; j < rowChildren.count(); j++)
  3645. {
  3646. QDomNode columnNode;
  3647. QDomElement columnElement;
  3648. columnNode = rowChildren.at(j);
  3649. if(columnNode.isElement())
  3650. {
  3651. columnElement = columnNode.toElement();
  3652. if(columnElement.tagName() == "column")
  3653. {
  3654. column++;
  3655. if(columnElement.hasAttribute("column"))
  3656. {
  3657. column = columnElement.attribute("column").toInt();
  3658. }
  3659. if(columnElement.hasAttribute("width"))
  3660. {
  3661. layout->setColumnMinimumWidth(column,
  3662. columnElement.attribute("width").toInt());
  3663. }
  3664. if(columnElement.hasAttribute("stretch"))
  3665. {
  3666. layout->setColumnStretch(column,
  3667. columnElement.attribute("stretch").toInt());
  3668. }
  3669. int hspan = 1;
  3670. int vspan = 1;
  3671. if(columnElement.hasAttribute("rowspan"))
  3672. {
  3673. vspan = columnElement.attribute("rowspan").toInt();
  3674. }
  3675. if(columnElement.hasAttribute("colspan"))
  3676. {
  3677. hspan = columnElement.attribute("colspan").toInt();
  3678. }
  3679. QHBoxLayout *cell = new QHBoxLayout;
  3680. layout->addLayout(cell, row, column, vspan, hspan);
  3681. layoutStack->push(cell);
  3682. populateBoxLayout(columnElement, widgetStack, layoutStack);
  3683. layoutStack->pop();
  3684. }
  3685. }
  3686. }
  3687. @ Box layouts are populated by checking for child elements representing
  3688. supported widget types and layouts and adding these to the current layout.
  3689. @<Functions for scripting@>=
  3690. void populateBoxLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3691. QStack<QLayout *> *layoutStack)
  3692. {
  3693. QDomNodeList children = element.childNodes();
  3694. for(int i = 0; i < children.count(); i++)
  3695. {
  3696. QDomNode current;
  3697. QDomElement currentElement;
  3698. current = children.at(i);
  3699. if(current.isElement())
  3700. {
  3701. currentElement = current.toElement();
  3702. if(currentElement.tagName() == "button")
  3703. {
  3704. addButtonToLayout(currentElement, widgetStack, layoutStack);
  3705. }
  3706. else if(currentElement.tagName() == "calendar")
  3707. {
  3708. addCalendarToLayout(currentElement, widgetStack, layoutStack);
  3709. }
  3710. else if(currentElement.tagName() == "decoration")
  3711. {
  3712. addDecorationToLayout(currentElement, widgetStack,
  3713. layoutStack);
  3714. }
  3715. else if(currentElement.tagName() == "layout")
  3716. {
  3717. addLayoutToLayout(currentElement, widgetStack, layoutStack);
  3718. }
  3719. else if(currentElement.tagName() == "splitter")
  3720. {
  3721. addSplitterToLayout(currentElement, widgetStack, layoutStack);
  3722. }
  3723. else if(currentElement.tagName() == "label")
  3724. {
  3725. QBoxLayout *layout =
  3726. qobject_cast<QBoxLayout *>(layoutStack->top());
  3727. QLabel *label = new QLabel(currentElement.text());
  3728. layout->addWidget(label);
  3729. }
  3730. else if(currentElement.tagName() == "lcdtemperature")
  3731. {
  3732. addTemperatureDisplayToLayout(currentElement, widgetStack,
  3733. layoutStack);
  3734. }
  3735. else if(currentElement.tagName() == "lcdtimer")
  3736. {
  3737. addTimerDisplayToLayout(currentElement, widgetStack,
  3738. layoutStack);
  3739. }
  3740. else if(currentElement.tagName() == "line")
  3741. {
  3742. addLineToLayout(currentElement, widgetStack, layoutStack);
  3743. }
  3744. else if(currentElement.tagName() == "report")
  3745. {
  3746. addReportToLayout(currentElement, widgetStack, layoutStack);
  3747. }
  3748. else if(currentElement.tagName() == "sqldrop")
  3749. {
  3750. addSqlDropToLayout(currentElement, widgetStack, layoutStack);
  3751. }
  3752. else if(currentElement.tagName() == "sqltablearray")
  3753. {
  3754. addSaltToLayout(currentElement, widgetStack, layoutStack);
  3755. }
  3756. else if(currentElement.tagName() == "sqlview")
  3757. {
  3758. addSqlQueryViewToLayout(currentElement, widgetStack,
  3759. layoutStack);
  3760. }
  3761. else if(currentElement.tagName() == "textarea")
  3762. {
  3763. addTextToLayout(currentElement, widgetStack, layoutStack);
  3764. }
  3765. else if(currentElement.tagName() == "spinbox")
  3766. {
  3767. addSpinBoxToLayout(currentElement, widgetStack, layoutStack);
  3768. }
  3769. else if(currentElement.tagName() == "formarray")
  3770. {
  3771. addFormArrayToLayout(currentElement, widgetStack, layoutStack);
  3772. }
  3773. else if(currentElement.tagName() =="hscale")
  3774. {
  3775. addScaleControlToLayout(currentElement, widgetStack,
  3776. layoutStack);
  3777. }
  3778. else if(currentElement.tagName() == "vscale")
  3779. {
  3780. addIntensityControlToLayout(currentElement, widgetStack,
  3781. layoutStack);
  3782. }
  3783. else if(currentElement.tagName() == "webview")
  3784. {
  3785. addWebViewToLayout(currentElement, widgetStack, layoutStack);
  3786. }
  3787. else if(currentElement.tagName() == "stretch")
  3788. {
  3789. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  3790. layout->addStretch();
  3791. }
  3792. }
  3793. }
  3794. }
  3795. @ Box layouts support adding additional layouts to the layout. The form of the
  3796. function is very similar to |addLayoutToWidget()|.
  3797. @<Functions for scripting@>=
  3798. void addLayoutToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3799. QStack<QLayout *> *layoutStack)
  3800. {
  3801. QLayout *targetLayout = layoutStack->pop();
  3802. QBoxLayout *boxLayout = qobject_cast<QBoxLayout *>(targetLayout);
  3803. if(element.hasAttribute("type"))
  3804. {
  3805. @<Create and populate layout@>@;
  3806. boxLayout->addLayout(layout);
  3807. layoutStack->pop();
  3808. }
  3809. layoutStack->push(targetLayout);
  3810. }
  3811. @ A splitter is similar to a layout in that it manages the size and position of
  3812. one or more widgets, however it is not a layout and therefore needs to be
  3813. handled separately.
  3814. @<Functions for scripting@>=
  3815. void addSplitterToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3816. QStack<QLayout *> *layoutStack)
  3817. {
  3818. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  3819. QSplitter *splitter = new(QSplitter);
  3820. layout->addWidget(splitter);
  3821. @<Set up splitter@>@;
  3822. }
  3823. @ As there are multiple places where a splitter element must be examined, the
  3824. common code is set aside.
  3825. @<Set up splitter@>=
  3826. QString orientation = element.attribute("type");
  3827. if(orientation == "horizontal")
  3828. {
  3829. splitter->setOrientation(Qt::Horizontal);
  3830. }
  3831. else if(orientation == "vertical")
  3832. {
  3833. splitter->setOrientation(Qt::Vertical);
  3834. }
  3835. QString id = element.attribute("id");
  3836. if(!id.isEmpty())
  3837. {
  3838. splitter->setObjectName(id);
  3839. }
  3840. if(element.hasChildNodes())
  3841. {
  3842. widgetStack->push(splitter);
  3843. populateSplitter(element, widgetStack, layoutStack);
  3844. widgetStack->pop();
  3845. }
  3846. @ When populating a splitter, it is important to note that only widgets can be
  3847. added. If a layout is needed, this can be handled by adding a |QWidget| and
  3848. applying the layout to that widget.
  3849. @<Functions for scripting@>=
  3850. void populateSplitter(QDomElement element, QStack<QWidget *> *widgetStack,@|
  3851. QStack<QLayout *> *layoutStack)
  3852. {
  3853. QDomNodeList children = element.childNodes();
  3854. for(int i = 0; i < children.count(); i++)
  3855. {
  3856. QDomNode current;
  3857. QDomElement currentElement;
  3858. current = children.at(i);
  3859. if(current.isElement())
  3860. {
  3861. currentElement = current.toElement();
  3862. if(currentElement.tagName() == "decoration")
  3863. {
  3864. addDecorationToSplitter(currentElement, widgetStack,
  3865. layoutStack);
  3866. }
  3867. else if(currentElement.tagName() == "graph")
  3868. {
  3869. addGraphToSplitter(currentElement, widgetStack, layoutStack);
  3870. }
  3871. else if(currentElement.tagName() == "splitter")
  3872. {
  3873. addSplitterToSplitter(currentElement, widgetStack, layoutStack);
  3874. }
  3875. else if(currentElement.tagName() == "lcdtemperature")
  3876. {
  3877. addTemperatureDisplayToSplitter(currentElement, widgetStack,
  3878. layoutStack);
  3879. }
  3880. else if(currentElement.tagName() == "lcdtimer")
  3881. {
  3882. addTimerDisplayToSplitter(currentElement, widgetStack,
  3883. layoutStack);
  3884. }
  3885. else if(currentElement.tagName() == "measurementtable")
  3886. {
  3887. addZoomLogToSplitter(currentElement, widgetStack, layoutStack);
  3888. }
  3889. else if(currentElement.tagName() == "widget")
  3890. {
  3891. addWidgetToSplitter(currentElement, widgetStack, layoutStack);
  3892. }
  3893. }
  3894. }
  3895. }
  3896. @ Adding a splitter to a splitter is similar to adding it to a layout.
  3897. @<Functions for scripting@>=
  3898. void addSplitterToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  3899. QStack<QLayout *> *layoutStack)
  3900. {
  3901. QSplitter *parent = qobject_cast<QSplitter *>(widgetStack->top());
  3902. QSplitter *splitter = new(QSplitter);
  3903. splitter->setParent(parent);
  3904. parent->addWidget(splitter);
  3905. @<Set up splitter@>@;
  3906. }
  3907. @ Temperature displays are useful to have in an application such as this. At
  3908. present, this code only supports the {\tt id} attribute. It may be useful in the
  3909. future to allow other attributes for changing default attributes of the
  3910. indicator rather than needing to pull the object from script code and set
  3911. changes there.
  3912. @<Functions for scripting@>=
  3913. void addTemperatureDisplayToSplitter(QDomElement element,@|
  3914. QStack<QWidget *> *widgetStack,
  3915. QStack<QLayout *> *)
  3916. {
  3917. TemperatureDisplay *display = new(TemperatureDisplay);
  3918. if(element.hasAttribute("id"))
  3919. {
  3920. display->setObjectName(element.attribute("id"));
  3921. }
  3922. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  3923. splitter->addWidget(display);
  3924. }
  3925. void addTemperatureDisplayToLayout(QDomElement element,@|
  3926. QStack<QWidget *> *,
  3927. QStack<QLayout *> *layoutStack)
  3928. {
  3929. TemperatureDisplay *display = new(TemperatureDisplay);
  3930. if(element.hasAttribute("id"))
  3931. {
  3932. display->setObjectName(element.attribute("id"));
  3933. }
  3934. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  3935. layout->addWidget(display);
  3936. }
  3937. @ Timer displays are similarly useful to have. The default format for a timer
  3938. display is {\tt hh:mm:ss}, but this can be changed through the {\tt format}
  3939. attribute of an {\tt <lcdtimer>} element.
  3940. @<Functions for scripting@>=
  3941. void addTimerDisplayToSplitter(QDomElement element,@|
  3942. QStack<QWidget *> *widgetStack,
  3943. QStack<QLayout *> *)
  3944. {
  3945. TimerDisplay *display = new(TimerDisplay);
  3946. if(element.hasAttribute("id"))
  3947. {
  3948. display->setObjectName(element.attribute("id"));
  3949. }
  3950. if(element.hasAttribute("format"))
  3951. {
  3952. display->setDisplayFormat(element.attribute("format"));
  3953. }
  3954. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  3955. splitter->addWidget(display);
  3956. }
  3957. void addTimerDisplayToLayout(QDomElement element,@|
  3958. QStack<QWidget *> *,
  3959. QStack<QLayout *> *layoutStack)
  3960. {
  3961. TimerDisplay *display = new(TimerDisplay);
  3962. if(element.hasAttribute("id"))
  3963. {
  3964. display->setObjectName(element.attribute("id"));
  3965. }
  3966. if(element.hasAttribute("format"))
  3967. {
  3968. display->setDisplayFormat(element.attribute("format"));
  3969. }
  3970. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  3971. layout->addWidget(display);
  3972. }
  3973. @ When multiple timer or temperature displays are required, it can be useful to
  3974. provide a label to indicate just what is being measured.
  3975. @<Functions for scripting@>=
  3976. void addDecorationToLayout(QDomElement element, QStack<QWidget *> *,@|
  3977. QStack<QLayout *> *layoutStack)
  3978. {
  3979. @<Set up decoration@>@;
  3980. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  3981. layout->addWidget(decoration);
  3982. }
  3983. void addDecorationToSplitter(QDomElement element,
  3984. QStack<QWidget *> *widgetStack,
  3985. QStack<QLayout *> *)
  3986. {
  3987. @<Set up decoration@>@;
  3988. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  3989. splitter->addWidget(decoration);
  3990. }
  3991. @ The decoration needs a label text, an orientation, and the widget to be
  3992. labeled.
  3993. @<Set up decoration@>=
  3994. QString labelText = element.attribute("name");
  3995. Qt::Orientations@, orientation = Qt::Horizontal;
  3996. if(element.hasAttribute("type"))
  3997. {
  3998. if(element.attribute("type") == "horizontal")
  3999. {
  4000. orientation = Qt::Horizontal;
  4001. }
  4002. else if(element.attribute("type") == "vertical")
  4003. {
  4004. orientation = Qt::Vertical;
  4005. }
  4006. }
  4007. @<Find widget to decorate@>@;
  4008. WidgetDecorator *decoration = new WidgetDecorator(theWidget, labelText,
  4009. orientation);
  4010. if(element.hasAttribute("id"))
  4011. {
  4012. decoration->setObjectName(element.attribute("id"));
  4013. }
  4014. @ The widget to decorate should be found as a child of the {\tt <decoration>}
  4015. element.
  4016. @<Find widget to decorate@>=
  4017. QWidget *theWidget = NULL;
  4018. QDomNodeList children = element.childNodes();
  4019. for(int i = 0; i < children.count(); i++)
  4020. {
  4021. QDomNode item = children.at(i);
  4022. if(item.isElement())
  4023. {
  4024. QDomElement itemElement = item.toElement();
  4025. if(itemElement.tagName() == "lcdtemperature")
  4026. {
  4027. TemperatureDisplay *display = new TemperatureDisplay;
  4028. if(itemElement.hasAttribute("id"))
  4029. {
  4030. display->setObjectName(itemElement.attribute("id"));
  4031. }
  4032. theWidget = display;
  4033. }
  4034. else if(itemElement.tagName() == "lcdtimer")
  4035. {
  4036. TimerDisplay *display = new TimerDisplay;
  4037. if(itemElement.hasAttribute("id"))
  4038. {
  4039. display->setObjectName(itemElement.attribute("id"));
  4040. }
  4041. if(itemElement.hasAttribute("format"))
  4042. {
  4043. display->setDisplayFormat(itemElement.attribute("format"));
  4044. }
  4045. theWidget = display;
  4046. }
  4047. }
  4048. }
  4049. @ As splitters cannot contain layouts directly, there is a need to allow
  4050. otherwise empty widgets to be included in a splitter for cases where a splitter
  4051. should manage several widgets together as a group. A row of annotation buttons
  4052. is an example of such a layout.
  4053. @<Functions for scripting@>=
  4054. void addWidgetToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4055. QStack<QLayout *> *layoutStack)
  4056. {
  4057. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4058. QWidget *widget = new QWidget;
  4059. if(element.hasAttribute("id"))
  4060. {
  4061. widget->setObjectName(element.attribute("id"));
  4062. }
  4063. splitter->addWidget(widget);
  4064. if(element.hasChildNodes())
  4065. {
  4066. widgetStack->push(widget);
  4067. populateWidget(element, widgetStack, layoutStack);
  4068. widgetStack->pop();
  4069. }
  4070. }
  4071. void populateWidget(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4072. QStack<QLayout *> *layoutStack)
  4073. {
  4074. QDomNodeList children = element.childNodes();
  4075. for(int i = 0; i < children.count(); i++)
  4076. {
  4077. QDomNode current;
  4078. QDomElement currentElement;
  4079. current = children.at(i);
  4080. if(current.isElement())
  4081. {
  4082. currentElement = current.toElement();
  4083. if(currentElement.tagName() == "layout")
  4084. {
  4085. addLayoutToWidget(currentElement, widgetStack, layoutStack);
  4086. }
  4087. }
  4088. }
  4089. }
  4090. @ There are two types of buttons that can be added to a layout. There are normal
  4091. push buttons and there are annotation buttons. Other button types may be added
  4092. in the future.
  4093. @<Functions for scripting@>=
  4094. void addButtonToLayout(QDomElement element, QStack<QWidget *> *,@|
  4095. QStack<QLayout *> *layoutStack)
  4096. {
  4097. QAbstractButton *button = NULL;
  4098. QString text = element.attribute("name");
  4099. if(element.hasAttribute("type"))
  4100. {
  4101. QString type = element.attribute("type");
  4102. if(type == "annotation")
  4103. {
  4104. AnnotationButton *abutton = new AnnotationButton(text);
  4105. if(element.hasAttribute("annotation"))
  4106. {
  4107. abutton->setAnnotation(element.attribute("annotation"));
  4108. }
  4109. if(element.hasAttribute("series"))
  4110. {
  4111. abutton->setTemperatureColumn(element.attribute("series").
  4112. toInt());
  4113. }
  4114. if(element.hasAttribute("column"))
  4115. {
  4116. abutton->setAnnotationColumn(element.attribute("column").
  4117. toInt());
  4118. }
  4119. button = abutton;
  4120. }
  4121. else if(type == "check")
  4122. {
  4123. button = new QCheckBox(text);
  4124. }
  4125. else if(type == "push")
  4126. {
  4127. button = new QPushButton(text);
  4128. }
  4129. }
  4130. if(element.hasAttribute("id"))
  4131. {
  4132. button->setObjectName(element.attribute("id"));
  4133. }
  4134. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4135. layout->addWidget(button);
  4136. }
  4137. @ While annotation buttons are useful for many batch notes, a spin box is
  4138. sometimes a better input choice. There are several attributes that can be set on
  4139. a spin box. These include text to be included in the annotation before and after
  4140. the value of the spin box, the temperature and annotation columns, the range of
  4141. values available in the spin box, the precision of allowed values, and the
  4142. amount by which increment and decrement operations change the value.
  4143. @<Functions for scripting@>=
  4144. void addSpinBoxToLayout(QDomElement element, QStack<QWidget *> *,@|
  4145. QStack<QLayout *> *layoutStack)
  4146. {
  4147. AnnotationSpinBox *box = new AnnotationSpinBox("", "", NULL);
  4148. if(element.hasAttribute("pretext"))
  4149. {
  4150. box->setPretext(element.attribute("pretext"));
  4151. }
  4152. if(element.hasAttribute("posttext"))
  4153. {
  4154. box->setPosttext(element.attribute("posttext"));
  4155. }
  4156. if(element.hasAttribute("series"))
  4157. {
  4158. box->setTemperatureColumn(element.attribute("series").toInt());
  4159. }
  4160. if(element.hasAttribute("column"))
  4161. {
  4162. box->setAnnotationColumn(element.attribute("column").toInt());
  4163. }
  4164. if(element.hasAttribute("min"))
  4165. {
  4166. box->setMinimum(element.attribute("min").toDouble());
  4167. }
  4168. if(element.hasAttribute("max"))
  4169. {
  4170. box->setMaximum(element.attribute("max").toDouble());
  4171. }
  4172. if(element.hasAttribute("decimals"))
  4173. {
  4174. box->setDecimals(element.attribute("decimals").toInt());
  4175. }
  4176. if(element.hasAttribute("step"))
  4177. {
  4178. box->setSingleStep(element.attribute("step").toDouble());
  4179. }
  4180. if(element.hasAttribute("id"))
  4181. {
  4182. box->setObjectName(element.attribute("id"));
  4183. }
  4184. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4185. layout->addWidget(box);
  4186. }
  4187. @ Previously, in order to change a |ZoomLog| from the default set of columns,
  4188. script code would need to alter the column set. While this works fine on a Mac,
  4189. this did not work very well under Windows. For the current version, I would like
  4190. to remove the need to deal with table columns from the host environment. The
  4191. first step for this is allowing column descriptions in XML. After this, I'd like
  4192. to remove the default column set from the widget code and provide some better
  4193. functionality for dealing with additional data sets.
  4194. When creating the |ZoomLog| here, we check for {\tt <column>} child elements
  4195. which specify the names of the columns.
  4196. @<Functions for scripting@>=
  4197. void addZoomLogToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4198. QStack<QLayout *> *)
  4199. {
  4200. ZoomLog *widget = new ZoomLog;
  4201. if(!widget)
  4202. {
  4203. qDebug() << "Error constructing widget!";
  4204. }
  4205. if(element.hasAttribute("id"))
  4206. {
  4207. widget->setObjectName(element.attribute("id"));
  4208. }
  4209. if(element.hasChildNodes())
  4210. {
  4211. QDomNodeList children = element.childNodes();
  4212. int column = 0;
  4213. for(int i = 0; i < children.count(); i++)
  4214. {
  4215. QDomNode current;
  4216. QDomElement currentElement;
  4217. current = children.at(i);
  4218. if(current.isElement())
  4219. {
  4220. currentElement = current.toElement();
  4221. if(currentElement.tagName() == "column")
  4222. {
  4223. QString text = currentElement.text();
  4224. widget->setHeaderData(column, text);
  4225. column++;
  4226. }
  4227. }
  4228. }
  4229. }
  4230. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4231. if(splitter)
  4232. {
  4233. splitter->addWidget(widget);
  4234. }
  4235. else
  4236. {
  4237. qDebug() << "Splitter not found at top of widget stack!";
  4238. }
  4239. }
  4240. @ The last of the widgets needed to duplicate the window provided in previous
  4241. versions of \pn{} is the |GraphView|.
  4242. @<Functions for scripting@>=
  4243. void addGraphToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4244. QStack<QLayout *> *)
  4245. {
  4246. GraphView *view = new GraphView;
  4247. if(element.hasAttribute("id"))
  4248. {
  4249. view->setObjectName(element.attribute("id"));
  4250. }
  4251. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4252. splitter->addWidget(view);
  4253. }
  4254. @ When interacting with a database, it can be useful to provide a combo box
  4255. populated by the results of a database query. One way to do this is through a
  4256. |SqlComboBox| widget.
  4257. @<Functions for scripting@>=
  4258. void addSqlDropToLayout(QDomElement element, QStack<QWidget *> *,@|
  4259. QStack<QLayout *> *layoutStack)
  4260. {
  4261. SqlComboBox *box = new SqlComboBox();
  4262. if(element.hasAttribute("data"))
  4263. {
  4264. box->setDataColumn(element.attribute("data").toInt());
  4265. }
  4266. if(element.hasAttribute("display"))
  4267. {
  4268. box->setDisplayColumn(element.attribute("display").toInt());
  4269. }
  4270. if(element.hasAttribute("showdata"))
  4271. {
  4272. if(element.attribute("showdata") == "true")
  4273. {
  4274. box->showData(true);
  4275. }
  4276. }
  4277. if(element.hasAttribute("editable"))
  4278. {
  4279. if(element.attribute("editable") == "true")
  4280. {
  4281. box->setEditable(true);
  4282. }
  4283. }
  4284. if(element.hasChildNodes())
  4285. {
  4286. QDomNodeList children = element.childNodes();
  4287. for(int i = 0; i < children.count(); i++)
  4288. {
  4289. QDomNode current;
  4290. QDomElement currentElement;
  4291. current = children.at(i);
  4292. if(current.isElement())
  4293. {
  4294. currentElement = current.toElement();
  4295. if(currentElement.tagName() == "null")
  4296. {
  4297. box->addNullOption();
  4298. }
  4299. else if(currentElement.tagName() == "query")
  4300. {
  4301. box->addSqlOptions(currentElement.text());
  4302. }
  4303. }
  4304. }
  4305. }
  4306. if(element.hasAttribute("id"))
  4307. {
  4308. box->setObjectName(element.attribute("id"));
  4309. }
  4310. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4311. layout->addWidget(box);
  4312. }
  4313. @ The next database aware widget that can be useful to have in \pn{} is a
  4314. {\bf S}QL {\bf A}rray {\bf L}iteral {\bf T}able. As might be apparent from the
  4315. name, this is a table view with an associated model and delegates appropriate
  4316. for creating ordered arrays to pass into a database. Each column represents an
  4317. array of values. The most common use of this is in cases where it is important
  4318. to produce multiple arrays of the same size in which each element of one array
  4319. is related to the element in the same position of another array. For example,
  4320. when roasting coffee there are times when some may want to add more than one
  4321. coffee to the roaster at a time. In order to correctly track the green coffee
  4322. inventory and so that the roasting log may have an accurate record of what is
  4323. really happening, insertions on the roasting log provide two arrays, one
  4324. representing all of the coffees being added to the roaster, the other the amount
  4325. of each of these coffees. The database can then use a trigger function to
  4326. examine these arrays and produce the necessary entries in the use table which in
  4327. turn update the record containing the amount of each green coffee currently in
  4328. stock.
  4329. While a generic |QTableView| is used here, there is a need to add functionality
  4330. specific to using this table with a |SaltModel| when obtaining this widget from
  4331. the host environment. In order to accomodate this, we add a dynamic property to
  4332. the view to identify the type of table in the absense of a unique class name.
  4333. @<Functions for scripting@>=
  4334. void addSaltToLayout(QDomElement element, QStack<QWidget *> *,@|
  4335. QStack<QLayout *> *layoutStack)
  4336. {
  4337. QTableView *view = new QTableView;
  4338. view->setProperty("tabletype", QVariant(QString("SaltTable")));
  4339. SaltModel *model = new SaltModel(element.childNodes().count());
  4340. if(element.hasAttribute("id"))
  4341. {
  4342. view->setObjectName(element.attribute("id"));
  4343. }
  4344. if(element.hasChildNodes())
  4345. {
  4346. QDomNodeList children = element.childNodes();
  4347. int currentColumn = 0;
  4348. for(int i = 0; i < children.count(); i++)
  4349. {
  4350. QDomNode current;
  4351. QDomElement currentElement;
  4352. current = children.at(i);
  4353. if(current.isElement())
  4354. {
  4355. currentElement = current.toElement();
  4356. if(currentElement.tagName() == "column")
  4357. {
  4358. if(currentElement.hasAttribute("name"))
  4359. {
  4360. model->setHeaderData(currentColumn, Qt::Horizontal,
  4361. currentElement.attribute("name"));
  4362. }
  4363. if(currentElement.hasAttribute("delegate"))
  4364. {
  4365. @<Set column delegate from XML attribute@>@;
  4366. }
  4367. currentColumn++;
  4368. }
  4369. }
  4370. }
  4371. }
  4372. view->setModel(model);
  4373. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4374. layout->addWidget(view);
  4375. }
  4376. @ It is often desirable to restrict the allowed values in an entry to either a
  4377. set of specific values or to a particular type of value. Delegates can be set
  4378. on a column to enforce such restrictions.
  4379. @<Set column delegate from XML attribute@>=
  4380. if(currentElement.attribute("delegate") == "sql")
  4381. {
  4382. @<Assign column delegate from SQL@>@;
  4383. }
  4384. else if(currentElement.attribute("delegate") == "numeric")
  4385. {
  4386. @<Assign numeric column delegate@>@;
  4387. }
  4388. @ When using a |SaltModel|, there are times where the array values being
  4389. inserted are identification numbers representing some record that already exists
  4390. in the database. For example, the id number representing a green coffee in the
  4391. table of items. In such a case, it is beneficial to provide a delegate capable
  4392. of presenting a human readable list of choices.
  4393. @<Assign column delegate from SQL@>=
  4394. SqlComboBoxDelegate *delegate = new SqlComboBoxDelegate;
  4395. SqlComboBox *widget = new SqlComboBox();
  4396. if(currentElement.hasAttribute("null"))
  4397. {
  4398. if(currentElement.attribute("null") == "true")
  4399. {
  4400. widget->addNullOption();
  4401. }
  4402. }
  4403. if(currentElement.hasAttribute("showdata"))
  4404. {
  4405. if(currentElement.attribute("showdata") == "true")
  4406. {
  4407. widget->showData(true);
  4408. }
  4409. }
  4410. if(currentElement.hasAttribute("data"))
  4411. {
  4412. widget->setDataColumn(currentElement.attribute("data").toInt());
  4413. }
  4414. if(currentElement.hasAttribute("display"))
  4415. {
  4416. widget->setDisplayColumn(currentElement.attribute("display").toInt());
  4417. }
  4418. widget->addSqlOptions(currentElement.text());
  4419. delegate->setWidget(widget);
  4420. view->setItemDelegateForColumn(currentColumn, delegate);
  4421. @ Another common use is allowing numeric values. At present this only
  4422. restricts input to numbers, however it may be useful to provide other options
  4423. such as restricting the range of allowed values in the future.
  4424. @<Assign numeric column delegate@>=
  4425. NumericDelegate *delegate = new NumericDelegate;
  4426. view->setItemDelegateForColumn(currentColumn, delegate);
  4427. @ The |NumericDelegate| will only set the display value to a number, but it
  4428. will perform mathematical calculations that are entered into the editor as
  4429. well. This allows a person to type something like $13.26+5.06$ with the result
  4430. of the expression ($18.32$) appearing in the table.
  4431. @<Class declarations@>=
  4432. class NumericDelegate : public QItemDelegate@/
  4433. {
  4434. @[Q_OBJECT@]@;
  4435. public:@/
  4436. NumericDelegate(QObject *parent = NULL);
  4437. QWidget *createEditor(QWidget *parent,
  4438. const QStyleOptionViewItem &option,@|
  4439. const QModelIndex &index) const;
  4440. void setEditorData(QWidget *editor, const QModelIndex &index) const;
  4441. void setModelData(QWidget *editor, QAbstractItemModel *model,@|
  4442. const QModelIndex &index) const;
  4443. void updateEditorGeometry(QWidget *editor,
  4444. const QStyleOptionViewItem &option,@|
  4445. const QModelIndex &index) const;
  4446. };
  4447. @ There is nothing special about the constructor.
  4448. @<NumericDelegate implementation@>=
  4449. NumericDelegate::NumericDelegate(QObject *parent) :
  4450. QItemDelegate(parent)
  4451. {
  4452. /* Nothing needs to be done here. */
  4453. }
  4454. @ Two roles are used by this delegate. The edit role should contain whatever
  4455. text has been entered in the editor while the display role contain the numeric
  4456. result of any expression that has been entered. Our editor only requires the
  4457. first of these.
  4458. @<NumericDelegate implementation@>=
  4459. void NumericDelegate::setEditorData(QWidget *editor,
  4460. const QModelIndex &index) const
  4461. {
  4462. QString value = index.model()->data(index, Qt::EditRole).toString();
  4463. QLineEdit *line = static_cast<QLineEdit*>(editor);
  4464. line->setText(value);
  4465. }
  4466. @ When editing is finished, the expression text must be saved back to the
  4467. model and the expression should be evaluated to set the display role. We make
  4468. use of the existing scripting engine to evaluate the expression, but only
  4469. preserve the result in the display role if the result of that expression is
  4470. numeric.
  4471. @<NumericDelegate implementation@>=
  4472. void NumericDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
  4473. const QModelIndex &index) const
  4474. {
  4475. QLineEdit *line = static_cast<QLineEdit*>(editor);
  4476. model->setData(index, line->text(), Qt::EditRole);
  4477. QScriptEngine *engine = AppInstance->engine;
  4478. engine->pushContext();
  4479. QString script = QString("Number(%1)").arg(line->text());
  4480. QScriptValue result = engine->evaluate(line->text());
  4481. if(result.isNumber())
  4482. {
  4483. model->setData(index, result.toVariant(), Qt::DisplayRole);
  4484. }
  4485. else
  4486. {
  4487. model->setData(index, QVariant(), Qt::DisplayRole);
  4488. }
  4489. engine->popContext();
  4490. }
  4491. @ There is nothing special about the line edit used for this.
  4492. @<NumericDelegate implementation@>=
  4493. QWidget* NumericDelegate::createEditor(QWidget *parent,
  4494. const QStyleOptionViewItem &,
  4495. const QModelIndex &) const
  4496. {
  4497. return (new QLineEdit(parent));
  4498. }
  4499. @ To ensure that the editor is displayed appropriately, we must pass the
  4500. geometry data to our editor.
  4501. @<NumericDelegate implementation@>=
  4502. void NumericDelegate::updateEditorGeometry(QWidget *editor,
  4503. const QStyleOptionViewItem &option,
  4504. const QModelIndex &) const
  4505. {
  4506. editor->setGeometry(option.rect);
  4507. }
  4508. @ Line edits are useful when the user is expected to enter text without a
  4509. predetermined set of values.
  4510. Several attributes are supported on line edits. In addition to the usual
  4511. {\tt id} attribute, there is also a {\tt writable} attribute which, if
  4512. {\tt false}, can be used to create read only text areas which can only be edited
  4513. from script code. A {\tt validator} attribute allows entered text to be
  4514. restricted. This can take one of three values. If the value is {\tt "numeric"},
  4515. input is restricted to numeric values. If the value is {\tt "integer"}, input is
  4516. restricted to integer values. Finally, if the value is {\tt "expression"}, input
  4517. is restricted to text which matches a regular expression specified as the value
  4518. of the {\tt expression} attribute.
  4519. @<Functions for scripting@>=
  4520. void addLineToLayout(QDomElement element, QStack<QWidget *> *,@|
  4521. QStack<QLayout *> *layoutStack)
  4522. {
  4523. QLineEdit *widget = new QLineEdit(element.text());
  4524. if(element.hasAttribute("id"))
  4525. {
  4526. widget->setObjectName(element.attribute("id"));
  4527. }
  4528. if(element.hasAttribute("writable"))
  4529. {
  4530. if(element.attribute("writable") == "false")
  4531. {
  4532. widget->setReadOnly(true);
  4533. }
  4534. }
  4535. if(element.hasAttribute("validator"))
  4536. {
  4537. if(element.attribute("validator") == "numeric")
  4538. {
  4539. widget->setValidator(new QDoubleValidator(NULL));
  4540. }
  4541. else if(element.attribute("validator") == "integer")
  4542. {
  4543. widget->setValidator(new QIntValidator(NULL));
  4544. }
  4545. else if(element.attribute("validator") == "expression" &&
  4546. element.hasAttribute("expression"))
  4547. {
  4548. widget->setValidator(new QRegExpValidator(
  4549. QRegExp(element.attribute("expression")),
  4550. NULL));
  4551. }
  4552. }
  4553. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4554. layout->addWidget(widget);
  4555. }
  4556. @ It is natural for certain database fields to enter potentially large amounts
  4557. of free form text, for example, notes and annotations.
  4558. @<Functions for scripting@>=
  4559. void addTextToLayout(QDomElement element, QStack<QWidget *> *,@|
  4560. QStack<QLayout *> *layoutStack)
  4561. {
  4562. QTextEdit *widget = new QTextEdit;
  4563. if(element.hasAttribute("id"))
  4564. {
  4565. widget->setObjectName(element.attribute("id"));
  4566. }
  4567. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4568. layout->addWidget(widget);
  4569. }
  4570. @ The common use of |SqlQueryView| calls for the possibility of changing the
  4571. query during use. As such, there is little reason to accept attributes other
  4572. than an id for obtaining the view in a script.
  4573. @<Functions for scripting@>=
  4574. void addSqlQueryViewToLayout(QDomElement element,
  4575. QStack<QWidget *> *,@|
  4576. QStack<QLayout *> *layoutStack)
  4577. {
  4578. SqlQueryView *view = new SqlQueryView;
  4579. if(element.hasAttribute("id"))
  4580. {
  4581. view->setObjectName(element.attribute("id"));
  4582. }
  4583. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4584. layout->addWidget(view);
  4585. }
  4586. @ When the user is expected to enter a date, it is appropriate to use a date
  4587. editor. This one provides a calendar.
  4588. @<Functions for scripting@>=
  4589. void addCalendarToLayout(QDomElement element, QStack<QWidget *> *,@|
  4590. QStack<QLayout *> *layoutStack)
  4591. {
  4592. QDateEdit *widget = new QDateEdit;
  4593. widget->setCalendarPopup(true);
  4594. if(element.hasAttribute("id"))
  4595. {
  4596. widget->setObjectName(element.attribute("id"));
  4597. }
  4598. widget->setDate(QDate::currentDate());
  4599. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4600. layout->addWidget(widget);
  4601. }
  4602. @ Some additional properties are added to this object when it is retrieved by
  4603. the host environment.
  4604. @<Functions for scripting@>=
  4605. void setQDateEditProperties(QScriptValue value, QScriptEngine *engine)
  4606. {
  4607. setQDateTimeEditProperties(value, engine);
  4608. }
  4609. void setQDateTimeEditProperties(QScriptValue value, QScriptEngine *engine)
  4610. {
  4611. setQAbstractSpinBoxProperties(value, engine);
  4612. value.setProperty("setDate", engine->newFunction(QDateTimeEdit_setDate));
  4613. value.setProperty("day", engine->newFunction(QDateTimeEdit_day));
  4614. value.setProperty("month", engine->newFunction(QDateTimeEdit_month));
  4615. value.setProperty("year", engine->newFunction(QDateTimeEdit_year));
  4616. }
  4617. @ Certain operations on a |QDateEdit| are easier with a few convenience
  4618. properties that bypass the need to use the built in |date| property. For
  4619. example, an editor that should be set to 1 January of the current year can
  4620. obtain the year and set the date without directly using a |QDate| object.
  4621. @<Functions for scripting@>=
  4622. QScriptValue QDateTimeEdit_setDate(QScriptContext *context, QScriptEngine *)
  4623. {
  4624. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  4625. if(context->argumentCount() == 3)
  4626. {
  4627. self->setDate(QDate(argument<int>(0, context),
  4628. argument<int>(1, context),
  4629. argument<int>(2, context)));
  4630. }
  4631. else
  4632. {
  4633. context->throwError("Incorrect number of arguments passed to "
  4634. "QDateTimeEdit::setDate(). This method takes three integer arguments "
  4635. "specifying the year, month, and day.");
  4636. }
  4637. return QScriptValue();
  4638. }
  4639. QScriptValue QDateTimeEdit_day(QScriptContext *context, QScriptEngine *)
  4640. {
  4641. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  4642. return QScriptValue(self->date().day());
  4643. }
  4644. QScriptValue QDateTimeEdit_month(QScriptContext *context, QScriptEngine *)
  4645. {
  4646. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  4647. return QScriptValue(self->date().month());
  4648. }
  4649. QScriptValue QDateTimeEdit_year(QScriptContext *context, QScriptEngine *)
  4650. {
  4651. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  4652. return QScriptValue(self->date().year());
  4653. }
  4654. @ A few function prototypes are needed for this.
  4655. @<Function prototypes for scripting@>=
  4656. void setQDateEditProperties(QScriptValue value, QScriptEngine *engine);
  4657. void setQDateTimeEditProperties(QScriptValue value, QScriptEngine *engine);
  4658. QScriptValue QDateTimeEdit_setDate(QScriptContext *context,
  4659. QScriptEngine *engine);
  4660. QScriptValue QDateTimeEdit_day(QScriptContext *context, QScriptEngine *engine);
  4661. QScriptValue QDateTimeEdit_month(QScriptContext *context,
  4662. QScriptEngine *engine);
  4663. QScriptValue QDateTimeEdit_year(QScriptContext *context, QScriptEngine *engine);
  4664. @ In order to get to objects created from the XML description, it is necessary
  4665. to provide a function that can be called to retrieve children of a given widget.
  4666. When providing such an object to the script, it is necessary to determine the
  4667. type of that object and add the appropriate properties.
  4668. @<Function prototypes for scripting@>=
  4669. QScriptValue findChildObject(QScriptContext *context, QScriptEngine *engine);
  4670. @ This function must be made available to the scripting engine.
  4671. @<Set up the scripting engine@>=
  4672. engine->globalObject().setProperty("findChildObject",
  4673. engine->newFunction(findChildObject));
  4674. @ This function takes a script value representing some object which may have
  4675. been created from an XML description and a string containing the name of the
  4676. requested child element.
  4677. @<Functions for scripting@>=
  4678. QScriptValue findChildObject(QScriptContext *context, QScriptEngine *engine)
  4679. {
  4680. QObject *parent = argument<QObject *>(0, context);
  4681. QString name = argument<QString>(1, context);
  4682. QObject *object = parent->findChild<QObject *>(name);
  4683. QScriptValue value;
  4684. if(object)
  4685. {
  4686. value = engine->newQObject(object);
  4687. QString className = object->metaObject()->className();
  4688. @<Set object properties based on class name@>@;
  4689. }
  4690. return value;
  4691. }
  4692. @ Properties are added for a large number of class types.
  4693. @<Set object properties based on class name@>=
  4694. if(className == "TemperatureDisplay")
  4695. {
  4696. setTemperatureDisplayProperties(value, engine);
  4697. }
  4698. else if(className == "TimerDisplay")
  4699. {
  4700. setTimerDisplayProperties(value, engine);
  4701. }
  4702. else if(className == "QAction")
  4703. {
  4704. setQActionProperties(value, engine);
  4705. }
  4706. else if(className == "QBoxLayout")
  4707. {
  4708. setQBoxLayoutProperties(value, engine);
  4709. }
  4710. else if(className == "QDateEdit")
  4711. {
  4712. setQDateEditProperties(value, engine);
  4713. }
  4714. else if(className == "QFrame")
  4715. {
  4716. setQFrameProperties(value, engine);
  4717. }
  4718. else if(className == "QHBoxLayout")
  4719. {
  4720. setQBoxLayoutProperties(value, engine);
  4721. }
  4722. else if(className == "QLCDNumber")
  4723. {
  4724. setQLCDNumberProperties(value, engine);
  4725. }
  4726. else if(className == "QMenu")
  4727. {
  4728. setQMenuProperties(value, engine);
  4729. }
  4730. else if(className == "QMenuBar")
  4731. {
  4732. setQMenuBarProperties(value, engine);
  4733. }
  4734. else if(className == "QPushButton")
  4735. {
  4736. setQPushButtonProperties(value, engine);
  4737. }
  4738. else if(className == "QSplitter")
  4739. {
  4740. setQSplitterProperties(value, engine);
  4741. }
  4742. else if(className == "QTableView")
  4743. {
  4744. if(object->property("tabletype").isValid())
  4745. {
  4746. if(object->property("tabletype").toString() == "SaltTable")
  4747. {
  4748. setSaltTableProperties(value, engine);
  4749. }
  4750. }
  4751. }
  4752. else if(className == "QVBoxLayout")
  4753. {
  4754. setQBoxLayoutProperties(value, engine);
  4755. }
  4756. else if(className == "QWidget")
  4757. {
  4758. setQWidgetProperties(value, engine);
  4759. }
  4760. else if(className == "ScriptQMainWindow")
  4761. {
  4762. setQMainWindowProperties(value, engine);
  4763. }
  4764. else if(className == "SqlComboBox")
  4765. {
  4766. setSqlComboBoxProperties(value, engine);
  4767. }
  4768. else if(className == "SqlQueryView")
  4769. {
  4770. setSqlQueryViewProperties(value, engine);
  4771. }
  4772. else if(className == "ZoomLog")
  4773. {
  4774. setZoomLogProperties(value, engine);
  4775. }
  4776. else if(className == "QTextEdit")
  4777. {
  4778. setQTextEditProperties(value, engine);
  4779. }
  4780. else if(className == "QWebView")
  4781. {
  4782. setQWebViewProperties(value, engine);
  4783. }
  4784. @ In the list of classes, the SaltTable entry is for a class which does not
  4785. strictly exist on its own. It is, however, useful to provide some custom
  4786. properties when passing such an object to the host environment.
  4787. @<Function prototypes for scripting@>=
  4788. void setSaltTableProperties(QScriptValue value, QScriptEngine *engine);
  4789. QScriptValue SaltTable_bindableColumnArray(QScriptContext *context,
  4790. QScriptEngine *engine);
  4791. QScriptValue SaltTable_bindableQuotedColumnArray(QScriptContext *context,
  4792. QScriptEngine *engine);
  4793. QScriptValue SaltTable_columnSum(QScriptContext *context,
  4794. QScriptEngine *engine);
  4795. QScriptValue SaltTable_columnArray(QScriptContext *context,
  4796. QScriptEngine *engine);
  4797. QScriptValue SaltTable_data(QScriptContext *context, QScriptEngine *engine);
  4798. QScriptValue SaltTable_model(QScriptContext *context, QScriptEngine *engine);
  4799. QScriptValue SaltTable_quotedColumnArray(QScriptContext *context,
  4800. QScriptEngine *engine);
  4801. QScriptValue SaltTable_setData(QScriptContext *context, QScriptEngine *engine);
  4802. @ There are times when it is useful to obtain the sum of values in a column of
  4803. a SaltTable object. For example, when a column represents the weight of the
  4804. green coffee used in a batch, a sum of that column provides the total weight of
  4805. the batch which, when presented to the user, can be used to catch errors in
  4806. measuring batches or entering data.
  4807. @<Functions for scripting@>=
  4808. QScriptValue SaltTable_columnSum(QScriptContext *context, QScriptEngine *engine)
  4809. {
  4810. QTableView *self = getself<QTableView *>(context);
  4811. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  4812. QString datum;
  4813. double total = 0.0;
  4814. int column = argument<int>(0, context);
  4815. int role = argument<int>(1, context);
  4816. for(int i = 0; i < model->rowCount(); i++)
  4817. {
  4818. datum = model->data(model->index(i, column), role).toString();
  4819. if(!datum.isEmpty())
  4820. {
  4821. total += datum.toDouble();
  4822. }
  4823. }
  4824. return QScriptValue(engine, total);
  4825. }
  4826. @ Another common use of the SaltTable is producing the text for an array literal
  4827. to pass into a SQL query. The |SaltModel| used by this table makes this simple.
  4828. There are four functions for this functionality for different use cases.
  4829. @<Functions for scripting@>=
  4830. QScriptValue SaltTable_columnArray(QScriptContext *context,
  4831. QScriptEngine *engine)
  4832. {
  4833. QTableView *self = getself<QTableView *>(context);
  4834. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  4835. int column = argument<int>(0, context);
  4836. int role = argument<int>(1, context);
  4837. QString literal = model->arrayLiteral(column, role);
  4838. return QScriptValue(engine, literal);
  4839. }
  4840. QScriptValue SaltTable_quotedColumnArray(QScriptContext *context,
  4841. QScriptEngine *engine)
  4842. {
  4843. QTableView *self = getself<QTableView *>(context);
  4844. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  4845. int column = argument<int>(0, context);
  4846. int role = argument<int>(1, context);
  4847. QString literal = model->quotedArrayLiteral(column, role);
  4848. return QScriptValue(engine, literal);
  4849. }
  4850. QScriptValue SaltTable_bindableColumnArray(QScriptContext *context,
  4851. QScriptEngine *engine)
  4852. {
  4853. QTableView *self = getself<QTableView *>(context);
  4854. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  4855. int column = argument<int>(0, context);
  4856. int role = argument<int>(1, context);
  4857. QString literal = model->arrayLiteral(column, role);
  4858. literal.chop(1);
  4859. literal = literal.remove(0, 1);
  4860. return QScriptValue(engine, literal);
  4861. }
  4862. QScriptValue SaltTable_bindableQuotedColumnArray(QScriptContext *context,
  4863. QScriptEngine *engine)
  4864. {
  4865. QTableView *self = getself<QTableView *>(context);
  4866. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  4867. int column = argument<int>(0, context);
  4868. int role = argument<int>(1, context);
  4869. QString literal = model->quotedArrayLiteral(column, role);
  4870. literal.chop(1);
  4871. literal = literal.remove(0, 1);
  4872. return QScriptValue(engine, literal);
  4873. }
  4874. @ In order to obtain signals related to changes in the model, we need a way to
  4875. get to the model from the host environment.
  4876. @<Functions for scripting@>=
  4877. QScriptValue SaltTable_model(QScriptContext *context, QScriptEngine *engine)
  4878. {
  4879. QTableView *self = getself<QTableView *>(context);
  4880. QScriptValue value = engine->newQObject(self->model());
  4881. return value;
  4882. }
  4883. @ While this table was originally intended strictly for user input, there are a
  4884. few use cases in which it is useful to allow scripts to set the values in the
  4885. table. This can be done with |setData|. This method takes four arguments: the
  4886. row and column of the table being set, the value to set, and the role of the
  4887. data being set.
  4888. @<Functions for scripting@>=
  4889. QScriptValue SaltTable_setData(QScriptContext *context, QScriptEngine *)
  4890. {
  4891. QTableView *self = getself<QTableView *>(context);
  4892. int row = argument<int>(0, context);
  4893. int column = argument<int>(1, context);
  4894. QVariant value = argument<QVariant>(2, context);
  4895. int role = argument<int>(3, context);
  4896. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  4897. QModelIndex cell = model->index(row, column);
  4898. model->setData(cell, value, role);
  4899. self->update(cell);
  4900. return QScriptValue();
  4901. }
  4902. @ It is sometimes useful to obtain the data from a single cell of the table.
  4903. This can be done with the |data()| property.
  4904. @<Functions for scripting@>=
  4905. QScriptValue SaltTable_data(QScriptContext *context, QScriptEngine *engine)
  4906. {
  4907. QTableView *self = getself<QTableView *>(context);
  4908. int row = argument<int>(0, context);
  4909. int column = argument<int>(1, context);
  4910. int role = argument<int>(2, context);
  4911. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  4912. QModelIndex cell = model->index(row, column);
  4913. QVariant value = model->data(cell, role);
  4914. QScriptValue retval = engine->newVariant(value);
  4915. retval.setProperty("value", QScriptValue(value.toString()));
  4916. return retval;
  4917. }
  4918. @ These functions need to be added as properties of the table when it is passed
  4919. to the host environment.
  4920. @<Functions for scripting@>=
  4921. void setSaltTableProperties(QScriptValue value, QScriptEngine *engine)
  4922. {
  4923. setQWidgetProperties(value, engine);
  4924. value.setProperty("columnArray",
  4925. engine->newFunction(SaltTable_columnArray));
  4926. value.setProperty("quotedColumnArray",
  4927. engine->newFunction(SaltTable_quotedColumnArray));
  4928. value.setProperty("bindableColumnArray",
  4929. engine->newFunction(SaltTable_bindableColumnArray));
  4930. value.setProperty("bindableQuotedColumnArray",
  4931. engine->newFunction(SaltTable_bindableQuotedColumnArray));
  4932. value.setProperty("columnSum", engine->newFunction(SaltTable_columnSum));
  4933. value.setProperty("data", engine->newFunction(SaltTable_data));
  4934. value.setProperty("model", engine->newFunction(SaltTable_model));
  4935. value.setProperty("setData", engine->newFunction(SaltTable_setData));
  4936. }
  4937. @ The |SqlComboBox| is another class that is not constructed from scripts but is
  4938. useful to access from them. A property is added to obtain the current user data
  4939. from the widget.
  4940. @<Function prototypes for scripting@>=
  4941. void setSqlComboBoxProperties(QScriptValue value, QScriptEngine *engine);
  4942. void setQComboBoxProperties(QScriptValue value, QScriptEngine *engine);
  4943. QScriptValue QComboBox_currentData(QScriptContext *context,
  4944. QScriptEngine *engine);
  4945. QScriptValue QComboBox_addItem(QScriptContext *context, QScriptEngine *engine);
  4946. QScriptValue QComboBox_setModel(QScriptContext *context, QScriptEngine *engine);
  4947. QScriptValue QComboBox_findText(QScriptContext *context, QScriptEngine *engine);
  4948. @ These functions should seem familiar by now.
  4949. @<Functions for scripting@>=
  4950. void setSqlComboBoxProperties(QScriptValue value, QScriptEngine *engine)
  4951. {
  4952. setQComboBoxProperties(value, engine);
  4953. }
  4954. void setQComboBoxProperties(QScriptValue value, QScriptEngine *engine)
  4955. {
  4956. setQWidgetProperties(value, engine);
  4957. value.setProperty("currentData",
  4958. engine->newFunction(QComboBox_currentData));
  4959. value.setProperty("addItem", engine->newFunction(QComboBox_addItem));
  4960. value.setProperty("setModel", engine->newFunction(QComboBox_setModel));
  4961. value.setProperty("findText", engine->newFunction(QComboBox_findText));
  4962. }
  4963. QScriptValue QComboBox_currentData(QScriptContext *context,
  4964. QScriptEngine *engine)
  4965. {
  4966. QComboBox *self = getself<QComboBox *>(context);
  4967. return QScriptValue(engine,
  4968. self->itemData(self->currentIndex()).toString());
  4969. }
  4970. QScriptValue QComboBox_addItem(QScriptContext *context, QScriptEngine *)
  4971. {
  4972. QComboBox *self = getself<QComboBox *>(context);
  4973. self->addItem(argument<QString>(0, context));
  4974. return QScriptValue();
  4975. }
  4976. QScriptValue QComboBox_setModel(QScriptContext *context, QScriptEngine *)
  4977. {
  4978. QComboBox *self = getself<QComboBox *>(context);
  4979. self->setModel(argument<QAbstractItemModel *>(0, context));
  4980. return QScriptValue();
  4981. }
  4982. QScriptValue QComboBox_findText(QScriptContext *context, QScriptEngine *engine)
  4983. {
  4984. QComboBox *self = getself<QComboBox *>(context);
  4985. return QScriptValue(engine, self->findText(argument<QString>(0, context)));
  4986. }
  4987. @i abouttypica.w
  4988. @** A representation of temperature measurements.
  4989. \noindent Most of the information in a roast log will be temperature
  4990. measurements. These measurements are made of two components: the measured
  4991. temperature and the time at which that measurement was taken.
  4992. Measurement times are represented as instances of |QTime|.
  4993. The declaration of |Measurement| is reasonably straightforward. Measurements
  4994. will often be passed around to a number of different objects through the signals
  4995. and slots mechanism of Qt. The simplest way to make this work is to provide a
  4996. copy constructor and an assignment operator.
  4997. Starting with version 1.1.2 the |Measurement| class contains an indication of
  4998. the measurement unit and methods for converting a measurement from one unit to
  4999. another. The units are represented by the same constants as the |DAQ| class.
  5000. This can almost certainly be handled better.
  5001. @<Class declarations@>=
  5002. class Measurement@/
  5003. {
  5004. public:@/
  5005. enum TemperatureUnits
  5006. {
  5007. Fahrenheit = 10144,
  5008. Celsius = 10143,
  5009. Kelvin = 10325,
  5010. Rankine = 10145
  5011. };
  5012. private:@/
  5013. double theTemperature;
  5014. QTime theTime;
  5015. TemperatureUnits unit;
  5016. public:@;
  5017. Measurement(double temperature = 0, QTime time = QTime(),@|
  5018. TemperatureUnits sc = Fahrenheit);
  5019. Measurement(double temperature);
  5020. Measurement(const Measurement &x);
  5021. Measurement& operator=(Measurement &x);
  5022. ~Measurement();
  5023. double temperature() const;
  5024. QTime time() const;
  5025. void setTemperature(double temperature);
  5026. void setTime(QTime time);
  5027. void setUnit(TemperatureUnits scale);
  5028. TemperatureUnits scale();
  5029. Measurement toFahrenheit();
  5030. Measurement toCelsius();
  5031. Measurement toKelvin();
  5032. Measurement toRankine();
  5033. };
  5034. @ There are two constructors that can create |Measurement| objects. The
  5035. constructor that takes both a temperature and a time is declared as a default
  5036. constructor because one is needed to pass objects through |QMetaType|. The
  5037. constructor that only takes a temperature uses the measured temperature and the
  5038. current time.
  5039. @<Measurement implementation@>=
  5040. Measurement::Measurement(double temperature, QTime time,
  5041. TemperatureUnits sc) :@;
  5042. @t\kern2em@>theTemperature(temperature), theTime(time), unit(sc)@;
  5043. {
  5044. /* Nothing has to be done here. */
  5045. }@;
  5046. Measurement::Measurement(double temperature) :@;
  5047. @t\kern2em@>theTemperature(temperature), theTime(QTime::currentTime()),
  5048. unit(Fahrenheit)@;
  5049. {
  5050. /* Nothing has to be done here. */
  5051. }@;
  5052. @ Qt uses |QMetaType| in queued signals and slots connections such as those
  5053. between objects in different execution threads. To pass |Measurement| objects
  5054. through this mechanism we must register it with that class. This only needs to
  5055. be done once and can be done in the |main()| function during program
  5056. initialization.
  5057. @<Register meta-types@>=
  5058. qRegisterMetaType<Measurement>("Measurement");@/
  5059. @ To successfully register a class with |QMetaType| it must have a public
  5060. default constructor (already defined above), a public copy constructor, and a
  5061. public destructor.
  5062. @<Measurement implementation@>=
  5063. Measurement::Measurement(const Measurement &x) :@;
  5064. @t\kern2em@>theTemperature(x.temperature()), theTime(x.time()),
  5065. unit(x.unit)
  5066. {
  5067. /* Nothing has to be done here. */
  5068. }@;
  5069. Measurement::~Measurement()
  5070. {
  5071. /* Nothing has to be done here. */
  5072. }
  5073. @ Once the assignment operator is implemented it is possible to get measurements
  5074. to all of the objects that need them.
  5075. @<Measurement implementation@>=
  5076. Measurement&@,@, Measurement::operator=(Measurement &x)
  5077. {
  5078. theTemperature = x.temperature();
  5079. theTime = x.time();
  5080. unit = x.unit;
  5081. return *this;
  5082. }
  5083. @ Four member functions are used to get and set the time and temperature data of
  5084. a measurement. A measurement might need to be modified to convert from one
  5085. temperature unit to another or to convert a measurement time from system time to
  5086. a time relative to the start of a batch.
  5087. @<Measurement implementation@>=
  5088. double Measurement::temperature() const
  5089. {
  5090. return theTemperature;
  5091. }
  5092. QTime Measurement::time() const
  5093. {
  5094. return theTime;
  5095. }
  5096. void Measurement::setTemperature(double temperature)
  5097. {
  5098. theTemperature = temperature;
  5099. }
  5100. void Measurement::setTime(QTime time)
  5101. {
  5102. theTime = time;
  5103. }
  5104. @ This method changes the scale of the measurement. Note that this does not
  5105. alter the number holding the measurement. To convert a measurement from one
  5106. unit to another, use the appropriate |to[Fahrenheit||Celsius||Kelvin||Rankine]|
  5107. method.
  5108. @<Measurement implementation@>=
  5109. void Measurement::setUnit(TemperatureUnits scale)
  5110. {
  5111. unit = scale;
  5112. }
  5113. Measurement::TemperatureUnits Measurement::scale()
  5114. {
  5115. return unit;
  5116. }
  5117. @ Four methods create a new |Measurement| from the object the method is called
  5118. on representing the same measurement expressed in different units. The
  5119. conversion formul\ae{} come from Wikipedia.\nfnote{%
  5120. \pdfURL{Temperature Conversion}{%
  5121. http://en.wikipedia.org/%
  5122. w/index.php?title=Temperature_conversion&oldid=226047163}}
  5123. The |toFahrenheit()| method converts a measurement to Fahrenheit.
  5124. @<Measurement implementation@>=
  5125. Measurement Measurement::toFahrenheit()
  5126. {
  5127. switch(unit)
  5128. {
  5129. case Celsius:
  5130. return Measurement(this->temperature() * 9 / 5 + 32, this->time(),
  5131. Fahrenheit);
  5132. break;
  5133. case Kelvin:
  5134. return Measurement(this->temperature() * 5 / 9 - 459.67,
  5135. this->time(), Fahrenheit);
  5136. break;
  5137. case Rankine:
  5138. return Measurement(this->temperature() - 459.67, this->time(),
  5139. Fahrenheit);
  5140. break;
  5141. default:
  5142. return Measurement(this->temperature(), this->time(), Fahrenheit);
  5143. break;
  5144. }
  5145. }
  5146. @ Similarly, the following converts to Celsius.
  5147. @<Measurement implementation@>=
  5148. Measurement Measurement::toCelsius()
  5149. {
  5150. switch(unit)
  5151. {
  5152. case Fahrenheit:
  5153. return Measurement((this->temperature() - 32) * 5 / 9, this->time(),
  5154. Celsius);
  5155. break;
  5156. case Kelvin:
  5157. return Measurement(this->temperature() - 273.15, this->time(),
  5158. Celsius);
  5159. break;
  5160. case Rankine:
  5161. return Measurement((this->temperature() - 491.67) * 5 / 9,
  5162. this->time(), Celsius);
  5163. break;
  5164. default:
  5165. return Measurement(this->temperature(), this->time(), Celsius);
  5166. break;
  5167. }
  5168. }
  5169. @ For those who prefer absolute scales, a method is provided to convert to
  5170. Kelvin.
  5171. @<Measurement implementation@>=
  5172. Measurement Measurement::toKelvin()
  5173. {
  5174. switch(unit)
  5175. {
  5176. case Fahrenheit:
  5177. return Measurement((this->temperature() + 459.67) * 5 / 9,
  5178. this->time(), Kelvin);
  5179. break;
  5180. case Celsius:
  5181. return Measurement(this->temperature() + 273.15, this->time(),
  5182. Kelvin);
  5183. break;
  5184. case Rankine:
  5185. return Measurement(this->temperature() * 5 / 9, this->time(),
  5186. Kelvin);
  5187. break;
  5188. default:
  5189. return Measurement(this->temperature(), this->time(), Kelvin);
  5190. break;
  5191. }
  5192. }
  5193. @ Finally, conversion to Rankine is also allowed.
  5194. @<Measurement implementation@>=
  5195. Measurement Measurement::toRankine()
  5196. {
  5197. switch(unit)
  5198. {
  5199. case Fahrenheit:
  5200. return Measurement(this->temperature() + 459.67, this->time(),
  5201. Rankine);
  5202. break;
  5203. case Celsius:
  5204. return Measurement((this->temperature() + 273.15) * 9 / 5,
  5205. this->time(), Rankine);
  5206. break;
  5207. case Kelvin:
  5208. return Measurement(this->temperature() * 9 / 5, this->time(),
  5209. Rankine);
  5210. break;
  5211. default:
  5212. return Measurement(this->temperature(), this->time(), Rankine);
  5213. break;
  5214. }
  5215. }
  5216. @** The Main Measurement Pipeline.
  5217. \noindent Measurements are sent through \pn{} in a way similar to liquid moving
  5218. through a series of connected pipes. \pn{} is not something that you just dump
  5219. measurements on. It's not a big truck\nfnote{Senator Ted Stevens (R-Alaska) on
  5220. network neutrality, June 28, 2006\par
  5221. \hbox{\indent\pdfURL{http://media.publicknowledge.org/stevens-on-nn.mp3}%
  5222. {http://media.publicknowledge.org/stevens-on-nn.mp3}}}. In most cases the
  5223. connections between classes (represented by arrows in Figure \secno) are made
  5224. with Qt's signals and slots mechanism\nfnote{Qt 4.4.3: Signals and Slots\par
  5225. \hbox{\indent\pdfURL{http://doc.trolltech.com/4.4/signalsandslots.html}%
  5226. {http://doc.trolltech.com/4.4/signalsandslots.html}}}, but
  5227. these
  5228. connections can
  5229. also be made through direct function calls as is the case with the connection
  5230. between |ZoomLog| and |MeasurementModel|.
  5231. \medskip
  5232. \includegraphics{pipes}
  5233. \smallskip
  5234. \centerline{Figure \secno: Example Flow of Measurement objects in \pn}
  5235. \medskip
  5236. Please note that Figure \secno~is representative of a typical configuration. Now
  5237. that the flow of measurements through \pn{} is determined by a script specified
  5238. by the user, whatever pipeline is needed can be specified at run time.
  5239. @* The DAQ class.
  5240. \noindent The |DAQ| class represents a piece of hardware that allows the
  5241. computer to read measurements from one or more thermocouples. Presently this
  5242. class is only handles continuous sampling on devices from National Instruments.
  5243. It should be simple to modify this class to handle similar devices from other
  5244. vendors.
  5245. Each device is represented by a single instance of this class. Multiple channels
  5246. can be used on a device if the device supports it.
  5247. Two enumerations are declared in this class to be used as arguments to
  5248. |newChannel()|. The first is used to set the measurement unit for the channel.
  5249. As the measurements themselves do not carry this information, it is important to
  5250. keep track of this information. The values come from {\tt nidaqmxbase.h} and can
  5251. be used to select among Fahrenheit, Celsius, Kelvin, and Rankine. The
  5252. second enumeration, |ThermocoupleType|, should be used to specify the type of
  5253. thermocouple connected to the device. If this does not match reality, the
  5254. measurements will not be correct. The meanings of the values should be obvious
  5255. from the names.
  5256. \danger When this class was originally written the method of thread handling
  5257. used was considered appropriate. New functionality in |QThread| has made this
  5258. no longer the case. This class is currently planned for depreciation once a
  5259. replacement class hierarchy more suited to multiple hardware types is available
  5260. however if this is not ready soon it may be beneficial to rewrite this class to
  5261. conform to current best practices.\endanger
  5262. @<Class declarations@>=
  5263. class Channel;
  5264. class DAQImplementation;@/
  5265. class DAQ : public QObject@;@/
  5266. {@t\1@>@/
  5267. Q_OBJECT@/
  5268. Q_ENUMS(TemperatureUnits)@/
  5269. Q_ENUMS(ThermocoupleType)@;@/
  5270. DAQImplementation *imp;@/
  5271. @t\4@>private slots@t\kern-3pt@>:@/
  5272. void threadFinished();
  5273. public:@;
  5274. DAQ(QString device, const QString &driver = QString("nidaqmxbase"));
  5275. ~DAQ();@/
  5276. Channel* newChannel(int units, int thermocouple);@/
  5277. @[Q_INVOKABLE@,@, void@]@, setClockRate(double Hz);@t\2\2@>@/
  5278. @[Q_INVOKABLE@,@, void@]@, start();@t\2\2@>@/
  5279. @[Q_INVOKABLE@]@, void stop();
  5280. enum TemperatureUnits@/
  5281. {
  5282. @!Fahrenheit = 10144,
  5283. @!Celsius = 10143,
  5284. @!Kelvin = 10325,
  5285. @!Rankine = 10145
  5286. };
  5287. enum ThermocoupleType@/
  5288. {
  5289. @!TypeJ = 10072,
  5290. @!TypeK = 10073,
  5291. @!TypeN = 10077,
  5292. @!TypeR = 10082,
  5293. @!TypeS = 10085,
  5294. @!TypeT = 10086,
  5295. @!TypeB = 10047,
  5296. @!TypeE = 10055
  5297. };@t\2@>@/
  5298. }@t\kern-3pt@>;
  5299. @ The |DAQ| class has as a private member an instance of a class called
  5300. |DAQImplementation|. The two classes together create and run a new thread of
  5301. execution. This thread spends most of its time blocking while waiting for a new
  5302. measurement to become available. When a new measurement is available, that
  5303. measurement is passed to the appropriate channel which in turn passes it to any
  5304. interested object.
  5305. @<Class declarations@>=
  5306. class DAQImplementation : public QThread@;@/
  5307. {@;
  5308. Q_OBJECT@;@/
  5309. public:@;
  5310. DAQImplementation(const QString &driverinfo);
  5311. ~DAQImplementation();
  5312. void run();
  5313. void measure();
  5314. @<Library function pointers@>@;
  5315. @<DAQImplementation member data@>@;
  5316. }@+@t\kern-3pt@>;
  5317. @ In order to solve some minor problems, NI-DAQmxBase is no longer linked at
  5318. compile time. Rather, this is now linked at runtime through a |QLibrary| object.
  5319. In order to use functions from this library, these functions must be stored in
  5320. function pointers. Fortunately, all of these functions can be expressed with the
  5321. same pointer type. Unfortunately, this way of doing things offers very little
  5322. debugging information in the event that something is not quite right.
  5323. @<Library function pointers@>=
  5324. typedef int (*daqfp)(...);
  5325. daqfp read;
  5326. daqfp errorInfo;
  5327. daqfp startTask;
  5328. daqfp createTask;
  5329. daqfp createChannel;
  5330. daqfp setClock;
  5331. daqfp stopTask;
  5332. daqfp clearTask;
  5333. daqfp resetDevice;
  5334. daqfp waitForMeasurement;
  5335. @ |DAQImplementation| also maintains information about the device and the
  5336. channels the measurements are sent to.
  5337. @<DAQImplementation member data@>=
  5338. bool useBase;
  5339. QString device;
  5340. QVector<Channel*> channelMap;
  5341. unsigned int handle;@/
  5342. int error;
  5343. int channels;
  5344. bool ready;
  5345. QLibrary driver;
  5346. QVector<Measurement::TemperatureUnits> unitMap;
  5347. @ Most of the interesting work associated with the |DAQ| class is handled in
  5348. the |measure()| method of |DAQImplementation|. This function will block until a
  5349. measurement is available. Once |buffer| is filled by |DAQmxBaseReadAnalogF64()|
  5350. that function returns and new |Measurement| objects are created based on the
  5351. information in the buffer. These measurements are sent to |Channel| objects
  5352. tracked by |channelMap|.
  5353. Up until version 1.0.7 there was a bug in this code that would prevent the code
  5354. from working when more than one channel is requested. This has been corrected.
  5355. With version 1.0.9, time measurement is moved out of the loop, reducing the
  5356. number of calls in cases of more than 1 measurement and ensuring that all
  5357. simultaneously obtained measurements have the same time stamp.
  5358. @<DAQ Implementation@>=
  5359. void DAQImplementation::measure()@t\2@>@/
  5360. @t\4@>{@/
  5361. int samplesRead = 0;
  5362. double buffer[channels];
  5363. error = read((unsigned int)(handle), (signed long)(1), (double)(10.0),
  5364. (unsigned long)(0), buffer, (unsigned long)(channels),
  5365. &samplesRead, (signed long)(0));
  5366. if(error)@/
  5367. @t\1@>{@/
  5368. ready = false;@t\2@>@/
  5369. }
  5370. else@/
  5371. {
  5372. if(samplesRead)@/
  5373. {
  5374. QTime time = QTime::currentTime();@/
  5375. for(int i = 0; i < samplesRead; i++)@/
  5376. {
  5377. for(int j = 0; j < channels; j++)@/
  5378. {
  5379. Measurement measure(buffer[@,j+(i*channels)], time,
  5380. unitMap[j]);
  5381. channelMap[@,j]->input(measure);
  5382. }
  5383. }
  5384. }
  5385. }
  5386. @t\4@>}
  5387. @ It was noted that |DAQmxBaseReadAnalogF64()| blocks until it is able to fill
  5388. the |buffer| passed to it. To prevent this behavior from having adverse effects
  5389. on the rest of the program, measure is called from a loop running in its own
  5390. thread of execution. When the thread is started, it begins its execution from
  5391. the |run()| method of |DAQImplementation| which overrides the |run()| method of
  5392. |QThread|. Here the priority of the thread is set in an attempt to cut down on
  5393. the variation in time between recorded measurements.
  5394. The while loop is controlled by |ready| which is set to |false| when there is an
  5395. error in collecting a measurement or when the user wants to exit the program. It
  5396. could also be set to |false| when the |DAQ| is reconfigured.
  5397. @<DAQ Implementation@>=
  5398. void DAQImplementation::run()
  5399. {
  5400. setPriority(QThread::TimeCriticalPriority);
  5401. while(ready)
  5402. {
  5403. measure();
  5404. }
  5405. }
  5406. @ When this loop exits, |DAQImplementation| emits a finished signal to indicate
  5407. that the thread is no longer running. This could be due to perfectly normal
  5408. conditions, but there could also be a problem that the user must be informed of.
  5409. That signal is connected to a function that checks for error conditions and
  5410. reports them if needed.
  5411. @<DAQ Implementation@>=
  5412. void DAQ::threadFinished()
  5413. {
  5414. if(imp->error)
  5415. {
  5416. @<Display DAQ Error@>@;
  5417. }
  5418. }
  5419. @ Errors are displayed with a |QMessageBox|. NIDAQmxBase provides the message
  5420. strings for these errors, but this should probably change as these error strings
  5421. are generally completely unrelated to what the problem really is. For example,
  5422. ``Error: -1'' usually means that the device is not plugged in.
  5423. ``Error: -200170'' usually means that \pn{} or another program using the device
  5424. did not exit cleanly. A table of replacement warning messages should be added to
  5425. this program.
  5426. \bigskip
  5427. \settabs 5 \columns
  5428. \+Error Code & NIDAQmxBase Text & & Likely Cause\cr
  5429. \+\hrulefill & \hrulefill & \hrulefill & \hrulefill & \hrulefill & \hrulefill\cr
  5430. \+ -1 & Not implemented for this device & & The device is not plugged in.\cr
  5431. \+ & type. & \cr
  5432. \+ -200170 & Physical channel specified & & The program did not exit cleanly\cr
  5433. \+ & does not exist on this device. & & or another program is using the\cr
  5434. \+ & Refer to the documentation for & & device.\cr
  5435. \+ & channels available on this device.\cr
  5436. \+ -1073807194 & {\it{(No text)}} & & The device has been unplugged.\cr
  5437. \medskip
  5438. \centerline{Table \secno: Error codes, text, and what they really mean.}
  5439. \bigskip
  5440. There are two calls to |DAQmxBaseGetExtendedErrorInfo()| to obtain the error
  5441. messages. The first is used just to obtain the length of the error string. That
  5442. length is then used to allocate space for the error message. The second call
  5443. fills that string. This isn't allowed by ISO \CPLUSPLUS/\nfnote{%
  5444. \CPLUSPLUS/Dynamic Arrays (Crowl and Austern, May 16, 2008)\par
  5445. \hbox{\indent\pdfURL{%
  5446. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2648.html}{%
  5447. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2648.html}}} but it
  5448. works with gcc. If this is a problem, the first call can be
  5449. removed and the buffer can be set large enough to fit the largest error message
  5450. that will be produced. Heap allocation could be used, but then we need to
  5451. remember to free the memory allocated to the string. Alternately, we can get rid
  5452. of \CEE/ style strings and write our own error messages. This would be the
  5453. preferred correction.
  5454. @<Display DAQ Error@>=
  5455. imp->ready = false;
  5456. QMessageBox warning;
  5457. warning.setStandardButtons(QMessageBox::Cancel);
  5458. warning.setIcon(QMessageBox::Warning);
  5459. warning.setText(QString(tr("Error: %1")).arg(imp->error));
  5460. unsigned long bytes = imp->errorInfo(NULL, 0);
  5461. char string[bytes];
  5462. imp->errorInfo(string, bytes);
  5463. warning.setInformativeText(QString(string));
  5464. warning.setWindowTitle(QString(PROGRAM_NAME));
  5465. warning.exec();
  5466. @ Starting the thread is almost as simple as ending it. The hardware is
  5467. instructed to begin taking measurements. If there is an error, this is handled.
  5468. Otherwise, the finished signal from |DAQImplementation| is connected to
  5469. |threadFinished()| and the new thread is started. The call to |imp->start()|
  5470. starts a new thread and passes control of that thread to |imp->run()|. The main
  5471. thread of execution returns without waiting for the new thread to do anything.
  5472. The call to |DAQmxBaseStartTask()| requires some time before the first
  5473. measurement is available. This is one of the reasons we start gathering
  5474. measurements before we really need them and continue to collect them until it is
  5475. time to exit the program.
  5476. @<DAQ Implementation@>=
  5477. void DAQ::start()
  5478. {
  5479. if(imp->ready)
  5480. {
  5481. imp->error = imp->startTask(imp->handle);
  5482. if(imp->error)
  5483. {
  5484. @<Display DAQ Error@>@;
  5485. }
  5486. else
  5487. {
  5488. connect(imp, SIGNAL(finished()), this, SLOT(threadFinished()));
  5489. imp->start();
  5490. }
  5491. }
  5492. }
  5493. void DAQ::stop()
  5494. {
  5495. if(imp->useBase)
  5496. {
  5497. imp->ready = false;
  5498. imp->wait(ULONG_MAX);
  5499. imp->stopTask(imp->handle);
  5500. }
  5501. else
  5502. {
  5503. imp->ready = false;
  5504. imp->error = imp->stopTask(imp->handle);
  5505. if(imp->error)
  5506. {
  5507. @<Display DAQ Error@>@;
  5508. }
  5509. imp->error = imp->clearTask(imp->handle);
  5510. if(imp->error)
  5511. {
  5512. @<Display DAQ Error@>@;
  5513. }
  5514. }
  5515. }
  5516. @ Setting up the DAQ begins by constructing a new |DAQ| object. The constructor
  5517. takes as its argument a string indicating the name of the device and will
  5518. typically be something like |"Dev1"|. This creates a new task which is required
  5519. for the setup that follows once a new |DAQ| is created.
  5520. @<DAQ Implementation@>=
  5521. DAQ::DAQ(QString device, const QString &driver) : imp(new DAQImplementation(driver))@/
  5522. @t\4\4@>{@/
  5523. imp->device = device;
  5524. imp->error = imp->createTask(device.toAscii().data(), &(imp->handle));
  5525. if(imp->error)@/
  5526. {
  5527. @<Display DAQ Error@>@;
  5528. }
  5529. else@/
  5530. @t\1@>{@/
  5531. imp->ready = true;@t\2@>@/
  5532. }@/
  5533. @t\4\4@>}
  5534. @ Once the |DAQ| is created, one or more channels can be added to that |DAQ|.
  5535. All |Channel| objects are created by the |DAQ| class and are managed by the
  5536. |DAQ| class. When a new channel is created, a pointer is passed back allowing
  5537. other classes to connect to the channel. Measurements cannot be read from the
  5538. |DAQ| directly. They must at some point pass through a channel.
  5539. @<DAQ Implementation@>=
  5540. Channel* DAQ::newChannel(int units, int thermocouple)
  5541. {
  5542. Channel *retval = new Channel();
  5543. imp->channelMap[imp->channels] = retval;
  5544. imp->unitMap[imp->channels] = (Measurement::TemperatureUnits)units;
  5545. imp->channels++;
  5546. if(imp->ready)
  5547. {
  5548. if(imp->useBase)
  5549. {
  5550. imp->error = imp->createChannel(imp->handle,
  5551. QString("%1/ai%2").arg(imp->device).
  5552. arg(imp->channels - 1).
  5553. toAscii().data(),
  5554. "", (double)(-1.0), (double)(100.0),
  5555. (signed long)(units),
  5556. (signed long)(thermocouple),
  5557. (signed long)(10200), (double)(0),
  5558. "");
  5559. }
  5560. else
  5561. {
  5562. imp->error = imp->createChannel(imp->handle,
  5563. QString("%1/ai%2").arg(imp->device).
  5564. arg(imp->channels - 1).
  5565. toAscii().data(),
  5566. "", (double)(50.0), (double)(500.0),
  5567. (signed long)(units),
  5568. (signed long)(thermocouple),
  5569. (signed long)(10200), (double)(0),
  5570. "");
  5571. }
  5572. if(imp->error)
  5573. {
  5574. @<Display DAQ Error@>@;
  5575. }
  5576. }
  5577. return retval;
  5578. }
  5579. @ Once the channels are created, it is necessary to set the clock rate of the
  5580. DAQ. The clock rate chosen must be supported by the hardware. The clock rates
  5581. supported by the hardware may be altered by the number of channels in use.
  5582. The amount of time between measurements may vary slightly. A test configuration
  5583. at Wilson's Coffee \char'046~Tea used a 4Hz clock rate and provides measurements
  5584. every 251$\pm$1ms with 80\% of measurements spaced 251ms apart.
  5585. @<DAQ Implementation@>=
  5586. void DAQ::setClockRate(double Hz)
  5587. {
  5588. if(imp->ready)
  5589. {
  5590. imp->error = imp->setClock(imp->handle, "OnboardClock", Hz,
  5591. (signed long)(10280), (signed long)(10123),
  5592. (unsigned long long)(1));
  5593. if(imp->error)
  5594. {
  5595. @<Display DAQ Error@>@;
  5596. }
  5597. }
  5598. }
  5599. @ Before the program exits, the |DAQ| should be deleted. The destructor
  5600. instructs the measurement thread to stop, waits for it to finish, and resets the
  5601. device. If this is not done, an error would be issued the next time a program
  5602. attempted to use the device.
  5603. @<DAQ Implementation@>=
  5604. DAQ::~DAQ()@/
  5605. @t\4\4@>{@/
  5606. if(imp->useBase)
  5607. {
  5608. imp->resetDevice(imp->device.toAscii().data());
  5609. imp->clearTask(imp->handle);
  5610. }
  5611. else
  5612. {
  5613. if(imp->ready)
  5614. {
  5615. imp->ready = false;
  5616. imp->wait(ULONG_MAX);
  5617. imp->stopTask(imp->handle);
  5618. imp->resetDevice(imp->device.toAscii().data());
  5619. imp->clearTask(imp->handle);
  5620. }
  5621. }
  5622. delete imp;
  5623. @t\4\4@>}
  5624. @ This just leaves the constructor and destructor for |DAQImplementation|. The
  5625. way the program is currently written, the number of channels available on the
  5626. |DAQ| is limited to 4. If a known larger number is required, the value here can
  5627. simply be set larger, however the best long term solution would be to modify
  5628. |newChannel()| to resize |channelMap| as more channels are added.
  5629. The constructor handles loading NI-DAQmxBase and preparing function pointers for
  5630. the symbols used in \pn{}.
  5631. @<DAQ Implementation@>=
  5632. DAQImplementation::DAQImplementation(const QString &driverinfo)
  5633. : QThread(NULL), channelMap(4), handle(0), error(0), channels(0), ready(false),
  5634. unitMap(4)@/
  5635. {
  5636. if(driverinfo == "nidaqmxbase")
  5637. {
  5638. useBase = true;
  5639. }
  5640. else
  5641. {
  5642. useBase = false;
  5643. }
  5644. if(useBase)
  5645. {
  5646. driver.setFileName("nidaqmxbase.framework/nidaqmxbase");
  5647. if(!driver.load())
  5648. {
  5649. driver.setFileName("nidaqmxbase");
  5650. if(!driver.load())
  5651. {
  5652. QMessageBox::critical(NULL, tr("Typica: Driver not found"),
  5653. tr("Failed to find nidaqmxbase. Please install it."));
  5654. QApplication::quit();
  5655. }
  5656. }
  5657. }
  5658. else
  5659. {
  5660. driver.setFileName("nicaiu");
  5661. if(!driver.load())
  5662. {
  5663. QMessageBox::critical(NULL, tr("Typica: Driver not found"),
  5664. tr("Failed to find nidaqmx. Please install it."));
  5665. QApplication::quit();
  5666. }
  5667. }
  5668. if(useBase)
  5669. {
  5670. if((createTask = (daqfp) driver.resolve("DAQmxBaseCreateTask")) == 0 || @|
  5671. (startTask = (daqfp) driver.resolve("DAQmxBaseStartTask")) == 0 || @|
  5672. (stopTask = (daqfp) driver.resolve("DAQmxBaseStopTask")) == 0 || @|
  5673. (clearTask = (daqfp) driver.resolve("DAQmxBaseClearTask")) == 0 || @|
  5674. (createChannel = (daqfp) driver.resolve("DAQmxBaseCreateAIThrmcplChan"))
  5675. == 0 || @|
  5676. (setClock = (daqfp) driver.resolve("DAQmxBaseCfgSampClkTiming")) ==
  5677. 0 || @|
  5678. (read = (daqfp) driver.resolve("DAQmxBaseReadAnalogF64")) == 0 || @|
  5679. (errorInfo = (daqfp) driver.resolve("DAQmxBaseGetExtendedErrorInfo")) ==
  5680. 0 || @|
  5681. (resetDevice = (daqfp) driver.resolve("DAQmxBaseResetDevice")) == 0)@/
  5682. {
  5683. waitForMeasurement = NULL;
  5684. QMessageBox::critical(NULL, tr("Typica: Link error"),
  5685. tr("Failed to link a required symbol in NI-DAQmxBase."));
  5686. QApplication::quit();
  5687. }
  5688. }
  5689. else
  5690. {
  5691. if((createTask = (daqfp)driver.resolve("DAQmxCreateTask")) == 0 || @|
  5692. (startTask = (daqfp)driver.resolve("DAQmxStartTask")) == 0 || @|
  5693. (stopTask = (daqfp)driver.resolve("DAQmxStopTask")) == 0 || @|
  5694. (clearTask = (daqfp)driver.resolve("DAQmxClearTask")) == 0 || @|
  5695. (createChannel = (daqfp)driver.resolve("DAQmxCreateAIThrmcplChan"))
  5696. == 0 || @|
  5697. (setClock = (daqfp)driver.resolve("DAQmxCfgSampClkTiming")) == 0 || @|
  5698. (read = (daqfp)driver.resolve("DAQmxReadAnalogF64")) == 0 || @|
  5699. (errorInfo = (daqfp)driver.resolve("DAQmxGetExtendedErrorInfo")) ==
  5700. 0 || @|
  5701. (resetDevice = (daqfp)driver.resolve("DAQmxResetDevice")) == 0 ||
  5702. (waitForMeasurement = (daqfp)driver.resolve("DAQmxWaitUntilTaskDone")) == 0)
  5703. {
  5704. QMessageBox::critical(NULL, tr("Typica: Link error"),
  5705. tr("Failed to link a required symbol in NI-DAQmx."));
  5706. QApplication::quit();
  5707. }
  5708. }
  5709. }
  5710. DAQImplementation::~DAQImplementation()
  5711. {
  5712. driver.unload();
  5713. }
  5714. @ When exposing the |DAQ| class to the scripting engine, we need to provide a
  5715. constructor that can be called from a script and we need a way to call
  5716. |DAQ::newChannel()|. Other methods that are useful when called from a script are
  5717. made available automatically with the |Q_INVOKABLE| macro, however this does not
  5718. work for methods such as |newChannel()| which return a pointer to a |Channel|
  5719. object.
  5720. @<Function prototypes for scripting@>=
  5721. QScriptValue constructDAQ(QScriptContext *context, QScriptEngine *engine);
  5722. QScriptValue DAQ_newChannel(QScriptContext *context, QScriptEngine *engine);
  5723. void setDAQProperties(QScriptValue value, QScriptEngine *engine);
  5724. @ First we make these functions known to the scripting engine.
  5725. @<Set up the scripting engine@>=
  5726. constructor = engine->newFunction(constructDAQ);
  5727. value = engine->newQMetaObject(&DAQ::staticMetaObject, constructor);
  5728. engine->globalObject().setProperty("DAQ", value);
  5729. @ When creating a new |DAQ|, we make sure that it is owned by the script engine.
  5730. This is necessary to ensure that the destructor is called before \pn{} exits.
  5731. Just as the constructor requires an argument that specifies the device name, the
  5732. constructor available from a script also requires this argument.
  5733. @<Functions for scripting@>=
  5734. QScriptValue constructDAQ(QScriptContext *context, QScriptEngine *engine)
  5735. {
  5736. QScriptValue object;
  5737. if(context->argumentCount() == 1)
  5738. {
  5739. object = engine->newQObject(new DAQ(argument<QString>(0, context)),
  5740. QScriptEngine::ScriptOwnership);
  5741. setDAQProperties(object, engine);
  5742. }
  5743. else if(context->argumentCount() == 2)
  5744. {
  5745. object = engine->newQObject(new DAQ(argument<QString>(0, context),
  5746. argument<QString>(1, context)),
  5747. QScriptEngine::ScriptOwnership);
  5748. setDAQProperties(object, engine);
  5749. }
  5750. else
  5751. {
  5752. context->throwError("Incorrect number of arguments passed to DAQ"@|
  5753. "constructor. The DAQ constructor takes one"@|
  5754. "string as an argument specifying a device name."@|
  5755. "Example: Dev1");
  5756. }
  5757. return object;
  5758. }
  5759. @ As |DAQ| inherits |QObject|, we add the |newChannel()| property after adding
  5760. any |QObject| properties.
  5761. @<Functions for scripting@>=
  5762. void setDAQProperties(QScriptValue value, QScriptEngine *engine)
  5763. {
  5764. setQObjectProperties(value, engine);
  5765. value.setProperty("newChannel", engine->newFunction(DAQ_newChannel));
  5766. }
  5767. @ The |newChannel()| method method also requires that two arguments are provided
  5768. by the script.
  5769. @<Functions for scripting@>=
  5770. QScriptValue DAQ_newChannel(QScriptContext *context, QScriptEngine *engine)
  5771. {
  5772. DAQ *self = getself<@[DAQ *@]>(context);
  5773. QScriptValue object;
  5774. if(self)
  5775. {
  5776. object =
  5777. engine->newQObject(self->newChannel(argument<int>(0, context),@|
  5778. argument<int>(1, context)));
  5779. setChannelProperties(object, engine);
  5780. }
  5781. return object;
  5782. }
  5783. @ Sometimes it can be useful to test other parts of the program (for example,
  5784. when developing new scripts) when the DAQ hardware is not available. In these
  5785. cases, it is possible to temporarily use the |FakeDAQ| class. This class mimics
  5786. the |DAQ| class, but just makes up the measurements sent to the rest of the
  5787. program.
  5788. @<Class declarations@>=
  5789. class FakeDAQImplementation : public QThread@/
  5790. {@/
  5791. Q_OBJECT@;
  5792. public:@/
  5793. FakeDAQImplementation();
  5794. ~FakeDAQImplementation();
  5795. void run();
  5796. void measure();
  5797. QVector<Channel *> channelMap;
  5798. int channels;
  5799. bool ready;
  5800. double clockRate;
  5801. };@/
  5802. class FakeDAQ : public QObject@/
  5803. {@/
  5804. Q_OBJECT@;
  5805. FakeDAQImplementation *imp;
  5806. public:@/
  5807. FakeDAQ(QString device);
  5808. ~FakeDAQ();
  5809. Channel *newChannel(int units, int thermocouple);@/
  5810. @[Q_INVOKABLE@,@, void@]@, setClockRate(double Hz);@t\2\2@>@/
  5811. @[Q_INVOKABLE@,@, void@]@, start();@t\2\2@>@/
  5812. };
  5813. @ Just as in the |DAQ| class, most of the interesting stuff happens in
  5814. |measure()|. For each invokation of the method, we sleep for some amount of time
  5815. based on the clock rate then create a |Measurement| object at random for each
  5816. |Channel| that has been created.
  5817. @<FakeDAQ Implementation@>=
  5818. void FakeDAQImplementation::measure()
  5819. {
  5820. msleep((int)(1000/clockRate));
  5821. QTime time = QTime::currentTime();
  5822. for(int i = 0; i < channels; i++)
  5823. {
  5824. Measurement measure(qrand() % 500, time);
  5825. channelMap[i]->input(measure);
  5826. }
  5827. }
  5828. @ To call |measure|, we need to flesh out the rest of |FakeDAQImplementation|.
  5829. @<FakeDAQ Implementation@>=
  5830. void FakeDAQImplementation::run()
  5831. {
  5832. setPriority(QThread::TimeCriticalPriority);
  5833. while(ready)
  5834. {
  5835. measure();
  5836. }
  5837. }
  5838. FakeDAQImplementation::FakeDAQImplementation() : QThread(NULL), channelMap(4),
  5839. channels(0), ready(false), clockRate(1)@/
  5840. {
  5841. /* Nothing has to be done here. */
  5842. }
  5843. FakeDAQImplementation::~FakeDAQImplementation()
  5844. {
  5845. /* Nothing has to be done here. */
  5846. }
  5847. @ Next we need an implementation for the |FakeDAQ| class. This is simplified by
  5848. the fact that we are just using a random number generator to generate
  5849. measurements rather than special hardware for obtaining measurements.
  5850. @<FakeDAQ Implementation@>=
  5851. void FakeDAQ::start()
  5852. {
  5853. if(imp->ready)
  5854. {
  5855. imp->start();
  5856. }
  5857. }@#
  5858. FakeDAQ::FakeDAQ(QString) : imp(new FakeDAQImplementation())@t\2\2@>@/
  5859. {@t\1@>@/
  5860. imp->ready = true;@t\2@>@/
  5861. }@#
  5862. Channel* FakeDAQ::newChannel(int, int)
  5863. {
  5864. Channel *retval;
  5865. if(imp->ready)
  5866. {
  5867. retval = new Channel();
  5868. imp->channelMap[imp->channels] = retval;
  5869. imp->channels++;
  5870. }
  5871. else
  5872. {
  5873. return NULL;
  5874. }
  5875. return retval;
  5876. }
  5877. void FakeDAQ::setClockRate(double Hz)
  5878. {
  5879. if(imp->ready)
  5880. {
  5881. imp->clockRate = Hz;
  5882. }
  5883. }@#
  5884. FakeDAQ::~FakeDAQ()@t\2\2@>@/
  5885. {@t\1@>@/
  5886. imp->ready = false;
  5887. imp->wait(ULONG_MAX);
  5888. delete imp;@t\2@>@/
  5889. }
  5890. @ As the entire purpose of the |FakeDAQ| class is for testing purposes from
  5891. within the scripting engine, we need to make it available to the scripting
  5892. engine. This is done in a manner very similar to how the |DAQ| class is handled.
  5893. @<Function prototypes for scripting@>=
  5894. QScriptValue constructFakeDAQ(QScriptContext *context, QScriptEngine *engine);
  5895. QScriptValue FakeDAQ_newChannel(QScriptContext *context, QScriptEngine *engine);
  5896. void setFakeDAQProperties(QScriptValue value, QScriptEngine *engine);
  5897. @ The scripting engine is informed of the constructor.
  5898. @<Set up the scripting engine@>=
  5899. constructor = engine->newFunction(constructFakeDAQ);
  5900. value = engine->newQMetaObject(&FakeDAQ::staticMetaObject, constructor);
  5901. engine->globalObject().setProperty("FakeDAQ", value);
  5902. @ The constructor sets a property to allow calling |newChannel()| on a |FakeDAQ|
  5903. created from a script.
  5904. @<Functions for scripting@>=
  5905. QScriptValue constructFakeDAQ(QScriptContext *context,
  5906. QScriptEngine *engine)
  5907. {
  5908. QScriptValue object;
  5909. if(context->argumentCount() == 1)
  5910. {
  5911. object =
  5912. engine->newQObject(new FakeDAQ(argument<QString>(0, context)),
  5913. QScriptEngine::ScriptOwnership);
  5914. setFakeDAQProperties(object, engine);
  5915. }
  5916. else
  5917. {
  5918. context->throwError("Incorrect number of arguments passed to DAQ"@|
  5919. "constructor. The DAQ constructor takes one"@|
  5920. "string as an argument specifying a device name."@|
  5921. "Example: Dev1");
  5922. }
  5923. return object;
  5924. }
  5925. void setFakeDAQProperties(QScriptValue value, QScriptEngine *engine)
  5926. {
  5927. setQObjectProperties(value, engine);
  5928. value.setProperty("newChannel", engine->newFunction(FakeDAQ_newChannel));
  5929. }
  5930. QScriptValue FakeDAQ_newChannel(QScriptContext *context, QScriptEngine *engine)
  5931. {
  5932. FakeDAQ *self = getself<@[FakeDAQ *@]>(context);
  5933. QScriptValue object;
  5934. if(self)
  5935. {
  5936. object =
  5937. engine->newQObject(self->newChannel(argument<int>(0, context),@|
  5938. argument<int>(1, context)));
  5939. setChannelProperties(object, engine);
  5940. }
  5941. return object;
  5942. }
  5943. @* The Channel class.
  5944. \noindent |Channel| is a simple class. It is a subclass of |QObject| so it can
  5945. use Qt's signals and slots mechanism. Any object that is interested in
  5946. measurements from a channel can connect to the |newData| signal the channel
  5947. emits. Any number of objects can make this connection and each will receive a
  5948. copy of the measurement.
  5949. |Channel| objects should only be created by the |DAQ| class.
  5950. @<Class declarations@>=
  5951. class Channel : public QObject@;@/
  5952. {@t\1@>@/
  5953. Q_OBJECT@/
  5954. public:@;
  5955. Channel();
  5956. ~Channel();@/
  5957. @t\4@>public slots@t\kern-3pt@>:@;
  5958. void input(Measurement measurement);@/
  5959. signals:@;
  5960. void newData(Measurement);@t\2@>@/
  5961. };
  5962. @ The implementation of this class is trivial.
  5963. @<Channel Implementation@>=
  5964. Channel::Channel() : QObject(NULL)@/
  5965. {
  5966. /* Nothing has to be done here. */
  5967. }
  5968. Channel::~Channel()
  5969. {
  5970. /* Nothing has to be done here. */
  5971. }
  5972. void Channel::input(Measurement measurement)
  5973. {
  5974. emit newData(measurement);
  5975. }
  5976. @ A function is provided for use when a channel is created by a DAQ from a
  5977. script.
  5978. @<Function prototypes for scripting@>=
  5979. void setChannelProperties(QScriptValue value, QScriptEngine *engine);
  5980. @ The implementation is trivial.
  5981. @<Functions for scripting@>=
  5982. void setChannelProperties(QScriptValue value, QScriptEngine *engine)
  5983. {
  5984. setQObjectProperties(value, engine);
  5985. }
  5986. @* Calibration and Unit Conversion.
  5987. \noindent One of the planned features for \pn{} is support for hardware that
  5988. collects non-temperature measurements. This is frequently handled with analog
  5989. voltage signals which are proportional to some range in a meaningful unit. Some
  5990. hardware also requires calibration in software. In many cases both of these can
  5991. be handled at the same time with a single mapping in the form:
  5992. $$f(x) = L_1 + (x - L_2){U_1 - L_1\over{U_2 - L_2}}$$
  5993. \noindent where $L_1$ is the logical lower bound, $L_2$ is the measured lower
  5994. bound, $U_1$ is the logical upper bound, $U_2$ is the measured upper bound, and
  5995. $x$ is the value we wish to map from the range $\lbrack L_2, U_2 \rbrack$ to
  5996. the range $\lbrack L_1, U_1 \rbrack$.
  5997. Some use cases require a closed range but others require that this constraint
  5998. is loosened to allow extrapolation. Both are provided by this class.
  5999. @<Class declarations@>=
  6000. class LinearCalibrator : public QObject@/
  6001. {@/
  6002. @[Q_OBJECT@]@;
  6003. @[Q_PROPERTY(double measuredLower READ measuredLower
  6004. WRITE setMeasuredLower)@]@;
  6005. @[Q_PROPERTY(double measuredUpper READ measuredUpper
  6006. WRITE setMeasuredUpper)@]@;
  6007. @[Q_PROPERTY(double mappedLower READ mappedLower WRITE setMappedLower)@]@;
  6008. @[Q_PROPERTY(double mappedUpper READ mappedUpper WRITE setMappedUpper)@]@;
  6009. @[Q_PROPERTY(bool closedRange READ isClosedRange WRITE setClosedRange)@]@;
  6010. @[Q_PROPERTY(double sensitivity READ sensitivity WRITE setSensitivity)@]@;
  6011. public:@/
  6012. LinearCalibrator(QObject *parent = NULL);
  6013. double measuredLower();
  6014. double measuredUpper();
  6015. double mappedLower();
  6016. double mappedUpper();
  6017. bool isClosedRange();
  6018. double sensitivity();
  6019. @t\4@>@[public slots@t\kern-3pt@>:@]@;
  6020. void setMeasuredLower(double lower);
  6021. void setMeasuredUpper(double upper);
  6022. void setMappedLower(double lower);
  6023. void setMappedUpper(double upper);
  6024. void setClosedRange(bool closed);
  6025. void setSensitivity(double sensitivity);
  6026. void newMeasurement(Measurement measure);
  6027. @t\4@>@[signals:@]@;
  6028. void measurement(Measurement measure);
  6029. private:@/
  6030. double Lo1;
  6031. double Lo2;
  6032. double Up1;
  6033. double Up2;
  6034. double sensitivitySetting;
  6035. bool clamp;
  6036. };
  6037. @ When the measured range and the mapped range are identical and the range is
  6038. open, we have an identity mapping. This is the default state in a newly
  6039. constructed |LinearCalibrator| which should quickly be changed.
  6040. @<LinearCalibrator Implementation@>=
  6041. LinearCalibrator::LinearCalibrator(QObject *parent) :
  6042. QObject(parent), Lo1(0), Lo2(0), Up1(1), Up2(1), sensitivitySetting(0.0), clamp(false)@/
  6043. {
  6044. /* Nothing needs to be done here. */
  6045. }
  6046. @ The functional portion of the class is in the |newMeasurement()| slot. This
  6047. will receive measurements as they come in and emit a |measurement()| signal for
  6048. each with the calibration and unit adjustment performed.
  6049. This method also handles any rounding needed if there has been a call to
  6050. |setSensitivity()|.
  6051. @<LinearCalibrator Implementation@>=
  6052. void LinearCalibrator::newMeasurement(Measurement measure)
  6053. {
  6054. double outval = Lo1 + (measure.temperature() - Lo2) * (Up1 - Lo1)/(Up2 - Lo2);
  6055. if(clamp)
  6056. {
  6057. if(outval < Lo1)
  6058. {
  6059. outval = Lo1;
  6060. }
  6061. else if(outval > Up1)
  6062. {
  6063. outval = Up1;
  6064. }
  6065. }
  6066. if(sensitivitySetting >= 0.05)
  6067. {
  6068. int temp = qRound(outval/sensitivitySetting);
  6069. outval = temp * sensitivitySetting;
  6070. }
  6071. Measurement adjusted(outval, measure.time(), measure.scale());
  6072. emit measurement(adjusted);
  6073. }
  6074. @ The rest of the class consists of trivial accessor methods.
  6075. @<LinearCalibrator Implementation@>=
  6076. double LinearCalibrator::measuredLower()
  6077. {
  6078. return Lo2;
  6079. }
  6080. double LinearCalibrator::measuredUpper()
  6081. {
  6082. return Up2;
  6083. }
  6084. double LinearCalibrator::mappedLower()
  6085. {
  6086. return Lo1;
  6087. }
  6088. double LinearCalibrator::mappedUpper()
  6089. {
  6090. return Up1;
  6091. }
  6092. bool LinearCalibrator::isClosedRange()
  6093. {
  6094. return clamp;
  6095. }
  6096. void LinearCalibrator::setMeasuredLower(double lower)
  6097. {
  6098. Lo2 = lower;
  6099. }
  6100. void LinearCalibrator::setMeasuredUpper(double upper)
  6101. {
  6102. Up2 = upper;
  6103. }
  6104. void LinearCalibrator::setMappedLower(double lower)
  6105. {
  6106. Lo1 = lower;
  6107. }
  6108. void LinearCalibrator::setMappedUpper(double upper)
  6109. {
  6110. Up1 = upper;
  6111. }
  6112. void LinearCalibrator::setClosedRange(bool closed)
  6113. {
  6114. clamp = closed;
  6115. }
  6116. void LinearCalibrator::setSensitivity(double sensitivity)
  6117. {
  6118. sensitivitySetting = sensitivity;
  6119. }
  6120. double LinearCalibrator::sensitivity()
  6121. {
  6122. return sensitivitySetting;
  6123. }
  6124. @ Finally, we make this class available to the scripting engine. Two functions
  6125. are required for this.
  6126. @<Function prototypes for scripting@>=
  6127. QScriptValue constructLinearCalibrator(QScriptContext *context,
  6128. QScriptEngine *engine);
  6129. void setLinearCalibratorProperties(QScriptValue value, QScriptEngine *engine);
  6130. @ The scripting engine is informed of the constructor.
  6131. @<Set up the scripting engine@>=
  6132. constructor = engine->newFunction(constructLinearCalibrator);
  6133. value = engine->newQMetaObject(&LinearCalibrator::staticMetaObject,
  6134. constructor);
  6135. engine->globalObject().setProperty("LinearCalibrator", value);
  6136. @ The implementation of these functions is typical for this application.
  6137. @<Functions for scripting@>=
  6138. QScriptValue constructLinearCalibrator(QScriptContext *, QScriptEngine *engine)
  6139. {
  6140. QScriptValue object = engine->newQObject(new LinearCalibrator(NULL));
  6141. setLinearCalibratorProperties(object, engine);
  6142. return object;
  6143. }
  6144. void setLinearCalibratorProperties(QScriptValue value, QScriptEngine *engine)
  6145. {
  6146. setQObjectProperties(value, engine);
  6147. }
  6148. @* Linear Spline Interpolation.
  6149. \noindent While linear interpolation is adequate for many purposes, it fails
  6150. when a nonlinear mapping is required. The primary use case is to calibrate
  6151. multiple coffee roasters so that roast profiles can be shared among coffee
  6152. roasters with sufficiently similar heat transfer characteristics even if
  6153. differences in the measurement hardware result in different measured values.
  6154. By recording measured values at several points known to be equivalent due to
  6155. easily observable physical changes in the coffee it is possible to use linear
  6156. spline interpolation to produce a data series that approximates on one machine
  6157. the measurements that would have been produced at another. Acceptable results
  6158. may be available with surprisingly few data points.
  6159. It was originally suspected that cubic spline interpolation would produce a
  6160. more accurate mapping, but testing with linear spline interpolation produced
  6161. results good enough that more complex mappings were not needed. Cubic spline
  6162. interpolation may still be implemented in the future, but it is a low
  6163. priority.
  6164. @<Class declarations@>=
  6165. class LinearSplineInterpolator : public QObject
  6166. {
  6167. @[Q_OBJECT@]@/
  6168. public:@/
  6169. LinearSplineInterpolator(QObject *parent = NULL);
  6170. @[Q_INVOKABLE@]@, void add_pair(double source, double destination);
  6171. @[public slots@]:@/
  6172. void newMeasurement(Measurement measure);
  6173. @[signals@]:@/
  6174. void newData(Measurement measure);
  6175. private:@/
  6176. void make_interpolators();
  6177. QMap<double, double> *pairs;
  6178. QList<LinearCalibrator *> *interpolators;
  6179. };
  6180. @ We take advantage of the fact that iterating over a QMap always returns
  6181. entries in key order. When new measurement pairs are specified, the
  6182. interpolators are regenerated. There is significant room for performance
  6183. improvement.
  6184. @<LinearSplineInterpolator Implementation@>=
  6185. void LinearSplineInterpolator::add_pair(double source, double destination)
  6186. {
  6187. pairs->insert(source, destination);
  6188. make_interpolators();
  6189. }
  6190. void LinearSplineInterpolator::make_interpolators()
  6191. {
  6192. if(pairs->size() > 1)
  6193. {
  6194. while(interpolators->size() > 0)
  6195. {
  6196. LinearCalibrator *removed = interpolators->takeFirst();
  6197. removed->deleteLater();
  6198. }
  6199. QMap<double, double>::const_iterator i = pairs->constBegin();
  6200. QMap<double, double>::const_iterator j = i + 1;
  6201. while(j != pairs->constEnd())
  6202. {
  6203. LinearCalibrator *segment = new LinearCalibrator();
  6204. segment->setMeasuredLower(i.key());
  6205. segment->setMappedLower(i.value());
  6206. segment->setMeasuredUpper(j.key());
  6207. segment->setMappedUpper(j.value());
  6208. segment->setClosedRange(false);
  6209. interpolators->append(segment);
  6210. connect(segment, SIGNAL(measurement(Measurement)), this, SIGNAL(newData(Measurement)));
  6211. i++;
  6212. j++;
  6213. }
  6214. }
  6215. }
  6216. LinearSplineInterpolator::LinearSplineInterpolator(QObject *parent) :
  6217. QObject(parent), pairs(new QMap<double, double>),
  6218. interpolators(new QList<LinearCalibrator *>)
  6219. {
  6220. /* Nothing needs to be done here. */
  6221. }
  6222. void LinearSplineInterpolator::newMeasurement(Measurement measure)
  6223. {
  6224. QMap<double, double>::const_iterator i = pairs->constBegin();
  6225. int index = -1;
  6226. while(i != pairs->constEnd())
  6227. {
  6228. if(measure.temperature() <= i.key())
  6229. {
  6230. break;
  6231. }
  6232. i++;
  6233. index++;
  6234. }
  6235. if(index < 0)
  6236. {
  6237. index = 0;
  6238. }
  6239. if(index >= interpolators->size())
  6240. {
  6241. index = interpolators->size() - 1;
  6242. }
  6243. if(interpolators->at(index) != NULL)
  6244. {
  6245. interpolators->at(index)->newMeasurement(measure);
  6246. }
  6247. }
  6248. @ This is exposed to the scripting environment as usual.
  6249. @<Function prototypes for scripting@>=
  6250. QScriptValue constructLinearSplineInterpolator(QScriptContext *context, QScriptEngine *engine);
  6251. void setLinearSplineInterpolatorProperties(QScriptValue value, QScriptEngine *engine);
  6252. @ As usual.
  6253. @<Set up the scripting engine@>=
  6254. constructor = engine->newFunction(constructLinearSplineInterpolator);
  6255. value = engine->newQMetaObject(&LinearSplineInterpolator::staticMetaObject, constructor);
  6256. engine->globalObject().setProperty("LinearSplineInterpolator", value);
  6257. @ And again as usual.
  6258. @<Functions for scripting@>=
  6259. QScriptValue constructLinearSplineInterpolator(QScriptContext *, QScriptEngine *engine)
  6260. {
  6261. QScriptValue object = engine->newQObject(new LinearSplineInterpolator(NULL));
  6262. setLinearSplineInterpolatorProperties(object, engine);
  6263. return object;
  6264. }
  6265. void setLinearSplineInterpolatorProperties(QScriptValue value, QScriptEngine *engine)
  6266. {
  6267. setQObjectProperties(value, engine);
  6268. }
  6269. @* The TemperatureDisplay class.
  6270. Now that measurements have been generated by the |DAQ| and passed to a
  6271. |Channel|, any object that is interested in these measurements can connect to
  6272. the channel and use the measurements it sends out. So far, the time on each
  6273. measurement is the time at which it was collected. Unfortunately, this is often
  6274. not what we want. It is more useful to have the time relative to some other
  6275. point in time such as the start of the batch.
  6276. Until the measurement time is adjusted, the measurements are really only useful
  6277. to classes that do not care about the measurement time. The |TemperatureDisplay|
  6278. class is such a class. It receives measurements and displays the most recently
  6279. measured temperature.
  6280. This is a specialization of |QLCDNumber|.
  6281. @<Class declarations@>=
  6282. class TemperatureDisplay : public QLCDNumber@/
  6283. {@t\1@>@/
  6284. Q_OBJECT@;
  6285. Q_ENUMS(DisplayUnits)
  6286. int unit;
  6287. public:@/
  6288. enum DisplayUnits
  6289. {
  6290. Auto = -1,
  6291. Fahrenheit = 10144,
  6292. Celsius = 10143,
  6293. Kelvin = 10325,
  6294. Rankine = 10145
  6295. };
  6296. TemperatureDisplay(QWidget *parent = NULL);
  6297. ~TemperatureDisplay();@/
  6298. @t\4@>public slots@t\kern-3pt@>:@/
  6299. void setValue(Measurement temperature);
  6300. void invalidate();
  6301. void setDisplayUnits(DisplayUnits scale);@t\2@>@/
  6302. };
  6303. @ Displaying a temperature is a simple matter of taking the temperature
  6304. component from the measurement and converting it to a string. Presently, this
  6305. code assumes that the measurements are in degrees Fahrenheit. If the code
  6306. becomes smarter about measurement units it might be a good idea to change this.
  6307. |QLCDNumber| is capable of displaying more than just numbers, so the call to
  6308. display takes a string which in this case consists of the temperature to the
  6309. $1\over100$th of a degree and might be followed by ' which will be converted to
  6310. $^\circ$ and the letter F, C, or r to indicate the unit. This class should be
  6311. mofified to allow a user specified precision.
  6312. @<TemperatureDisplay Implementation@>=
  6313. void TemperatureDisplay::setValue(Measurement temperature)
  6314. {
  6315. QString number;
  6316. switch(unit)
  6317. {
  6318. case Auto:
  6319. switch(temperature.scale())
  6320. {
  6321. case Fahrenheit:
  6322. display(QString("%1'F").
  6323. arg(number.setNum(temperature.temperature(), 'f', 2)));
  6324. break;
  6325. case Celsius:
  6326. display(QString("%1'C").
  6327. arg(number.setNum(temperature.temperature(), 'f', 2)));
  6328. break;
  6329. case Kelvin:
  6330. display(QString("%1").
  6331. arg(number.setNum(temperature.temperature(), 'f', 2)));
  6332. break;
  6333. case Rankine:
  6334. display(QString("%1'r").
  6335. arg(number.setNum(temperature.temperature(), 'f', 2)));
  6336. break;
  6337. }
  6338. break;
  6339. case Fahrenheit:
  6340. display(QString("%1'F").
  6341. arg(number.setNum(temperature.toFahrenheit().temperature(), 'f',
  6342. 2)));
  6343. break;
  6344. case Celsius:
  6345. display(QString("%1'C").
  6346. arg(number.setNum(temperature.toCelsius().temperature(), 'f',
  6347. 2)));
  6348. break;
  6349. case Kelvin:
  6350. display(QString("%1").
  6351. arg(number.setNum(temperature.toKelvin().temperature(), 'f',
  6352. 2)));
  6353. break;
  6354. case Rankine:
  6355. display(QString("%1'r").
  6356. arg(number.setNum(temperature.toRankine().temperature(), 'f',
  6357. 2)));
  6358. break;
  6359. }
  6360. }
  6361. @ Before measurements are displayed, we set a more sensible default display
  6362. style and an initial string. These defaults can all be overridden with calls to
  6363. the usual |QLCDNumber| methods.
  6364. \medskip
  6365. \resizebox*{6.3in}{!}{\includegraphics{QLCDNumber.png}}
  6366. \smallskip
  6367. \centerline{Figure \secno: Outline (Qt default) and Filled |QLCDNumber| Example}
  6368. \medskip
  6369. @<TemperatureDisplay Implementation@>=
  6370. TemperatureDisplay::TemperatureDisplay(QWidget *parent) :
  6371. QLCDNumber(8, parent), unit(Auto)@/
  6372. {
  6373. setSegmentStyle(Filled);
  6374. display("---.--'F");
  6375. }
  6376. @ While it is not currently used, it would be good to allow an error state to
  6377. be easily discernible from a very stable temperature. Currently, if an error
  6378. occurs that results in the measurement thread exiting, no new measurements will
  6379. be generated and the temperature display will continue to read the most recent
  6380. measured value. If an error signal were emitted, it could be connected to the
  6381. following code to change the display to reflect the fact that the current
  6382. temperature is unknown.
  6383. @<TemperatureDisplay Implementation@>=
  6384. void TemperatureDisplay::invalidate()
  6385. {
  6386. display("---.--'F");
  6387. }
  6388. @ \pn{} supports the display of multiple types of unit. Typically, we use the
  6389. Auto scale which will cause |TemperatureDisplay| objects to display measurements
  6390. in whichever scale the measurement is associated with. Alternately, we can fix
  6391. the scale to a different supported scale and convert measurements to that scale
  6392. prior to display.
  6393. @<TemperatureDisplay Implementation@>=
  6394. void TemperatureDisplay::setDisplayUnits(DisplayUnits scale)
  6395. {
  6396. unit = scale;
  6397. }
  6398. @ All that is left to deal with is the empty destructor.
  6399. @<TemperatureDisplay Implementation@>=
  6400. TemperatureDisplay::~TemperatureDisplay()
  6401. {
  6402. /* Nothing has to be done here. */
  6403. }
  6404. @ To use a |TemperatureDisplay| from a script, we need a function to pass a new
  6405. object to the scripting engine.
  6406. @<Function prototypes for scripting@>=
  6407. QScriptValue constructTemperatureDisplay(QScriptContext *context,
  6408. QScriptEngine *engine);
  6409. void setTemperatureDisplayProperties(QScriptValue value, QScriptEngine *engine);
  6410. @ The scripting engine must be informed of this function.
  6411. @<Set up the scripting engine@>=
  6412. constructor = engine->newFunction(constructTemperatureDisplay);
  6413. value = engine->newQMetaObject(&TemperatureDisplay::staticMetaObject,
  6414. constructor);
  6415. engine->globalObject().setProperty("TemperatureDisplay", value);
  6416. @ The constructor is trivial.
  6417. @<Functions for scripting@>=
  6418. QScriptValue constructTemperatureDisplay(QScriptContext *,
  6419. QScriptEngine *engine)
  6420. {
  6421. QScriptValue object = engine->newQObject(new TemperatureDisplay);
  6422. setTemperatureDisplayProperties(object, engine);
  6423. return object;
  6424. }
  6425. void setTemperatureDisplayProperties(QScriptValue value, QScriptEngine *engine)
  6426. {
  6427. setQLCDNumberProperties(value, engine);
  6428. }
  6429. @* The MeasurementTimeOffset class.
  6430. When a |DAQ| object creates a |Measurement| object, the time component is a
  6431. system time. In most cases, the system time is not interesting and a more useful
  6432. time would be relative to the start of a process. This class should be used as a
  6433. filter, taking measurements with a system time stamp and producing measurements
  6434. with a relative time.
  6435. @<Class declarations@>=
  6436. class MeasurementTimeOffset : public QObject@/
  6437. {@t\1@>@/
  6438. Q_OBJECT@;
  6439. QTime epoch;
  6440. QTime previous;
  6441. bool hasPrevious;@/
  6442. public:@;
  6443. MeasurementTimeOffset(QTime zero);
  6444. QTime zeroTime();@/
  6445. @t\4@>public slots@t\kern-3pt@>:@;
  6446. void newMeasurement(Measurement measure);
  6447. void setZeroTime(QTime zero);
  6448. signals:@;
  6449. void measurement(Measurement measure);@t\2@>@/
  6450. }@t\kern-3pt@>;
  6451. @ The interesting part of this class is the function which takes a measurement
  6452. with a system time and produces a new measurement with a time relative to some
  6453. start time.
  6454. When using this class, it is possible that a measurement will arrive with a time
  6455. slightly before a newly chosen epoch. In such a case we do not want to simply
  6456. subtract the epoch from the measurement time as other classes will interpret
  6457. this incorrectly as a measurement time slightly less than 1 hour. This means
  6458. that we need to check if the measurement time is before the epoch. If it is, we
  6459. consider it to have been generated at the epoch rather than before. Aren't race
  6460. conditions fun?
  6461. Additionally, since we're only getting time of day information, some special
  6462. handling must be done for time series that cross the boundary between days. We
  6463. should never get measurements out of order, so keeping a record of the previous
  6464. measurement and verifying that the new measurement comes after it is sufficient.
  6465. @<MeasurementTimeOffset Implementation@>=
  6466. void MeasurementTimeOffset::newMeasurement(Measurement measure)@t\2\2@>@/
  6467. {@t\1@>@/
  6468. if(measure.time() < epoch)@/
  6469. {
  6470. if(hasPrevious)@/
  6471. {
  6472. QTime jitBase(epoch.hour() - 1, epoch.minute(), epoch.second(),
  6473. epoch.msec());
  6474. QTime jitComp(epoch.hour(), measure.time().minute(),
  6475. measure.time().second(), measure.time().msec());
  6476. int relTime = jitBase.msecsTo(jitComp);
  6477. @<Produce and emit relative time@>@;
  6478. }
  6479. else@/
  6480. {
  6481. Measurement rel(measure.temperature(), QTime(0, 0, 0, 0));
  6482. emit measurement(rel);
  6483. }
  6484. }
  6485. else@/
  6486. {
  6487. int relTime = epoch.msecsTo(measure.time());
  6488. @<Produce and emit relative time@>@;
  6489. }
  6490. hasPrevious = true;
  6491. previous = measure.time();@t\2@>@/
  6492. }
  6493. @ The measurement emitted has a time with the number of minutes, seconds, and
  6494. milliseconds since the start of the batch. We never generate a time greater
  6495. than 1 hour.
  6496. @<Produce and emit relative time@>=
  6497. QTime newTime(0, 0, 0, 0);
  6498. newTime = newTime.addMSecs(relTime);
  6499. if(newTime.hour() > 0)
  6500. {
  6501. newTime.setHMS(0, newTime.minute(), newTime.second(), newTime.msec());
  6502. }
  6503. Measurement rel(measure.temperature(), newTime);
  6504. emit measurement(rel);
  6505. @ The rest of the code handles updating and reporting the reference time.
  6506. @<MeasurementTimeOffset Implementation@>=
  6507. MeasurementTimeOffset::MeasurementTimeOffset(QTime zero) : epoch(zero),
  6508. previous(0, 0, 0, 0), hasPrevious(false)
  6509. {
  6510. /* Nothing has to be done here. */
  6511. }
  6512. QTime MeasurementTimeOffset::zeroTime()
  6513. {
  6514. return epoch;
  6515. }
  6516. void MeasurementTimeOffset::setZeroTime(QTime zero)
  6517. {
  6518. epoch = zero;
  6519. hasPrevious = false;
  6520. }
  6521. @ Two functions are required to make this class available to the scripting
  6522. engine.
  6523. @<Function prototypes for scripting@>=
  6524. QScriptValue constructMeasurementTimeOffset(QScriptContext *context,@|
  6525. QScriptEngine *engine);
  6526. void setMeasurementTimeOffsetProperties(QScriptValue value,
  6527. QScriptEngine *engine);
  6528. @ The scripting engine must be informed of the constructor.
  6529. @<Set up the scripting engine@>=
  6530. constructor = engine->newFunction(constructMeasurementTimeOffset);
  6531. value = engine->newQMetaObject(&MeasurementTimeOffset::staticMetaObject,
  6532. constructor);
  6533. engine->globalObject().setProperty("MeasurementTimeOffset", value);
  6534. @ Previously, another property was added to the newly created object. That
  6535. method is believed to be obsolete and has been removed. Careful testing will
  6536. need to be done to verify that this decision was sane. I was very hungry when
  6537. that change was made.
  6538. @<Functions for scripting@>=
  6539. QScriptValue constructMeasurementTimeOffset(QScriptContext *,
  6540. QScriptEngine *engine)
  6541. {
  6542. QScriptValue object =@|
  6543. engine->newQObject(new MeasurementTimeOffset(QTime::currentTime()));
  6544. setMeasurementTimeOffsetProperties(object, engine);
  6545. return object;
  6546. }
  6547. void setMeasurementTimeOffsetProperties(QScriptValue value,
  6548. QScriptEngine *engine)
  6549. {
  6550. setQObjectProperties(value, engine);
  6551. }
  6552. @* Measured value threshold detection.
  6553. \noindent There are times when one might want to detect when a measured value
  6554. from a data series has passed a given value, with the limitation that we are
  6555. only interested in the ascending or descending edge. This can be used, for
  6556. example, to translate roast profile data in a graph along the time axis such
  6557. that the bean temperature series are aligned at a given
  6558. temperature.\nfnote{More details on the reasoning behind why one might want
  6559. to do this are provided at:\par\indent\pdfURL{http://youtu.be/hS0SfzypyFQ}
  6560. {http://youtu.be/hS0SfzypyFQ}} For this we can use a |ThresholdDetector|.
  6561. If we would like to catch changes on both the ascending and descending edge, we
  6562. can use two objects, however it may be a good idea to use more than two to
  6563. allow for sane behavior in the face of hysteresis.
  6564. @<Class declarations@>=
  6565. class ThresholdDetector : public QObject@/
  6566. {
  6567. @[Q_OBJECT@]@;
  6568. @[Q_ENUMS(EdgeDirection)@]@;
  6569. public:@/
  6570. enum EdgeDirection {
  6571. Ascending, Descending
  6572. };
  6573. ThresholdDetector(double value);
  6574. @[public slots@]:@/
  6575. void newMeasurement(Measurement measure);
  6576. void setThreshold(double value);
  6577. void setEdgeDirection(EdgeDirection direction);
  6578. signals:@/
  6579. void timeForValue(double);
  6580. private:@/
  6581. double previousValue;
  6582. double threshold;
  6583. EdgeDirection currentDirection;
  6584. };
  6585. @ This class emits the time in seconds when a given measurement crosses the
  6586. threshold value in the appropriate direction.
  6587. @<ThresholdDetector Implementation@>=
  6588. void ThresholdDetector::newMeasurement(Measurement measure)
  6589. {
  6590. if((currentDirection == Ascending && previousValue < threshold &&
  6591. previousValue >= 0) || (currentDirection == Descending &&
  6592. previousValue > threshold && previousValue >= 0))
  6593. {
  6594. if((currentDirection == Ascending && measure.temperature() >= threshold) ||
  6595. (currentDirection == Descending && measure.temperature() <= threshold))
  6596. {
  6597. double offset = measure.time().hour() * 60 * 60;
  6598. offset += measure.time().minute() * 60;
  6599. offset += measure.time().second();
  6600. offset += measure.time().msec()/1000;
  6601. emit timeForValue(offset);
  6602. }
  6603. }
  6604. previousValue = measure.temperature();
  6605. }
  6606. ThresholdDetector::ThresholdDetector(double value) : QObject(NULL),
  6607. previousValue(-1), threshold(value), currentDirection(Ascending)
  6608. {
  6609. /* Nothing needs to be done here. */
  6610. }
  6611. void ThresholdDetector::setThreshold(double value)
  6612. {
  6613. threshold = value;
  6614. }
  6615. void ThresholdDetector::setEdgeDirection(EdgeDirection direction)
  6616. {
  6617. currentDirection = direction;
  6618. }
  6619. @ This is exposed to the host environment.
  6620. @<Function prototypes for scripting@>=
  6621. QScriptValue constructThresholdDetector(QScriptContext *context, QScriptEngine *engine);
  6622. void setThresholdDetectorProperties(QScriptValue value, QScriptEngine *engine);
  6623. @ Inform the engine of the constructor.
  6624. @<Set up the scripting engine@>=
  6625. constructor = engine->newFunction(constructThresholdDetector);
  6626. value = engine->newQMetaObject(&ThresholdDetector::staticMetaObject, constructor);
  6627. engine->globalObject().setProperty("ThresholdDetector", value);
  6628. @ Implementation. At present I'm not bothering to implement constructor
  6629. arguments here and am aligning on a fixed point. Another slot method was added
  6630. to restore adjustability.
  6631. @<Functions for scripting@>=
  6632. QScriptValue constructThresholdDetector(QScriptContext *, QScriptEngine *engine)
  6633. {
  6634. QScriptValue object = engine->newQObject(new ThresholdDetector(300));
  6635. return object;
  6636. }
  6637. void setThresholdDetectorProperties(QScriptValue value, QScriptEngine *engine)
  6638. {
  6639. setQObjectProperties(value, engine);
  6640. }
  6641. @* The ZeroEmitter class.
  6642. \noindent Now that it is possible to record the time a measurement was taken
  6643. relative to an arbitrary start time, there is a minor problem left for logging.
  6644. It is extremely unlikely that a measurement will be passed through at the epoch.
  6645. For this, what we want to do is save the previous measurement and make it
  6646. available at time 0 whenever the start time is reset. This is the role of the
  6647. |ZeroEmitter| class.
  6648. Another problem is that most classes that are interested in a relative time are
  6649. also interested in logging multiple sets of temperature data. To facilitate this
  6650. an integer is emitted. Different temperature measurement sources should be set
  6651. to emit different numbers. A table view would place measurements in the
  6652. indicated column. A graph view would use different colors to plot different sets
  6653. of data.
  6654. @<Class declarations@>=
  6655. class ZeroEmitter : public QObject@/
  6656. {@t\1@>@/
  6657. Q_OBJECT@;
  6658. int col;
  6659. double temp;
  6660. public:@/
  6661. ZeroEmitter(int tempcolumn);
  6662. int column();
  6663. double lastTemperature();@/
  6664. @t\4@>public slots@t\kern-3pt@>:@;
  6665. void newMeasurement(Measurement measure);
  6666. void setColumn(int column);
  6667. void emitZero();
  6668. signals:@;
  6669. void measurement(Measurement measure, int tempcolumn);@t\2@>@/
  6670. }@t\kern-3pt@>;
  6671. @ The implementation of the class is trivial.
  6672. @<ZeroEmitter Implementation@>=
  6673. ZeroEmitter::ZeroEmitter(int tempcolumn) : QObject(NULL), col(tempcolumn),
  6674. temp(0)@;
  6675. {
  6676. /* Nothing has to be done here. */
  6677. }
  6678. int ZeroEmitter::column()
  6679. {
  6680. return col;
  6681. }
  6682. double ZeroEmitter::lastTemperature()
  6683. {
  6684. return temp;
  6685. }
  6686. void ZeroEmitter::newMeasurement(Measurement measure)
  6687. {
  6688. temp = measure.temperature();
  6689. }
  6690. void ZeroEmitter::setColumn(int column)
  6691. {
  6692. col = column;
  6693. }
  6694. void ZeroEmitter::emitZero()
  6695. {
  6696. emit measurement(Measurement(temp, QTime(0, 0, 0, 0)), col);
  6697. }
  6698. @ Making this class available to scripts requires only two functions.
  6699. @<Function prototypes for scripting@>=
  6700. QScriptValue constructZeroEmitter(QScriptContext *context,
  6701. QScriptEngine *engine);
  6702. void setZeroEmitterProperties(QScriptValue value, QScriptEngine *engine);
  6703. @ To use it, we must inform the engine of the constructor.
  6704. @<Set up the scripting engine@>=
  6705. constructor = engine->newFunction(constructZeroEmitter);
  6706. value = engine->newQMetaObject(&ZeroEmitter::staticMetaObject, constructor);
  6707. engine->globalObject().setProperty("ZeroEmitter", value);
  6708. @ The implementation of the constructor is trivial.
  6709. @<Functions for scripting@>=
  6710. QScriptValue constructZeroEmitter(QScriptContext *context,
  6711. QScriptEngine *engine)
  6712. {
  6713. QScriptValue object =
  6714. engine->newQObject(new ZeroEmitter(argument<int>(0, context)));
  6715. setZeroEmitterProperties(object, engine);
  6716. return object;
  6717. }
  6718. void setZeroEmitterProperties(QScriptValue value, QScriptEngine *engine)
  6719. {
  6720. setQObjectProperties(value, engine);
  6721. }
  6722. @* The MeasurementAdapter class.
  6723. \noindent The last of the measurement filter classes is the |MeasurementAdapter|
  6724. class. This takes measurements, typically from a |MeasurementTimeOffset|, and
  6725. sends the measurement out with a number to indicate which data series the
  6726. measurement belongs to.
  6727. The measurement pipeline could probably be made simpler by introducing a series
  6728. identifier into the measurement class.
  6729. @<Class declarations@>=
  6730. class MeasurementAdapter : public QObject@/
  6731. {@t\1@>@/
  6732. Q_OBJECT@;
  6733. int col;
  6734. public:@/
  6735. MeasurementAdapter(int tempcolumn);
  6736. int column();@/
  6737. @t\4@>public slots@t\kern-3pt@>:@/
  6738. void newMeasurement(Measurement measure);
  6739. void setColumn(int column);
  6740. signals:@/
  6741. void measurement(Measurement measure, int tempcolumn);@t\2@>@/
  6742. }@t\kern-3pt@>;
  6743. @ The implementation of this filter class is trivial.
  6744. @<MeasurementAdapter Implementation@>=
  6745. MeasurementAdapter::MeasurementAdapter(int tempcolumn) : col(tempcolumn)@;
  6746. {
  6747. /* Nothing has to be done here. */
  6748. }
  6749. int MeasurementAdapter::column()
  6750. {
  6751. return col;
  6752. }
  6753. void MeasurementAdapter::newMeasurement(Measurement measure)
  6754. {
  6755. emit measurement(measure, col);
  6756. }
  6757. void MeasurementAdapter::setColumn(int column)
  6758. {
  6759. col = column;
  6760. }
  6761. @ This filter class is also available from the host environment.
  6762. @<Function prototypes for scripting@>=
  6763. QScriptValue constructMeasurementAdapter(QScriptContext *context,
  6764. QScriptEngine *engine);
  6765. void setMeasurementAdapterProperties(QScriptValue value, QScriptEngine *engine);
  6766. @ As usual, the engine must be informed of the constructor.
  6767. @<Set up the scripting engine@>=
  6768. constructor = engine->newFunction(constructMeasurementAdapter);
  6769. value = engine->newQMetaObject(&MeasurementAdapter::staticMetaObject,
  6770. constructor);
  6771. engine->globalObject().setProperty("MeasurementAdapter", value);
  6772. @ The implementation is trivial.
  6773. @<Functions for scripting@>=
  6774. QScriptValue constructMeasurementAdapter(QScriptContext *context,
  6775. QScriptEngine *engine)
  6776. {
  6777. QScriptValue object =
  6778. engine->newQObject(new MeasurementAdapter(argument<int>(0, context)));
  6779. setMeasurementAdapterProperties(object, engine);
  6780. return object;
  6781. }
  6782. void setMeasurementAdapterProperties(QScriptValue value, QScriptEngine *engine)
  6783. {
  6784. setQObjectProperties(value, engine);
  6785. }
  6786. @* A graph of temperature over time.
  6787. \noindent A useful tool when roasting is a visual depiction of the current batch
  6788. as it happens, possibly laid over a previously recorded target profile. The
  6789. |GraphView| class can take multiple sets of temperature data and produce such a
  6790. visualization.
  6791. \medskip
  6792. \centerline{\includegraphics{roast}}
  6793. \smallskip
  6794. \centerline{Figure \secno: A Typical Roast}
  6795. \medskip
  6796. This class assumes that temperature data will be passed in the correct order.
  6797. @<Class declarations@>=
  6798. class GraphView : public QGraphicsView@/
  6799. {@t\1@>@/
  6800. Q_OBJECT@;
  6801. QGraphicsScene *theScene;@/
  6802. QMap<int, QList<QGraphicsLineItem * > * > *graphLines;@/
  6803. QMap<int, QPointF> *prevPoints;
  6804. QMap<int, double> *translations;
  6805. QList<QGraphicsItem *> *gridLinesF;
  6806. QList<QGraphicsItem *> *gridLinesC;@/
  6807. public:@/
  6808. GraphView(QWidget *parent = NULL);
  6809. void removeSeries(int column);@/
  6810. protected:@/
  6811. void resizeEvent(QResizeEvent *event);@/
  6812. @t\4@>public slots@t\kern-3pt@>:@/
  6813. void newMeasurement(Measurement measure, int tempcolumn);
  6814. void setSeriesTranslation(int column, double offset);
  6815. void clear();
  6816. void showF();
  6817. void showC();@t\2@>@/
  6818. }@t\kern-3pt@>;
  6819. @ I decided that it would probably be best to keep the graph area the same even
  6820. with different roast lengths over different temperature ranges so that similar
  6821. portions between these graphs would continue to look similar rather than
  6822. constantly attempting to select the best way to display the data currently in
  6823. the view.
  6824. I have chosen to represent roasting times of up to 20 minutes and temperatures
  6825. between 0 and 500$^\circ$ Fahrenheit. This should certainly be configurable at
  6826. run time, but until that is implemented, roasters who routinely roast batches
  6827. for longer periods of time will want to change the constructor. This class
  6828. should probably be modified to allow the user to specify several characteristics
  6829. of the display.
  6830. This class must also deal with the fact that coordinates in a |QGraphicsScene|
  6831. are not quite the same as coordinates in a cartesian plane. The easiest way to
  6832. deal with this is to negate the y coordinate and translate the viewport to the
  6833. area we draw in.
  6834. A small margin area left around the edges of the graph. This should probably be
  6835. configurable for those with particularly small displays.
  6836. @<GraphView Implementation@>=
  6837. GraphView::GraphView(QWidget *parent) : QGraphicsView(parent),
  6838. theScene(new QGraphicsScene),@/
  6839. graphLines(new QMap<int, QList<QGraphicsLineItem *> *>),@/
  6840. prevPoints(new QMap<int, QPointF>),
  6841. translations(new QMap<int, double>),
  6842. gridLinesF(new QList<QGraphicsItem *>),
  6843. gridLinesC(new QList<QGraphicsItem *>)@/
  6844. {
  6845. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  6846. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  6847. setScene(theScene);
  6848. setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
  6849. @<Draw temperature axis and grid lines@>;
  6850. @<Draw time axis and ticks@>;
  6851. fitInView(theScene->sceneRect().adjusted(-50,-50,50,50));
  6852. }
  6853. @ Grid lines are drawn every 100 degrees. These lines are labeled with
  6854. |setHtml()| for convenient access to the $^\circ$ symbol. If \pn{} is modified
  6855. to allow different units, this code should also be modified.
  6856. As of version 1.3.3 it is possible to switch the graph between degrees
  6857. Fahrenheit and degrees Celcius. Celcius grid lines are drawn but initially
  6858. hidden. Both the grid lines and the labels are added to a list depending on the
  6859. unit so that when changing from one view to another all that needs to happen is
  6860. hide one list of items and show another.
  6861. @<Draw temperature axis and grid lines@>=
  6862. QGraphicsLineItem *tempaxis = new QGraphicsLineItem;
  6863. tempaxis->setLine(-10, -500, -10, 0);
  6864. theScene->addItem(tempaxis);
  6865. QGraphicsLineItem *gridLine;
  6866. QGraphicsTextItem *label;
  6867. for(int y = -100; y > -600; y -= 100)@/
  6868. {@/
  6869. gridLine = new QGraphicsLineItem;
  6870. gridLine->setLine(0, y, 1200, y);
  6871. theScene->addItem(gridLine);
  6872. label = new QGraphicsTextItem;
  6873. label->setHtml(QString("%1&deg;F").arg(-y));
  6874. label->setPos(-55, y - (label->boundingRect().height() / 2));
  6875. theScene->addItem(label);
  6876. gridLinesF->append(gridLine);
  6877. gridLinesF->append(label);
  6878. }
  6879. for(int degC = 50; degC <= 250; degC += 50)
  6880. {
  6881. gridLine = new QGraphicsLineItem;
  6882. int y = -(degC * (9.0/5.0) + 32);
  6883. gridLine->setLine(0, y, 1200, y);
  6884. gridLine->hide();
  6885. theScene->addItem(gridLine);
  6886. gridLinesC->append(gridLine);
  6887. label = new QGraphicsTextItem;
  6888. label->setHtml(QString("%1&deg;C").arg(degC));
  6889. label->setPos(-55, y - (label->boundingRect().height() / 2));
  6890. label->hide();
  6891. theScene->addItem(label);
  6892. gridLinesC->append(label);
  6893. }
  6894. @ Two slots are used to switch between the different sets of grid lines.
  6895. @<GraphView Implementation@>=
  6896. void GraphView::showF()
  6897. {
  6898. for(int i = 0; i < gridLinesF->size(); i++)
  6899. {
  6900. gridLinesF->at(i)->show();
  6901. }
  6902. for(int i = 0; i < gridLinesC->size(); i++)
  6903. {
  6904. gridLinesC->at(i)->hide();
  6905. }
  6906. }
  6907. void GraphView::showC()
  6908. {
  6909. for(int i = 0; i < gridLinesF->size(); i++)
  6910. {
  6911. gridLinesF->at(i)->hide();
  6912. }
  6913. for(int i = 0; i < gridLinesC->size(); i++)
  6914. {
  6915. gridLinesC->at(i)->show();
  6916. }
  6917. }
  6918. @ The time axis has a tick every two minutes. The use of the |?| tertiary
  6919. operator shifts the labels with two digits a little more than labels with only
  6920. one digit. If it worked, a more resilient approach would be to take the width of
  6921. the label and center it under the tick.
  6922. @<Draw time axis and ticks@>=
  6923. QGraphicsLineItem *timeaxis = new QGraphicsLineItem;
  6924. timeaxis->setLine(0, 10, 1200, 10);
  6925. theScene->addItem(timeaxis);
  6926. for(int x = 0; x < 1201; x += 120)@/
  6927. {@/
  6928. QGraphicsLineItem *tick = new QGraphicsLineItem;
  6929. tick->setLine(x, 0, x, 20);
  6930. theScene->addItem(tick);
  6931. QGraphicsTextItem *label = new QGraphicsTextItem;
  6932. label->setPlainText(QString("%1").arg(x/60));
  6933. label->setPos(x - (label->boundingRect().width() / 2), 20);
  6934. theScene->addItem(label);
  6935. }
  6936. @ Typically, the user will be able to resize the graph. When the widget is
  6937. resized, we should fit the graph to the new size of the widget. This is safe to
  6938. do as we have already turned off the scroll bars.
  6939. @<GraphView Implementation@>=
  6940. void GraphView::resizeEvent(QResizeEvent *)
  6941. {
  6942. fitInView(theScene->sceneRect().adjusted(-50,-50,50,50));
  6943. }
  6944. @ When adding a new measurement, there are three cases that should be
  6945. considered. In the case of the first measurement, no drawing occurs. A |QList|
  6946. of line items is initialized when the second measurement is taken. Subsequent
  6947. measurements are able to simply append new line segments to the list.
  6948. @<GraphView Implementation@>=
  6949. #define FULLTIMETOINT(t) (t.msec() + (t.second() * 1000) + (t.minute() * 60 * 1000))
  6950. void GraphView::newMeasurement(Measurement measure, int tempcolumn)@/
  6951. {@/
  6952. double offset = 0;
  6953. if(translations->contains(tempcolumn))
  6954. {
  6955. offset = translations->value(tempcolumn);
  6956. }
  6957. if(prevPoints->contains(tempcolumn))@/
  6958. @t\1@>{@/
  6959. @<At least one measurement exists@>@;
  6960. if(graphLines->contains(tempcolumn))@/
  6961. {@t\1@>
  6962. /* More than one measurement existed. */
  6963. graphLines->value(tempcolumn)->append(segment);@t\2@>@/
  6964. }@/
  6965. else@/
  6966. {@/
  6967. /* This is the second measurement. */
  6968. QList<QGraphicsLineItem *> *newLine =
  6969. new QList<QGraphicsLineItem *>;@/
  6970. newLine->append(segment);
  6971. graphLines->insert(tempcolumn, newLine);
  6972. }@t\2@>@/
  6973. }@/
  6974. else@/
  6975. {@/
  6976. @<Handle the first measurement@>@;
  6977. }
  6978. }
  6979. @ There are some parts of the code that are correct, but seem somewhat goofy.
  6980. This is especially true surrounding the graphics view architecture as this was
  6981. not working correctly when I wrote the code that uses it. The code as it is
  6982. written works for me, but when these workarounds are no longer needed it would
  6983. be better to remove them. Handling values on the time axis is one example of
  6984. this.
  6985. Some might question the use of an integer data type, particularly when storing
  6986. the result of a division operation. While this could be a concern if high
  6987. resolution wall sized displays become common, is is expected that in most cases
  6988. with sufficiently high sample rates, many data points will map to the same pixel
  6989. even with the minor data loss below.
  6990. In the case of the first measurement,
  6991. @<Handle the first measurement@>=
  6992. int x = FULLTIMETOINT(measure.time())/1000;
  6993. prevPoints->insert(tempcolumn, QPointF(x, measure.temperature()));
  6994. @ When at least one measurement already exists, we need to handle drawing the
  6995. line between the new measurement and the previous measurement.
  6996. \danger At present, the color chosen for these lines is based on the temperature
  6997. column passed to the graph. It would be better if colors could be passed to the
  6998. view for a specified series rather than have this hard coded. \endanger
  6999. @<At least one measurement exists@>=
  7000. QGraphicsLineItem *segment = new QGraphicsLineItem;
  7001. QPointF nextPoint(FULLTIMETOINT(measure.time())/1000, measure.temperature());
  7002. segment->setLine(prevPoints->value(tempcolumn).x() + offset,
  7003. -(prevPoints->value(tempcolumn).y()),
  7004. nextPoint.x() + offset, -(nextPoint.y()));
  7005. static QColor p[12] = {Qt::yellow, Qt::blue, Qt::cyan, Qt::red, Qt::magenta,
  7006. Qt::green, Qt::darkGreen, Qt::darkMagenta,
  7007. Qt::darkRed, Qt::darkCyan, Qt::darkBlue,
  7008. Qt::darkYellow};
  7009. segment->setPen(p[tempcolumn % 12]);
  7010. theScene->addItem(segment);
  7011. prevPoints->insert(tempcolumn, nextPoint);
  7012. @ In addition to adding data to the view, we also sometimes want to clear the
  7013. view of data.
  7014. @<GraphView Implementation@>=
  7015. void GraphView::clear()
  7016. {
  7017. int i;
  7018. foreach(i, prevPoints->keys())
  7019. {
  7020. removeSeries(i);
  7021. }
  7022. translations->clear();
  7023. }
  7024. @ Removing a set of data from the view involves removing the lines from the
  7025. scene and removing the column from a couple data structures.
  7026. @<GraphView Implementation@>=
  7027. void GraphView::removeSeries(int column)
  7028. {
  7029. if(graphLines->contains(column))
  7030. {
  7031. QList<QGraphicsLineItem *> *series = graphLines->value(column);
  7032. QGraphicsLineItem *segment;
  7033. foreach(segment, *series)
  7034. {
  7035. theScene->removeItem(segment);
  7036. }
  7037. qDeleteAll(*series);
  7038. }
  7039. graphLines->remove(column);
  7040. prevPoints->remove(column);
  7041. }
  7042. @ Second prototype for data series translation.
  7043. @<GraphView Implementation@>=
  7044. void GraphView::setSeriesTranslation(int column, double offset)
  7045. {
  7046. if(graphLines->contains(column))
  7047. {
  7048. QList<QGraphicsLineItem *> *series = graphLines->value(column);
  7049. QGraphicsLineItem *segment;
  7050. foreach(segment, *series)
  7051. {
  7052. segment->setPos(segment->pos().x()+offset, segment->pos().y());
  7053. }
  7054. }
  7055. if(translations->contains(column))
  7056. {
  7057. translations->insert(column, offset + translations->value(column));
  7058. }
  7059. else
  7060. {
  7061. translations->insert(column, offset);
  7062. }
  7063. }
  7064. @ These functions are required to create a |GraphView| object from a script.
  7065. @<Function prototypes for scripting@>=
  7066. void setGraphViewProperties(QScriptValue value, QScriptEngine *engine);
  7067. QScriptValue constructGraphView(QScriptContext *context, QScriptEngine *engine);
  7068. @ The scripting engine must be informed of the constructor.
  7069. @<Set up the scripting engine@>=
  7070. constructor = engine->newFunction(constructGraphView);
  7071. value = engine->newQMetaObject(&GraphView::staticMetaObject, constructor);
  7072. engine->globalObject().setProperty("GraphView", value);
  7073. @ The function implementation is trivial.
  7074. @<Functions for scripting@>=
  7075. QScriptValue constructGraphView(QScriptContext *, QScriptEngine *engine)
  7076. {
  7077. QScriptValue object = engine->newQObject(new GraphView);
  7078. setGraphViewProperties(object, engine);
  7079. return object;
  7080. }
  7081. void setGraphViewProperties(QScriptValue value, QScriptEngine *engine)
  7082. {
  7083. setQGraphicsViewProperties(value, engine);
  7084. }
  7085. @* A table of roasting data.
  7086. \noindent A typical roast log is a table listing temperature measurements taken
  7087. at regular intervals. The introduction of a computer brings several advantages.
  7088. A human does not need to record the measurements. Every measurement taken can be
  7089. logged, but the measurements do not all need to be displayed. The |ZoomLog|
  7090. class presents a table with time, temperature, and annotation for one or more
  7091. sets of roasting data and allows the user to select from a few different levels
  7092. of detail.
  7093. Experience has shown that one measurement every 30 or 15 seconds is most useful,
  7094. but it is also possible to view one measurement every 1, 5, 10, or 60 seconds
  7095. and there is an option to view every measurement collected. This last is what is
  7096. saved to a file.
  7097. The zooming log is implemented by keeping a measurement model with every level
  7098. of detail of interest and making sure that new measurements get to the models
  7099. they belong in. Switching the level of detail of the view then becomes a matter
  7100. of changing which model the view is using. This is very inefficient in terms of
  7101. space, but it is very fast and simple to code.
  7102. Starting in version 1.4, column sizes are persisted automatically using the
  7103. same method as described in the section on |SqlQueryView|.
  7104. @<Class declarations@>=
  7105. class MeasurementModel;@/
  7106. class ZoomLog : public QTableView@/
  7107. {@/
  7108. @[Q_OBJECT@]@;
  7109. @<ZoomLog private member data@>@;
  7110. void switchLOD(MeasurementModel *m);@/
  7111. @[private slots@]:@/
  7112. void centerOn(int row);
  7113. void persistColumnResize(int column, int oldsize, int newsize);
  7114. void restoreColumnWidths();
  7115. public:@/
  7116. ZoomLog();
  7117. QVariant data(int row, int column) const;
  7118. int rowCount();
  7119. bool saveXML(QIODevice *device);
  7120. bool saveCSV(QIODevice *device);
  7121. QString lastTime(int series);
  7122. @[Q_INVOKABLE@,@, int displayUnits()@];@t\2\2@>@/
  7123. @[public slots@]:@/
  7124. void setVisible(bool visibility);
  7125. void setHeaderData(int section, QString text);
  7126. void LOD_ms();
  7127. void LOD_1s();
  7128. void LOD_5s();
  7129. void LOD_10s();
  7130. void LOD_15s();
  7131. void LOD_30s();
  7132. void LOD_1m();
  7133. void newMeasurement(Measurement measure, int tempcolumn);
  7134. void newAnnotation(QString annotation, int tempcolumn,
  7135. int annotationcolumn);
  7136. void clear();
  7137. void addOutputTemperatureColumn(int column);
  7138. void addOutputAnnotationColumn(int column);
  7139. void clearOutputColumns();
  7140. void setDisplayUnits(int scale);
  7141. void addToCurrentColumnSet(int column);
  7142. void clearCurrentColumnSet();@/
  7143. protected:@/
  7144. virtual void showEvent(QShowEvent *event);
  7145. };
  7146. @ This class uses a different model for each level of detail and provides logic
  7147. for placing measurements and annotations in the appropriate models. A list of
  7148. each model is provided for conveniently performing operations that apply to
  7149. every model.
  7150. @<ZoomLog private member data@>=
  7151. MeasurementModel *model_ms;
  7152. MeasurementModel *model_1s;
  7153. MeasurementModel *model_5s;
  7154. MeasurementModel *model_10s;
  7155. MeasurementModel *model_15s;
  7156. MeasurementModel *model_30s;
  7157. MeasurementModel *model_1m;
  7158. QList<MeasurementModel *> modelSet;
  7159. QHash<int, Measurement> lastMeasurement;
  7160. MeasurementModel *currentModel;
  7161. QList<int> saveTempCols;
  7162. QList<int> saveNoteCols;
  7163. QList<int> currentColumnSet;
  7164. @ Most of the functionality this class provides is in getting measurements to
  7165. the right models. Every measurement goes to the full detail model. We also keep
  7166. track of the most recent measurement to detect the first measurement in a new
  7167. second and pass all of these on to the 1 second level of detail model. Some of
  7168. these are also passed to other models. Additionally, the models that store
  7169. coarser data strip the millisecond portion of the time.
  7170. A decision was made to present data promptly. With a high sample rate, some
  7171. might prefer an average of a few measurements near the reported time, but such
  7172. a feature does not exist in \pn{} currently.
  7173. The first measurement is always added to each model.
  7174. @<ZoomLog Implementation@>=
  7175. void ZoomLog::newMeasurement(Measurement measure, int tempcolumn)
  7176. {
  7177. @<Synthesize measurements for slow hardware@>@;
  7178. model_ms->newMeasurement(measure, tempcolumn);
  7179. if(lastMeasurement.contains(tempcolumn))
  7180. {
  7181. if(measure.time().second() !=
  7182. lastMeasurement.value(tempcolumn).time().second())
  7183. {
  7184. Measurement adjusted(measure.temperature(),
  7185. QTime(0, measure.time().minute(),
  7186. measure.time().second(), 0));
  7187. model_1s->newMeasurement(adjusted, tempcolumn);
  7188. if(adjusted.time().second() % 5 == 0)
  7189. {
  7190. model_5s->newMeasurement(adjusted, tempcolumn);
  7191. if(adjusted.time().second() % 10 == 0)
  7192. {
  7193. model_10s->newMeasurement(adjusted, tempcolumn);
  7194. }
  7195. if(adjusted.time().second() % 15 == 0)
  7196. {
  7197. model_15s->newMeasurement(adjusted, tempcolumn);
  7198. if(adjusted.time().second() % 30 == 0)
  7199. {
  7200. model_30s->newMeasurement(adjusted, tempcolumn);
  7201. if(adjusted.time().second() == 0)
  7202. {
  7203. model_1m->newMeasurement(adjusted, tempcolumn);
  7204. }
  7205. }
  7206. }
  7207. }
  7208. }
  7209. @<Synthesize measurements for columns in set@>@;
  7210. }
  7211. else
  7212. {
  7213. @<Add the first measurement to every model@>@;
  7214. }
  7215. lastMeasurement[tempcolumn] = measure;
  7216. }
  7217. @ The first measurement in a series should be the epoch measurement. This
  7218. should exist in every level of detail.
  7219. @<Add the first measurement to every model@>=
  7220. MeasurementModel *m;
  7221. foreach(m, modelSet)
  7222. {
  7223. m->newMeasurement(measure, tempcolumn);
  7224. }
  7225. @ Some measurement hardware in use cannot guarantee delivery of at least one
  7226. measurement per second. This causes problems for the current |ZoomLog|
  7227. implementation as, for example, if there is no measurement at a time where
  7228. the seconds are divisible by 5, there will be no entry in that view. This can
  7229. result in situations where the |ZoomLog| at its default view of one measurement
  7230. every 30 seconds might not display any data at all aside from the first
  7231. measurement, the last measurement, and any measurement that happens to have an
  7232. annotation associated with it. The solution in this case is to synthesize
  7233. measurements so that the |ZoomLog| thinks it gets at least one measurement
  7234. every second.
  7235. The current approach simply replicates the last measurement every second until
  7236. the time for the most recent measurement is reached, however it would likely be
  7237. better to interpolate values between the two most recent real measurements as
  7238. this would match the graphic representation rather than altering it when later
  7239. reviewing the batch.
  7240. @<Synthesize measurements for slow hardware@>=
  7241. if(lastMeasurement[tempcolumn].time() < measure.time())
  7242. {
  7243. QList<QTime> timelist;
  7244. for(QTime i = lastMeasurement[tempcolumn].time().addSecs(1); i < measure.time(); i = i.addSecs(1))
  7245. {
  7246. timelist.append(i);
  7247. }
  7248. for(int i = 0; i < timelist.size(); i++)
  7249. {
  7250. newMeasurement(Measurement(measure.temperature(), timelist[i], measure.scale()), tempcolumn);
  7251. }
  7252. }
  7253. @ New to \pn{} 1.4 is the concept of a current column set. This was added to
  7254. improve support for devices where measurements on different data series may not
  7255. arrive at exactly the same time and for multi-device configurations where
  7256. measurements from different devices are unlikely to arrive at the same time.
  7257. This can cause issues with log annotations and serialization. The solution is
  7258. to group all columns that are logically part of the same data acquisition
  7259. process and as measurements come in, the most recent measurement from other
  7260. columns can be duplicated at the new time. Two methods are responsible for
  7261. managing this measurement set. One adds a column to the set and the other
  7262. removes all columns from the set.
  7263. @<ZoomLog Implementation@>=
  7264. void ZoomLog::addToCurrentColumnSet(int column)
  7265. {
  7266. currentColumnSet.append(column);
  7267. }
  7268. void ZoomLog::clearCurrentColumnSet()
  7269. {
  7270. currentColumnSet.clear();
  7271. }
  7272. @ Replicating the measurements occurs as measurements are delivered. Note
  7273. that this code will not be called for the first measurement in each column.
  7274. @<Synthesize measurements for columns in set@>=
  7275. if(currentColumnSet.contains(tempcolumn))
  7276. {
  7277. int replicationcolumn;
  7278. foreach(replicationcolumn, currentColumnSet)
  7279. {
  7280. if(replicationcolumn != tempcolumn)
  7281. {
  7282. if(lastMeasurement.contains(replicationcolumn))
  7283. {
  7284. if(measure.time() > lastMeasurement.value(replicationcolumn).time())
  7285. {
  7286. Measurement synthetic(lastMeasurement.value(replicationcolumn).temperature(),
  7287. measure.time());
  7288. model_ms->newMeasurement(synthetic, replicationcolumn);
  7289. if(synthetic.time().second() != lastMeasurement.value(replicationcolumn).time().second())
  7290. {
  7291. Measurement adjusted(synthetic.temperature(), QTime(0, synthetic.time().minute(), synthetic.time().second(), 0));
  7292. model_1s->newMeasurement(adjusted, replicationcolumn);
  7293. if(adjusted.time().second() % 5 == 0)
  7294. {
  7295. model_5s->newMeasurement(adjusted, replicationcolumn);
  7296. if(adjusted.time().second() % 10 == 0)
  7297. {
  7298. model_10s->newMeasurement(adjusted, replicationcolumn);
  7299. }
  7300. if(adjusted.time().second() % 15 == 0)
  7301. {
  7302. model_15s->newMeasurement(adjusted, replicationcolumn);
  7303. if(adjusted.time().second() % 30 == 0)
  7304. {
  7305. model_30s->newMeasurement(adjusted, replicationcolumn);
  7306. if(adjusted.time().second() == 0)
  7307. {
  7308. model_1m->newMeasurement(adjusted, replicationcolumn);
  7309. }
  7310. }
  7311. }
  7312. }
  7313. }
  7314. lastMeasurement[replicationcolumn] = synthetic;
  7315. }
  7316. }
  7317. }
  7318. }
  7319. }
  7320. @ Just as the first measurement should exist at every level of detail, so should
  7321. any annotations. The measurement models will, when presented with an annotation,
  7322. apply it to the most recently entered measurement in the specified data series.
  7323. This presents a problem for the coarser views as the data point the annotation
  7324. belongs to most likely does not exist in that view. Furthermore, the model as it
  7325. is currently written will overwrite annotations that already exist on a
  7326. measurement if it is still the most recently entered. When collecting samples
  7327. during profile development, it is common to produce several annotations in a
  7328. short amount of time. The most useful thing to do in such a case is to add the
  7329. most recent measurement to each model and then apply the annotation. This, of
  7330. course, should only be done if there is a most recent measurement. An annotation
  7331. regarding the starting condition of the roaster should apply to the yet to be
  7332. recorded time zero measurement.
  7333. Note that only the value from the temperature column specified is displayed in
  7334. the row with the annotation. It would be better to check the full detail model
  7335. to determine if there are other measurements at the annotation time and present
  7336. these as well. Another possibility in the case of data not existing in other
  7337. temperature columns would be to interpolate a value from the existing data in
  7338. these columns, however this is potentially challenging as I would want to keep
  7339. true measurements distinct from estimations.
  7340. @<ZoomLog Implementation@>=
  7341. void ZoomLog::newAnnotation(QString annotation, int tempcolumn,
  7342. int annotationcolumn)
  7343. {
  7344. model_ms->newAnnotation(annotation, tempcolumn, annotationcolumn);
  7345. MeasurementModel *m;
  7346. if(lastMeasurement.contains(tempcolumn))
  7347. {
  7348. foreach(m, modelSet)
  7349. {
  7350. m->newMeasurement(lastMeasurement.value(tempcolumn), tempcolumn);
  7351. }
  7352. }
  7353. foreach(m, modelSet)
  7354. {
  7355. m->newAnnotation(annotation, tempcolumn, annotationcolumn);
  7356. }
  7357. }
  7358. @ As measurements are added to the model, the model will emit rowChanged
  7359. signals. These signals are connected to a function here that will attempt to
  7360. scroll the view to keep the most recently entered data in the center of the
  7361. view.
  7362. @<ZoomLog Implementation@>=
  7363. void ZoomLog::centerOn(int row)
  7364. {
  7365. scrollTo(currentModel->index(row, 0), QAbstractItemView::PositionAtCenter);
  7366. }
  7367. @ Once we are done with the data in the table, we want to clear it to prepare
  7368. for new data. This also clears the lists holding the output columns to use when
  7369. saving data.
  7370. @<ZoomLog Implementation@>=
  7371. void ZoomLog::clear()
  7372. {
  7373. MeasurementModel *m;
  7374. foreach(m, modelSet)
  7375. {
  7376. m->clear();
  7377. }
  7378. lastMeasurement.clear();
  7379. saveTempCols.clear();
  7380. saveNoteCols.clear();
  7381. }
  7382. @ These are depreciated methods originally written to assist in serializing
  7383. model data prior to the introduction of the |XMLOutput| class. These methods are
  7384. likely to be removed in a future version of the program.
  7385. @<ZoomLog Implementation@>=
  7386. QVariant ZoomLog::data(int row, int column) const
  7387. {
  7388. return model_ms->data(model_ms->index(row, column, QModelIndex()),
  7389. Qt::DisplayRole);
  7390. }
  7391. int ZoomLog::rowCount()
  7392. {
  7393. return model_ms->rowCount();
  7394. }
  7395. @ This method initializes an |XMLOutput| instance, passes the columns that we
  7396. would like to save to that object, and uses it to write an XML file with the
  7397. desired data to the specified device.
  7398. Since the output format does not currently specify a unit, there is an
  7399. assumption that the XML output will always have measurements in Fahrenheit. If
  7400. the model is not currently displaying measurements in Fahrenheit, it is asked to
  7401. do so before writing the XML data. User preference is restored after the XML
  7402. data has been written. Since this change is only performed on |model_ms|, most
  7403. users will never notice this.
  7404. @<ZoomLog Implementation@>=
  7405. bool ZoomLog::saveXML(QIODevice *device)
  7406. {
  7407. int prevUnits = model_ms->displayUnits();
  7408. if(prevUnits != 10144)
  7409. {
  7410. model_ms->setDisplayUnits(10144);
  7411. }
  7412. XMLOutput writer(model_ms, device, 0);
  7413. int c;
  7414. foreach(c, saveTempCols)
  7415. {
  7416. writer.addTemperatureColumn(model_ms->headerData(c, Qt::Horizontal).
  7417. toString(), c);
  7418. }
  7419. foreach(c, saveNoteCols)
  7420. {
  7421. writer.addAnnotationColumn(model_ms->headerData(c, Qt::Horizontal).
  7422. toString(), c);
  7423. }
  7424. bool retval = writer.output();
  7425. if(prevUnits != 10144)
  7426. {
  7427. model_ms->setDisplayUnits(prevUnits);
  7428. }
  7429. return retval;
  7430. }
  7431. @ This method is similar to |saveXML()|. The main difference is that CSV data is
  7432. exported instead of XML.
  7433. @<ZoomLog Implementation@>=
  7434. bool ZoomLog::saveCSV(QIODevice *device)
  7435. {
  7436. CSVOutput writer(currentModel, device, 0);
  7437. int c;
  7438. foreach(c, saveTempCols)
  7439. {
  7440. writer.addTemperatureColumn(model_ms->headerData(c, Qt::Horizontal).
  7441. toString(), c);
  7442. }
  7443. foreach(c, saveNoteCols)
  7444. {
  7445. writer.addAnnotationColumn(model_ms->headerData(c, Qt::Horizontal).
  7446. toString(), c);
  7447. }
  7448. return writer.output();
  7449. }
  7450. @ Several little functions, all alike\nfnote{If you get the reference, you may
  7451. enjoy reading another \cweb{} program:\par\indent\pdfURL{%
  7452. http://www-cs-staff.stanford.edu/$\sim$uno/programs/advent.w.gz}
  7453. {http://www-cs-staff.stanford.edu/~uno/programs/advent.w.gz}}, are used to
  7454. switch the view from one level of detail to another.
  7455. @<ZoomLog Implementation@>=
  7456. void ZoomLog::switchLOD(MeasurementModel *m)
  7457. {
  7458. disconnect(currentModel, SIGNAL(rowChanged(int)), this, 0);
  7459. setModel(m);
  7460. currentModel = m;
  7461. connect(currentModel, SIGNAL(rowChanged(int)), this, SLOT(centerOn(int)));
  7462. }
  7463. void ZoomLog::LOD_ms()
  7464. {
  7465. switchLOD(model_ms);
  7466. }
  7467. void ZoomLog::LOD_1s()
  7468. {
  7469. switchLOD(model_1s);
  7470. }
  7471. void ZoomLog::LOD_5s()
  7472. {
  7473. switchLOD(model_5s);
  7474. }
  7475. void ZoomLog::LOD_10s()
  7476. {
  7477. switchLOD(model_10s);
  7478. }
  7479. void ZoomLog::LOD_15s()
  7480. {
  7481. switchLOD(model_15s);
  7482. }
  7483. void ZoomLog::LOD_30s()
  7484. {
  7485. switchLOD(model_30s);
  7486. }
  7487. void ZoomLog::LOD_1m()
  7488. {
  7489. switchLOD(model_1m);
  7490. }
  7491. @ It can be useful to display temperature measurements in various units. To do
  7492. so, we simply tell all of the models which unit to provide data in. It is also
  7493. possible to obtain the currently selected unit.
  7494. @<ZoomLog Implementation@>=
  7495. void ZoomLog::setDisplayUnits(int scale)
  7496. {
  7497. model_ms->setDisplayUnits(scale);
  7498. model_1s->setDisplayUnits(scale);
  7499. model_5s->setDisplayUnits(scale);
  7500. model_10s->setDisplayUnits(scale);
  7501. model_15s->setDisplayUnits(scale);
  7502. model_30s->setDisplayUnits(scale);
  7503. model_1m->setDisplayUnits(scale);
  7504. }
  7505. int ZoomLog::displayUnits()
  7506. {
  7507. return model_ms->displayUnits();
  7508. }
  7509. @ For convenience, a method is provided for returning a string containing the
  7510. time of the last inserted measurement in a given data series.
  7511. @<ZoomLog Implementation@>=
  7512. QString ZoomLog::lastTime(int series)
  7513. {
  7514. Measurement measure = lastMeasurement.value(series);
  7515. QTime time = measure.time();
  7516. return time.toString("h:mm:ss.zzz");
  7517. }
  7518. @ This just leaves the initial table setup.
  7519. @<ZoomLog Implementation@>=
  7520. ZoomLog::ZoomLog() : QTableView(NULL), model_ms(new MeasurementModel(this)),
  7521. model_1s(new MeasurementModel(this)),@/ model_5s(new MeasurementModel(this)),
  7522. model_10s(new MeasurementModel(this)),@/ model_15s(new MeasurementModel(this)),
  7523. model_30s(new MeasurementModel(this)),@/ model_1m(new MeasurementModel(this))@/
  7524. {@/
  7525. setEditTriggers(QAbstractItemView::NoEditTriggers);
  7526. setSelectionMode(QAbstractItemView::NoSelection);
  7527. modelSet << model_ms << model_1s << model_5s << model_10s << model_15s <<
  7528. model_30s << model_1m;
  7529. currentModel = model_30s;
  7530. setModel(currentModel);
  7531. connect(currentModel, SIGNAL(rowChanged(int)), this, SLOT(centerOn(int)));
  7532. connect(horizontalHeader(), SIGNAL(sectionResized(int, int, int)),
  7533. this, SLOT(persistColumnResize(int, int, int)));
  7534. connect(horizontalHeader(), SIGNAL(sectionCountChanged(int, int)),
  7535. this, SLOT(restoreColumnWidths()));
  7536. }
  7537. @ A new method was added to this class for version 1.0.7. This allows header
  7538. data to be set on the log and have it propagate to the model set. The longer
  7539. term plan involves removing the hard coding of some of the header data.
  7540. @<ZoomLog Implementation@>=
  7541. void ZoomLog::setHeaderData(int section, QString text)
  7542. {
  7543. MeasurementModel *m;
  7544. foreach(m, modelSet)
  7545. {
  7546. m->setHeaderData(section, Qt::Horizontal, QVariant(text));
  7547. }
  7548. }
  7549. @ As of version 1.2.3, these methods replace similar methods added for version
  7550. 1.0.8. The main difference is that it is now possible to save multiple data
  7551. series to the same output document.
  7552. @<ZoomLog Implementation@>=
  7553. void ZoomLog::addOutputTemperatureColumn(int column)
  7554. {
  7555. saveTempCols.append(column);
  7556. }
  7557. void ZoomLog::addOutputAnnotationColumn(int column)
  7558. {
  7559. saveNoteCols.append(column);
  7560. }
  7561. void ZoomLog::clearOutputColumns()
  7562. {
  7563. saveTempCols.clear();
  7564. saveNoteCols.clear();
  7565. }
  7566. @ Starting in version 1.4 two methods have been introduced which are used to
  7567. save and restore column widths.
  7568. @<ZoomLog Implementation@>=
  7569. void ZoomLog::persistColumnResize(int column, int, int newsize)
  7570. {
  7571. @<Save updated column size@>@;
  7572. }
  7573. void ZoomLog::restoreColumnWidths()
  7574. {
  7575. @<Restore table column widths@>@;
  7576. }
  7577. void ZoomLog::setVisible(bool visibility)
  7578. {
  7579. QTableView::setVisible(visibility);
  7580. }
  7581. void ZoomLog::showEvent(QShowEvent *)
  7582. {
  7583. @<Restore table column widths@>@;
  7584. }
  7585. @ The |ZoomLog| class is one of the more complicated classes to expose to the
  7586. scripting engine. In addition to a script constructor, we also need functions
  7587. for saving and restoring the state of the display and functions for saving data
  7588. from the log in the supported formats.
  7589. @<Function prototypes for scripting@>=
  7590. void setZoomLogProperties(QScriptValue value, QScriptEngine *engine);
  7591. QScriptValue constructZoomLog(QScriptContext *context, QScriptEngine *engine);
  7592. QScriptValue ZoomLog_saveXML(QScriptContext *context, QScriptEngine *engine);
  7593. QScriptValue ZoomLog_saveCSV(QScriptContext *context, QScriptEngine *engine);
  7594. QScriptValue ZoomLog_saveState(QScriptContext *context, QScriptEngine *engine);
  7595. QScriptValue ZoomLog_restoreState(QScriptContext *context,
  7596. QScriptEngine *engine);
  7597. QScriptValue ZoomLog_lastTime(QScriptContext *context, QScriptEngine *engine);
  7598. QScriptValue ZoomLog_saveTemporary(QScriptContext *context,
  7599. QScriptEngine *engnie);
  7600. @ Of these, the global object only needs to know about the constructor.
  7601. @<Set up the scripting engine@>=
  7602. constructor = engine->newFunction(constructZoomLog);
  7603. value = engine->newQMetaObject(&ZoomLog::staticMetaObject, constructor);
  7604. engine->globalObject().setProperty("ZoomLog", value);
  7605. @ The script constructor sets properties on the newly created object to allow
  7606. the other functions to be called.
  7607. @<Functions for scripting@>=
  7608. QScriptValue constructZoomLog(QScriptContext *, QScriptEngine *engine)@/
  7609. {@/
  7610. QScriptValue object = engine->newQObject(new ZoomLog);
  7611. setZoomLogProperties(object, engine);
  7612. return object;@/
  7613. }
  7614. void setZoomLogProperties(QScriptValue value, QScriptEngine *engine)
  7615. {
  7616. setQTableViewProperties(value, engine);
  7617. value.setProperty("saveXML", engine->newFunction(ZoomLog_saveXML));
  7618. value.setProperty("saveCSV", engine->newFunction(ZoomLog_saveCSV));
  7619. value.setProperty("saveState", engine->newFunction(ZoomLog_saveState));
  7620. value.setProperty("restoreState",
  7621. engine->newFunction(ZoomLog_restoreState));
  7622. value.setProperty("lastTime", engine->newFunction(ZoomLog_lastTime));
  7623. value.setProperty("saveTemporary",
  7624. engine->newFunction(ZoomLog_saveTemporary));
  7625. }
  7626. @ The functions for saving data are simple wrappers around the corresponding
  7627. calls in |ZoomLog|, except for a function added for saving data to a temporary
  7628. file. The last provides the name of the file saved for use in copying that data
  7629. to a database entry.
  7630. @<Functions for scripting@>=
  7631. QScriptValue ZoomLog_saveXML(QScriptContext *context, QScriptEngine *engine)
  7632. {
  7633. ZoomLog *self = getself<ZoomLog *>(context);
  7634. bool retval = self->saveXML(argument<QIODevice *>(0, context));
  7635. return QScriptValue(engine, retval);
  7636. }
  7637. QScriptValue ZoomLog_saveCSV(QScriptContext *context, QScriptEngine *engine)
  7638. {
  7639. ZoomLog *self = getself<ZoomLog *>(context);
  7640. bool retval = self->saveCSV(argument<QIODevice *>(0, context));
  7641. return QScriptValue(engine, retval);
  7642. }
  7643. QScriptValue ZoomLog_saveTemporary(QScriptContext *context,
  7644. QScriptEngine *engine)
  7645. {
  7646. ZoomLog *self = getself<ZoomLog *>(context);
  7647. QString filename = QDir::tempPath();
  7648. filename.append("/");
  7649. filename.append(QUuid::createUuid().toString());
  7650. filename.append(".xml");
  7651. QFile *file = new QFile(filename);
  7652. self->saveXML(file);
  7653. file->close();
  7654. delete file;
  7655. return QScriptValue(engine, filename);
  7656. }
  7657. @ The remaining functions are convenience functions for use with the scripting
  7658. engine. One will save the column widths to a |QSettings| object. Another will
  7659. restore the column widths from settings. Finally, there is a function for
  7660. obtaining a string representation of the most recent measurement from a data
  7661. series.
  7662. \danger There are a couple of problems with these functions. First, the body of
  7663. these functions would probably be better off as methods in the |ZoomLog| class
  7664. proper, either as slots or |Q_INVOKABLE| so the special scripting functions
  7665. could be eliminated. Second, rather than polluting the settings with separate
  7666. entries for each column, it would probably be better to store all of these
  7667. values in an array.\endanger
  7668. |ZoomLog_saveState()| was changed in version 1.2.3 to not save a new value for
  7669. the column width if that width is |0|. This was done mainly to ease debugging.
  7670. Similarly, |ZoomLog_restoreState()| picks a new default value when |0| is
  7671. encountered.
  7672. @<Functions for scripting@>=
  7673. QScriptValue ZoomLog_saveState(QScriptContext *context, QScriptEngine *)
  7674. {
  7675. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  7676. QString key = argument<QString>(0, context);
  7677. int columns = argument<int>(1, context);
  7678. QSettings settings;
  7679. for(int i = 0; i < columns; i++)
  7680. {
  7681. if(self->columnWidth(i))
  7682. {
  7683. settings.beginGroup(key);
  7684. settings.setValue(QString("%1").arg(i), self->columnWidth(i));
  7685. settings.endGroup();
  7686. }
  7687. }
  7688. return QScriptValue();
  7689. }
  7690. QScriptValue ZoomLog_restoreState(QScriptContext *context, QScriptEngine *)
  7691. {
  7692. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  7693. QString key = argument<QString>(0, context);
  7694. int columns = argument<int>(1, context);
  7695. QSettings settings;
  7696. for(int i = 0; i < columns; i++)
  7697. {
  7698. settings.beginGroup(key);
  7699. self->setColumnWidth(i,
  7700. settings.value(QString("%1").arg(i), 80).toInt());
  7701. if(settings.value(QString("%1").arg(i), 80).toInt() == 0)
  7702. {
  7703. self->setColumnWidth(i, 80);
  7704. }
  7705. settings.endGroup();
  7706. }
  7707. return QScriptValue();
  7708. }
  7709. QScriptValue ZoomLog_lastTime(QScriptContext *context, QScriptEngine *engine)
  7710. {
  7711. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  7712. return QScriptValue(engine, self->lastTime(argument<int>(0, context)));
  7713. }
  7714. @* A model for roasting data.
  7715. \noindent Qt provides a tool called the model view architecture. This provides a
  7716. uniform interface allowing different types of model classes to work with
  7717. different types of view classes without either needing to know implementation
  7718. details of the other. \pn{} provides the |MeasurementModel| as a specialization
  7719. of |QAbstractItemModel| for use in this architecture.
  7720. @<Class declarations@>=
  7721. class MeasurementList;@/
  7722. class MeasurementModel : public QAbstractItemModel@/
  7723. {@t\1@>@/
  7724. Q_OBJECT@;
  7725. Q_ENUMS(DisplayUnits);
  7726. int unit;
  7727. QList<MeasurementList *> *entries;
  7728. QStringList *hData;
  7729. int colcount;
  7730. QHash<int, int> *lastTemperature;
  7731. QList<MeasurementList *>::iterator@, lastInsertion;
  7732. public:@/
  7733. enum DisplayUnits
  7734. {
  7735. Auto = -1,
  7736. Fahrenheit = 10144,
  7737. Celsius = 10143,
  7738. Kelvin = 10325,
  7739. Rankine = 10145
  7740. };
  7741. MeasurementModel(QObject *parent = NULL);
  7742. ~MeasurementModel();
  7743. int rowCount(const QModelIndex &parent = QModelIndex()) const;
  7744. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  7745. bool setHeaderData(int section, Qt::Orientation orientation,
  7746. const QVariant &value,@|int role = Qt::DisplayRole);
  7747. QVariant data(const QModelIndex &index, int role) const;
  7748. bool setData(const QModelIndex &index, const QVariant &value,
  7749. int role = Qt::EditRole);
  7750. Qt::ItemFlags flags(const QModelIndex &index) const;
  7751. QVariant headerData(int section, Qt::Orientation orientation,
  7752. int role = Qt::DisplayRole) const;
  7753. QModelIndex index(int row, int column,
  7754. const QModelIndex &parent = QModelIndex()) const;
  7755. QModelIndex parent(const QModelIndex &index) const;
  7756. int displayUnits();@/
  7757. @t\4@>public slots@t\kern-3pt@>:@/
  7758. void newMeasurement(Measurement measure, int tempcolumn);
  7759. void newAnnotation(QString annotation, int tempcolumn,
  7760. int annotationColumn);
  7761. void clear();
  7762. void setDisplayUnits(int scale);
  7763. signals:@/
  7764. void rowChanged(int);@t\2@>@/
  7765. }@t\kern-3pt@>;
  7766. @ The measurement model stores its data in a list of measurement lists. This
  7767. allows the model to store as many sets of data as needed. In order to keep
  7768. measurements in the model sorted by time, the measurement list adds two
  7769. comparison functions.
  7770. @<Class declarations@>=
  7771. class MeasurementList : public QVariantList@/
  7772. {@t\1@>@/
  7773. @t\4@>public:@/
  7774. bool operator<(const MeasurementList &other) const;
  7775. bool operator==(const MeasurementList &other) const;@t\2@>@/
  7776. }@t\kern-3pt@>;
  7777. @ The overload of |<| checks if the time in one list (always stored in the first
  7778. column) is less than the time stored in the second. The overload of |==| is used
  7779. in an optimization that allows us to skip the search procedure on model
  7780. insertion.
  7781. @<MeasurementModel Implementation@>=
  7782. bool MeasurementList::operator<(const MeasurementList &other) const
  7783. {
  7784. return this->first().toTime() < other.first().toTime();
  7785. }
  7786. bool MeasurementList::operator==(const MeasurementList &other) const
  7787. {
  7788. return this->first().toTime() == other.first().toTime();
  7789. }
  7790. @ The |MeasurementModel| class extends the |QAbstractItemModel| class to work
  7791. better with measurements and annotations that are passed around in \pn{}. Many
  7792. of the class methods are required because of that choice. For example, the
  7793. parent function which is never used directly:
  7794. @<MeasurementModel Implementation@>=
  7795. QModelIndex MeasurementModel::parent(const QModelIndex&) const
  7796. {
  7797. return QModelIndex();
  7798. }
  7799. @ Perhaps the most complicated part of this class is the code for dealing with a
  7800. new measurement. This is complicated by the requirement to insert measurements
  7801. while keeping the model sorted by time.
  7802. @<MeasurementModel Implementation@>=
  7803. void MeasurementModel::newMeasurement(Measurement measure, int tempcolumn)
  7804. {
  7805. MeasurementList *temp;
  7806. temp = new MeasurementList;
  7807. temp->append(QVariant(measure.time()));
  7808. @<Find the insertion point@>@;
  7809. MeasurementList *newEntry;
  7810. int insertion;
  7811. if(i != entries->end())
  7812. {
  7813. insertion = entries->indexOf(*i);
  7814. if((*i)->first().toTime() == measure.time())
  7815. {
  7816. @<Insert a new measurement at an existing time@>@;
  7817. }
  7818. else
  7819. {
  7820. @<Insert a new measurement somewhere else@>@;
  7821. }
  7822. }
  7823. else
  7824. {
  7825. @<Append a measurement@>@;
  7826. }
  7827. if(tempcolumn >= colcount)
  7828. {
  7829. colcount = tempcolumn + 1;
  7830. }
  7831. emit rowChanged(insertion);
  7832. delete temp;
  7833. }
  7834. @ To find the insertion point for new measurements we use a binary search of the
  7835. existing data. The code below is a direct adaptation of Program B\nfnote{%
  7836. \underbar{The Art of Computer Programming} Volume 3 Sorting and Searching 2nd
  7837. ed. (Knuth, 1997) Section 6.2.1: Searching an Ordered Table} modified to use
  7838. list iterators and control structures more familiar to \CPLUSPLUS/programmers
  7839. rather than {\mc MIX} machine codes. When the loop exits |i| is the insertion
  7840. point.
  7841. \medskip
  7842. \centerline{\includegraphics{search}}
  7843. \smallskip
  7844. \centerline{Figure \secno: Binary Search}
  7845. \medskip
  7846. @<Find the insertion point@>=
  7847. @<Scan from most recent insertion@>@;
  7848. if(quickscan == false)
  7849. {
  7850. i = entries->begin();
  7851. QList<MeasurementList *>::iterator@, u = entries->end();
  7852. QList<MeasurementList *>::iterator@, midpoint;
  7853. int n = u - i;
  7854. int rA;
  7855. while(n > 0)@/
  7856. {
  7857. rA = n>>1; /* |rA = |~$\bigl\lfloor{n\over2}\bigr\rfloor$ */
  7858. midpoint = i + rA;
  7859. if(**midpoint < *temp)@/
  7860. {
  7861. i = midpoint + 1;
  7862. n -= rA + 1;
  7863. }
  7864. else@/
  7865. {
  7866. n = rA;
  7867. }
  7868. }
  7869. }
  7870. @ The binary search, while correct, is not a particularly optimal choice for
  7871. this application. While the average running time for this is on the order of
  7872. $\ln N$ when each insertion point is equally likely, the reality of this
  7873. application is that insertions will likely be at the beginning of the list, at
  7874. the point of the most recent insertion, or a short distance from the most recent
  7875. insertion. By first considering the possibility that the measurement should be
  7876. inserted at or near the most recent measurement, shorter, more constant running
  7877. times as $N$ increases can be obtained.
  7878. To do this, when the number of measurements in the list is above a small number
  7879. which must be greater than 1, we check first if the insertion point is at the
  7880. last insertion (the |<| comparison fails and we do an |==| comparison before
  7881. giving up), then we check a small number of rows for either the end of the list,
  7882. in which case the insertion point is at the end, or for a point at which the |<|
  7883. comparison fails. If neither condition holds for a small number of comparisons
  7884. we resort to the binary search.
  7885. Performance measurements with this modification compared with previous versions
  7886. shows that this provides a huge performance boost.
  7887. @<Scan from most recent insertion@>=
  7888. @[QList<MeasurementList *>::iterator@, i@] = lastInsertion;@/
  7889. bool quickscan = false;@/
  7890. if(entries->size() > 5)@/
  7891. {@t\1@>@/
  7892. if(**i < *temp)@/
  7893. {@t\1@>@/
  7894. i += 1;@/
  7895. for(int j = 10; j > 0; j--)@/
  7896. {@t\1@>@/
  7897. if(i != entries->end())@/
  7898. {@t\1@>@/
  7899. if(**i < *temp)@/
  7900. {
  7901. i += 1;
  7902. }@/
  7903. else@/
  7904. {@t\1@>@/
  7905. quickscan = true;
  7906. break;@t\2@>@/
  7907. }@t\2@>@/
  7908. }@/
  7909. else@/
  7910. {@t\1@>@/
  7911. quickscan = true;
  7912. break;@t\2@>@/
  7913. }@t\2@>@/
  7914. }@t\2@>@/
  7915. }@/
  7916. else@/
  7917. {@t\1@>@/
  7918. if(**i == *temp)@/
  7919. {@t\1@>@/
  7920. quickscan = true;@t\2@>@/
  7921. }@t\2@>@/
  7922. }@t\2@>@/
  7923. }
  7924. @ If the chosen insertion point is at an existing time, we don't need to worry
  7925. about inserting rows. There may be a need to increase the size of the
  7926. measurement list to accept an entry in a new data series.
  7927. @<Insert a new measurement at an existing time@>=
  7928. if((*i)->size() < tempcolumn + 1)
  7929. {
  7930. for(int j = (*i)->size() - 1; j < tempcolumn + 1; j++)
  7931. {
  7932. (*i)->append(QVariant());
  7933. }
  7934. }
  7935. (*i)->replace(tempcolumn, measure.temperature());
  7936. lastInsertion = i;
  7937. emit dataChanged(createIndex(insertion, tempcolumn),
  7938. createIndex(insertion, tempcolumn));
  7939. lastTemperature->insert(tempcolumn, insertion);
  7940. @ If the measurement is not past the end of the existing data and the insertion
  7941. point has a different time, we need to use |beginInsertRows()| and
  7942. |endInsertRows()| to notify any attached view that a new row will be added.
  7943. @<Insert a new measurement somewhere else@>=
  7944. beginInsertRows(QModelIndex(), insertion, insertion);
  7945. newEntry = new MeasurementList;
  7946. newEntry->append(QVariant(measure.time()));
  7947. for(int j = 0; j < tempcolumn + 1; j++)
  7948. {
  7949. newEntry->append(QVariant());
  7950. }
  7951. newEntry->replace(tempcolumn, measure.temperature());
  7952. lastInsertion = entries->insert(i, newEntry);
  7953. endInsertRows();
  7954. lastTemperature->insert(tempcolumn, insertion);
  7955. @ If the insertion point is past the end of the existing data, a new row should
  7956. be appended to the data. This only needs to be a separate case to prevent the
  7957. comparison with a nonexistent entry. This is very similar to the case of
  7958. inserting at a new time anywhere else.
  7959. @<Append a measurement@>=
  7960. insertion = entries->size();@/
  7961. @<Insert a new measurement somewhere else@>
  7962. @ The other bit of code that's a little bit more complicated than other parts of
  7963. the class handles adding annotations to the data. Two signals are emitted in
  7964. this method. The |dataChanged| signal is expected by view classes that can use
  7965. this model. The |rowChanged| signal is used by |ZoomLog| to scroll the view to
  7966. the row the annotation has been added to. This is mainly useful when loading a
  7967. target profile and entering the first annotation prior to starting the batch.
  7968. @<MeasurementModel Implementation@>=
  7969. void MeasurementModel::newAnnotation(QString annotation, int tempcolumn,@|
  7970. int annotationColumn)
  7971. {
  7972. int r;
  7973. if(lastTemperature->contains(tempcolumn))
  7974. {
  7975. r = lastTemperature->value(tempcolumn);
  7976. }
  7977. else
  7978. {
  7979. r = 0;
  7980. }
  7981. if(r == 0 && entries->size() == 0)
  7982. {
  7983. @<Create the first row@>@;
  7984. }
  7985. MeasurementList *row = entries->at(r);
  7986. if(row->size() <= annotationColumn)
  7987. {
  7988. for(int i = row->size() - 1; i < annotationColumn + 1; i++)
  7989. {
  7990. row->append(QVariant());
  7991. }
  7992. }
  7993. row->replace(annotationColumn, annotation);
  7994. emit dataChanged(createIndex(r, annotationColumn),
  7995. createIndex(r, annotationColumn));
  7996. emit rowChanged(r);
  7997. if(annotationColumn > colcount - 1)
  7998. {
  7999. colcount = annotationColumn + 1;
  8000. }
  8001. }
  8002. @ There is no need to further complicate the function by adding the annotation
  8003. when the first row is created.
  8004. @<Create the first row@>=
  8005. beginInsertRows(QModelIndex(), 0, 0);
  8006. MeasurementList *newEntry = new MeasurementList;
  8007. newEntry->append(QVariant(QTime(0, 0, 0, 0)));
  8008. entries->append(newEntry);
  8009. endInsertRows();
  8010. @ Clearing the model data is a simple matter of deleting every row, remembering
  8011. to let any attached views know that we are doing this, and resetting the number
  8012. of columns.
  8013. @<MeasurementModel Implementation@>=
  8014. void MeasurementModel::clear()
  8015. {
  8016. beginRemoveRows(QModelIndex(), 0, entries->size());
  8017. while(entries->size() != 0)
  8018. {
  8019. MeasurementList *row = entries->takeFirst();
  8020. delete row;
  8021. }
  8022. endRemoveRows();
  8023. colcount = hData->size();
  8024. lastTemperature->clear();
  8025. reset();
  8026. }
  8027. @ While these methods for adding measurements and annotations are fine when
  8028. recording a stream of measurements, either from the |DAQ| or when loading saved
  8029. data, there are also cases where we'd like to edit the data in the model
  8030. directly from the table view. For this, we need to reimplement |setData()|.
  8031. Very little input checking is done here. Editable views may want to place
  8032. delegates\nfnote{Qt 4.4: Delegate Classes\par\indent\hbox{%
  8033. \pdfURL{http://doc.trolltech.com/4.4/model-view-delegate.html}{%
  8034. http://doc.trolltech.com/4.4/model-view-delegate.html}}} on the columns to make
  8035. editing the data easier and less error prone.
  8036. @<MeasurementModel Implementation@>=
  8037. bool MeasurementModel::setData(const QModelIndex &index,
  8038. const QVariant &value, int role)@t\2\2@>@/
  8039. {@t\1@>@/
  8040. if(role != Qt::EditRole && role != Qt::DisplayRole)@/
  8041. {@t\1@>@/
  8042. return false;@t\2@>@/
  8043. }@/
  8044. @<Check that the index is valid@>@;
  8045. if(!valid)@/
  8046. {@t\1@>@/
  8047. return false;@t\2@>@/
  8048. }@/
  8049. MeasurementList *row = entries->at(index.row());
  8050. if(index.column() >= row->size())
  8051. {
  8052. @<Expand the row to prepare for new data@>@;
  8053. }
  8054. if(index.column() == 0)
  8055. {
  8056. @<Edit data in the time column@>@;
  8057. }
  8058. else
  8059. {
  8060. @<Edit data in other columns@>@;
  8061. }
  8062. return true;@t\2@>@/
  8063. }
  8064. @ There is no sense in attempting to edit the data if there isn't any data
  8065. available to edit. This check is also used when retrieving data from the model.
  8066. @<Check that the index is valid@>=
  8067. bool valid = false;
  8068. if(index.isValid())@/
  8069. {@t\1@>@/
  8070. if(index.row() < entries->size())@/
  8071. {@t\1@>@/
  8072. if(index.column() < colcount)@/
  8073. {@t\1@>@/
  8074. valid = true;@t\2@>@/
  8075. }@t\2@>@/
  8076. }@t\2@>@/
  8077. }
  8078. @ When editing data, there might not be anything where we want to add the data.
  8079. For example, adding an annotation to an otherwise unannotated measurement. This
  8080. is fine, but we need to expand the row instead of inserting data out of bounds.
  8081. @<Expand the row to prepare for new data@>=
  8082. for(int i = row->size() - 1; i < index.column(); i++)
  8083. {
  8084. row->append(QVariant());
  8085. }
  8086. @ Changing time data must be considered separately from other data. As the model
  8087. keeps itself sorted based on the time field, allowing the user to get the model
  8088. data out of order would result in poorly defined behavior later. Our approach is
  8089. to remove the row from the model temporarily then reuse the code from
  8090. |newMeasurement()| to find the new insertion point. No attempt is made to merge
  8091. the contents from two rows with identical times, but an attempt is made to not
  8092. be too rigid in what we expect the user to enter. If an invalid time is entered,
  8093. we give up and leave the data as we found it.
  8094. @<Edit data in the time column@>=
  8095. QTime time;@/
  8096. if(!(time = QTime::fromString(value.toString(), "m:s.z")).isValid())@/
  8097. {@t\1@>@/
  8098. if(!(time = QTime::fromString(value.toString(), "m:s")).isValid())@/
  8099. {@t\1@>@/
  8100. return false;@t\2@>@/
  8101. }@t\2@>@/
  8102. }@/
  8103. row = entries->takeAt(index.row());
  8104. row->replace(index.column(), QVariant(time));
  8105. MeasurementList *temp = row;
  8106. @<Find the insertion point@>@;
  8107. entries->insert(i, row);
  8108. int newRow = entries->indexOf(*i);
  8109. if(newRow < index.row())@/
  8110. {
  8111. emit dataChanged(createIndex(newRow, index.column()), index);
  8112. }
  8113. else@/
  8114. {
  8115. emit dataChanged(index, createIndex(newRow, index.column()));
  8116. }
  8117. @ Data in other columns is a little easier to handle.
  8118. @<Edit data in other columns@>=
  8119. row->replace(index.column(), value);
  8120. emit dataChanged(index, index);
  8121. @ As it has already been established that the first column is always considered
  8122. the time of the measurement, this assumption can be built into the model
  8123. constructor.
  8124. @<MeasurementModel Implementation@>=
  8125. MeasurementModel::MeasurementModel(QObject *parent) : QAbstractItemModel(parent),
  8126. unit(Fahrenheit), hData(new QStringList),
  8127. lastTemperature(new QHash<int, int>)@/
  8128. {
  8129. colcount = 1;
  8130. entries = new QList<MeasurementList *>;
  8131. lastInsertion = entries->begin();
  8132. hData->append(tr("Time"));
  8133. }
  8134. @ In the destructor we need to remember to clean up after ourselves.
  8135. @<MeasurementModel Implementation@>=
  8136. MeasurementModel::~MeasurementModel()
  8137. {
  8138. clear();
  8139. delete entries;
  8140. delete hData;
  8141. }
  8142. @ A pair of functions are used to determine the number of rows and columns the
  8143. model provides. No entries in the model have children, so the parent should
  8144. always be the invisible root object. If it isn't, we should return 0.
  8145. @<MeasurementModel Implementation@>=
  8146. int MeasurementModel::rowCount(const QModelIndex &parent) const
  8147. {
  8148. if(parent == QModelIndex())
  8149. {
  8150. return entries->size();
  8151. }
  8152. return 0;
  8153. }
  8154. int MeasurementModel::columnCount(const QModelIndex &parent) const
  8155. {
  8156. if(parent == QModelIndex())
  8157. {
  8158. return colcount;
  8159. }
  8160. return 0;
  8161. }
  8162. @ The model maintains a set of header data. At present, it only supports header
  8163. data at the top of the model due to the author's preference to not have row
  8164. numbers littering the left of the table (the time column is sufficient to
  8165. identify the row for the user).
  8166. The model view architecture supports the concept of different data roles in the
  8167. header data. At present, this model ignores the role when setting header data.
  8168. @<MeasurementModel Implementation@>=
  8169. bool MeasurementModel::setHeaderData(int section, Qt::Orientation orientation,@|
  8170. const QVariant &value, int)@t\2@>@/
  8171. @t\4@>{@/
  8172. if(orientation == Qt::Horizontal)@/
  8173. {@t\1@>@/
  8174. if(hData->size() < section + 1)@/
  8175. {@/
  8176. for(int i = hData->size(); i < section + 1; i++)@/
  8177. {@/
  8178. if(colcount < i)@/
  8179. {@/
  8180. beginInsertColumns(QModelIndex(), i, i);
  8181. }
  8182. hData->append(QString());
  8183. if(colcount < i)@/
  8184. {@/
  8185. endInsertColumns();
  8186. }
  8187. }
  8188. }
  8189. hData->replace(section, value.toString());
  8190. emit headerDataChanged(orientation, section, section);
  8191. if(colcount < section + 1)@/
  8192. {@/
  8193. colcount = section + 1;
  8194. }@/
  8195. return true;@t\2@>@/
  8196. }@/
  8197. return false;@/
  8198. @t\4@>}
  8199. @ While the current implementation always receives measurements in degrees
  8200. Fahrenheit, international users often want to see data presented in Celsius. To
  8201. do this, a slot is provided to allow selecting among different units. When this
  8202. method is called, the model indicates that all attached views must update all
  8203. displayed data and requests for temperature data will have any needed conversion
  8204. performed before sending that information to the view. Another method is
  8205. available to request a number identifyin the currently displayed units.
  8206. @<MeasurementModel Implementation@>=
  8207. void MeasurementModel::setDisplayUnits(int scale)
  8208. {
  8209. beginResetModel();
  8210. unit = scale;
  8211. endResetModel();
  8212. }
  8213. int MeasurementModel::displayUnits()
  8214. {
  8215. return unit;
  8216. }
  8217. @ A model is generally quite useless if the data the model contains cannot be
  8218. retrieved. To do this, we check that the index requested is a valid index that
  8219. is within the bounds of the model data and that a role we understand has been
  8220. requested. If none of these conditions are met, a default constructed |QVariant|
  8221. is returned.
  8222. At present, |Qt::DisplayRole| and |Qt::EditRole| are supported. These return the
  8223. same thing. Views will request the display role for presenting the information
  8224. to the user, but they will request the edit role if the user attempts to modify
  8225. the data through a view.
  8226. @<MeasurementModel Implementation@>=
  8227. QVariant MeasurementModel::data(const QModelIndex &index, int role) const@/
  8228. {@/
  8229. @<Check that the index is valid@>@;
  8230. if(!valid)
  8231. {
  8232. return QVariant();
  8233. }
  8234. if(role == Qt::DisplayRole || role == Qt::EditRole)
  8235. {
  8236. MeasurementList *row = entries->at(index.row());
  8237. if(index.column() > row->size())
  8238. {
  8239. return QVariant();
  8240. }
  8241. else
  8242. {
  8243. if(index.column() == 0)
  8244. {
  8245. return QVariant(row->at(0).toTime().toString("mm:ss.zzz"));
  8246. }
  8247. else if(lastTemperature->contains(index.column()))
  8248. {
  8249. if(row->at(index.column()).toString().isEmpty())
  8250. {
  8251. return QVariant();
  8252. }
  8253. switch(unit)
  8254. {
  8255. case Auto:
  8256. case Fahrenheit:
  8257. return QVariant(row->at(index.column()).toString());
  8258. break;
  8259. case Celsius:
  8260. return QVariant((row->at(index.column()).toDouble() -
  8261. 32) * 5 / 9);
  8262. break;
  8263. case Kelvin:
  8264. return QVariant((row->at(index.column()).toDouble() +
  8265. 459.67) * 5 / 9);
  8266. break;
  8267. case Rankine:
  8268. return QVariant(row->at(index.column()).toDouble() +
  8269. 459.67);
  8270. break;
  8271. default:
  8272. break;
  8273. }
  8274. }
  8275. return QVariant(row->at(index.column()).toString());
  8276. }
  8277. }
  8278. return QVariant();@/
  8279. }
  8280. @ Views also must be able to retrieve the header data.
  8281. @<MeasurementModel Implementation@>=
  8282. QVariant MeasurementModel::headerData(int section, Qt::Orientation orientation,
  8283. int role ) const
  8284. {
  8285. if(orientation == Qt::Horizontal)
  8286. {
  8287. if(role == Qt::DisplayRole)
  8288. {
  8289. if(section < hData->size())
  8290. {
  8291. return QVariant(hData->at(section));
  8292. }
  8293. }
  8294. }
  8295. return QVariant();
  8296. }
  8297. @ Views will sometimes request information about the interactions available for
  8298. an index. In the case of this model, each index is treated in the same way.
  8299. It may be a good idea to extend the model class to allow models that can be
  8300. edited through the view such as the table view presented in the |LogEditWindow|
  8301. and models that probably shouldn't be edited in the view, such as the models
  8302. managed by |ZoomLog|. This could be done by subclassing and only reimplementing
  8303. this method. Otherwise, a new method to specify that the user should not edit
  8304. the model could be provided and a flag would be checked here.
  8305. @<MeasurementModel Implementation@>=
  8306. Qt::ItemFlags MeasurementModel::flags(const QModelIndex &index) const@/
  8307. {@/
  8308. @<Check that the index is valid@>@;
  8309. if(valid)
  8310. {
  8311. return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable;
  8312. }
  8313. return 0;
  8314. }
  8315. @ Much of the way models are interacted with in Qt's model view architecture is
  8316. through model indices. The model is responsible for creating these indices from
  8317. row column pairs.
  8318. @<MeasurementModel Implementation@>=
  8319. QModelIndex MeasurementModel::index(int row, int column,
  8320. const QModelIndex &parent) const@t\2\2@>@/
  8321. {@t\1@>@/
  8322. if(parent == QModelIndex())@/
  8323. {@t\1@>@/
  8324. if(row < entries->size() && entries->isEmpty() == false)@/
  8325. {@/
  8326. if(column < entries->at(row)->size())@/
  8327. {@/
  8328. return createIndex(row, column);@/
  8329. }@/
  8330. }@t\2@>@/
  8331. }@/
  8332. return QModelIndex();@/
  8333. @t\4@>}
  8334. @** Annotating roast data.
  8335. \noindent In addition to recording time temperature pairs, \pn{} allows the user
  8336. to annotate the roasting log to indicate control changes, the end of the batch,
  8337. or samples collected from the roast. It is important that these annotations can
  8338. be applied to the roasting log quickly. This is the purpose of the
  8339. |AnnotationButton| class.
  8340. @<Class declarations@>=
  8341. class AnnotationButton : public QPushButton@/
  8342. {@t\1@>@/
  8343. Q_OBJECT@;
  8344. QString note;
  8345. int tc;
  8346. int ac;
  8347. int count;
  8348. public:@/
  8349. AnnotationButton(const QString &text, QWidget *parent = NULL);@/
  8350. @t\4@>public slots@t\kern-3pt@>:@/
  8351. void setAnnotation(const QString &annotation);
  8352. void setTemperatureColumn(int tempcolumn);
  8353. void setAnnotationColumn(int annotationcolumn);
  8354. void annotate();
  8355. void resetCount();
  8356. signals:@/
  8357. void annotation(QString annotation, int tempcolumn,
  8358. int notecolumn);@t\2@>@/
  8359. }@t\kern-3pt@>;
  8360. @ Setting up a new annotation button begins with the constructor. This takes a
  8361. string specifying the text that will appear on the button and optionally a
  8362. parent widget. This is also a sensible place to set up the desired behavior the
  8363. button should exhibit when clicked.
  8364. @<AnnotationButton Implementation@>=
  8365. AnnotationButton::AnnotationButton(const QString &text, QWidget *parent) :
  8366. QPushButton(text, parent), note(""), tc(0), ac(0), count(0)@/
  8367. {
  8368. connect(this, SIGNAL(clicked()), this, SLOT(annotate()));
  8369. }
  8370. @ The slot that is called when the button is clicked needs to be able to handle
  8371. two types of annotations. Simple annotations send the same annotation every time
  8372. the button is clicked. Counting annotations are annotation strings that have a
  8373. |"%1"| somewhere in the string. That substring will be replaced with an integer
  8374. that is incremented before the annotation is sent. This integer is initialized
  8375. to 0. It will be incremented to 1 the first time the button is clicked and that
  8376. will be the replacement value.
  8377. @<AnnotationButton Implementation@>=
  8378. void AnnotationButton::annotate()
  8379. {
  8380. if(note.contains("%1"))
  8381. {
  8382. count++;
  8383. emit annotation(note.arg(count), tc, ac);
  8384. }
  8385. else
  8386. {
  8387. emit annotation(note, tc, ac);
  8388. }
  8389. }
  8390. @ A few methods are available to indicate which temperature series the
  8391. annotation should be applied to, which column in a table view the annotation
  8392. should be entered in, and what text should be in the annotation.
  8393. @<AnnotationButton Implementation@>=
  8394. void AnnotationButton::setTemperatureColumn(int tempcolumn)
  8395. {
  8396. tc = tempcolumn;
  8397. }
  8398. void AnnotationButton::setAnnotationColumn(int annotationcolumn)
  8399. {
  8400. ac = annotationcolumn;
  8401. }
  8402. void AnnotationButton::setAnnotation(const QString &annotation)
  8403. {
  8404. note = annotation;
  8405. }
  8406. @ Finally, in the case of counting annotations, there should be a way to reset
  8407. the number used in the annotation.
  8408. @<AnnotationButton Implementation@>=
  8409. void AnnotationButton::resetCount()
  8410. {
  8411. count = 0;
  8412. }
  8413. @ A script constructor is needed to allow an |AnnotationButton| to be created
  8414. from a script.
  8415. @<Function prototypes for scripting@>=
  8416. QScriptValue constructAnnotationButton(QScriptContext *context,
  8417. QScriptEngine *engine);
  8418. void setAnnotationButtonProperties(QScriptValue value, QScriptEngine *engine);
  8419. @ In order to use this, the engine needs to be informed of the function.
  8420. @<Set up the scripting engine@>=
  8421. constructor = engine->newFunction(constructAnnotationButton);
  8422. value = engine->newQMetaObject(&AnnotationButton::staticMetaObject,
  8423. constructor);
  8424. engine->globalObject().setProperty("AnnotationButton", value);
  8425. @ The implementation is trivial.
  8426. @<Functions for scripting@>=
  8427. QScriptValue constructAnnotationButton(QScriptContext *context,
  8428. QScriptEngine *engine)
  8429. {
  8430. QScriptValue object =
  8431. engine->newQObject(new AnnotationButton(argument<QString>(0, context)));
  8432. setAnnotationButtonProperties(object, engine);
  8433. return object;
  8434. }
  8435. void setAnnotationButtonProperties(QScriptValue value, QScriptEngine *engine)
  8436. {
  8437. setQPushButtonProperties(value, engine);
  8438. }
  8439. @* A spin box for annotations.
  8440. \noindent While the annotation button is adequate for most log annotation tasks,
  8441. there are some times where the log should contain a small number of numerical
  8442. observations where it is inconvenient or cost prohibitive to enable automated
  8443. logging. For these tasks, a spin box that produces an appropriate annotation may
  8444. be useful.
  8445. @<Class declarations@>=
  8446. class AnnotationSpinBox : public QDoubleSpinBox@/
  8447. {@t\1@>@/
  8448. Q_OBJECT@;
  8449. QString pretext;
  8450. QString posttext;
  8451. int tc;
  8452. int ac;
  8453. bool change;
  8454. public:
  8455. AnnotationSpinBox(const QString &pret, const QString &postt,
  8456. QWidget *parent = NULL);@/
  8457. @t\4@>public slots@t\kern-3pt@>:@/
  8458. void setPretext(const QString &pret);
  8459. void setPosttext(const QString &postt);
  8460. void setTemperatureColumn(int tempcolumn);
  8461. void setAnnotationColumn(int annotationcolumn);
  8462. void annotate();
  8463. void resetChange();
  8464. signals:@/
  8465. void annotation(QString annotation, int tempcolumn,
  8466. int notecolumn);@t\2@>@/
  8467. }@t\kern-3pt@>;
  8468. @ Setting up a new annotation spin box begins with the constructor. This takes
  8469. two strings specifying optional text that may appear before or after the
  8470. numerical value of the spin box in the annotation. No spaces are placed between
  8471. the text and the numerical values, so if such spacing is required, it must be
  8472. included in the relevant string.
  8473. This function also sets up the behavior for firing annotation events. An
  8474. annotation should be fired when the user presses enter while the spin box has
  8475. focus. This implementation will also attempt to fire an annotation when the
  8476. spin box loses focus. No annotation is fired if the value of the spin box has
  8477. not been changed since the previous annotation event.
  8478. @<AnnotationSpinBox Implementation@>=
  8479. AnnotationSpinBox::AnnotationSpinBox(const QString &pret,
  8480. const QString &postt,@|
  8481. QWidget *parent)
  8482. : QDoubleSpinBox(parent), pretext(pret), posttext(postt)@/
  8483. {
  8484. resetChange();
  8485. connect(this, SIGNAL(editingFinished()), this, SLOT(annotate()));
  8486. connect(this, SIGNAL(valueChanged(double)), this, SLOT(resetChange()));
  8487. }
  8488. @ The |resetChange()| signal just sets a boolean which is checked prior to
  8489. sending an annotation. This is called automatically when the value of the spin
  8490. box is changed, but it should also be called when a batch is finished in case
  8491. the first required annotation is the same as the last required annotation from
  8492. the previous batch.
  8493. @<AnnotationSpinBox Implementation@>=
  8494. void AnnotationSpinBox::resetChange()@t\2\2@>@/
  8495. {@t\1@>@/
  8496. change = true;@t\2@>@/
  8497. }
  8498. @ The annotation slot is responsible for determining if an annotation should be
  8499. sent. The current implementation is to only attempt to send such a signal when
  8500. the |editingFinished()| signal is emitted, however this could also be connected
  8501. to other signals.
  8502. @<AnnotationSpinBox Implementation@>=
  8503. void AnnotationSpinBox::annotate()@t\2\2@>@/
  8504. {@t\1@>@/
  8505. if(change)@/
  8506. {@t\1@>@/
  8507. change = false;@/
  8508. emit annotation(QString("%1%2%3").arg(pretext).
  8509. arg(value()).arg(posttext), tc, ac);@t\2@>@/
  8510. }@t\2@>@/
  8511. }
  8512. @ These methods set various properties of the annotation.
  8513. @<AnnotationSpinBox Implementation@>=
  8514. void AnnotationSpinBox::setTemperatureColumn(int tempcolumn)
  8515. {
  8516. tc = tempcolumn;
  8517. }
  8518. void AnnotationSpinBox::setAnnotationColumn(int annotationcolumn)
  8519. {
  8520. ac = annotationcolumn;
  8521. }
  8522. void AnnotationSpinBox::setPretext(const QString &pret)
  8523. {
  8524. pretext = pret;
  8525. }
  8526. void AnnotationSpinBox::setPosttext(const QString &postt)
  8527. {
  8528. posttext = postt;
  8529. }
  8530. @ Two functions are needed to interface |AnnotationSpinBox| with the host
  8531. environment. Additional functions are required for setting up inheritance
  8532. properly.
  8533. @<Function prototypes for scripting@>=
  8534. QScriptValue constructAnnotationSpinBox(QScriptContext *context,
  8535. QScriptEngine *engine);
  8536. void setAnnotationSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  8537. void setQDoubleSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  8538. void setQAbstractSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  8539. @ The first of these is passed into the host environment.
  8540. @<Set up the scripting engine@>=
  8541. constructor = engine->newFunction(constructAnnotationSpinBox);
  8542. value = engine->newQMetaObject(&AnnotationSpinBox::staticMetaObject,
  8543. constructor);
  8544. engine->globalObject().setProperty("AnnotationSpinBox", value);
  8545. @ The script constructor creates a new object and passes it to a function that
  8546. is responsible for setting up properties in the inheritance chain.
  8547. @<Functions for scripting@>=
  8548. QScriptValue constructAnnotationSpinBox(QScriptContext *context,
  8549. QScriptEngine *engine)
  8550. {
  8551. QScriptValue object = engine->newQObject(new AnnotationSpinBox(
  8552. argument<QString>(0, context), argument<QString>(1, context)));
  8553. setAnnotationSpinBoxProperties(object, engine);
  8554. return object;
  8555. }
  8556. void setAnnotationSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  8557. {
  8558. setQDoubleSpinBoxProperties(value, engine);
  8559. }
  8560. void setQDoubleSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  8561. {
  8562. setQAbstractSpinBoxProperties(value, engine);
  8563. }
  8564. void setQAbstractSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  8565. {
  8566. setQWidgetProperties(value, engine);
  8567. }
  8568. @** A digital timer.
  8569. \noindent Before \pn{} was a data logger, it was a simple digital timer written
  8570. because there were no shops in Racine that could sell a simple dual digital
  8571. count up timer at a time when my first timer was malfunctioning. After
  8572. attempting to purchase a replacement device at several stores that have sold
  8573. such devices in the past, I decided to spend a couple hours writing my own
  8574. timer.
  8575. For historical reasons, the |TimerDisplay| class is considerably more functional
  8576. than \pn{} requires. Those needing only a digital timer can extract the code for
  8577. this class and use it in a timer application. This should work on any platform
  8578. supported by Qt.
  8579. @<Class declarations@>=
  8580. class TimerDisplay : public QLCDNumber@/
  8581. {@t\1@>@/
  8582. Q_OBJECT@/
  8583. @<TimerDisplay Properties@>@;
  8584. @t\4@>private slots@t\kern-3pt@>:@/
  8585. void updateTime();
  8586. void setCountUpMode();
  8587. void setCountDownMode();
  8588. void setClockMode();
  8589. public:@/
  8590. TimerDisplay(QWidget *parent = NULL);
  8591. ~TimerDisplay();
  8592. enum TimerMode
  8593. {
  8594. CountUp,
  8595. CountDown,
  8596. Clock
  8597. };
  8598. QString value();
  8599. QTime seconds();
  8600. TimerMode mode();
  8601. bool isRunning();
  8602. QTime resetValue();
  8603. QString displayFormat();
  8604. bool autoReset();@/
  8605. @t\4@>public slots@t\kern-3pt@>:@/
  8606. void setTimer(QTime value = QTime(0, 0, 0));
  8607. void setMode(TimerMode mode);
  8608. void startTimer();
  8609. void stopTimer();
  8610. void copyTimer();
  8611. void setResetValue(QTime value = QTime(0, 0, 0));
  8612. void reset();
  8613. void setDisplayFormat(QString format);
  8614. void setAutoReset(bool reset);
  8615. void updateDisplay();
  8616. signals:@/
  8617. void valueChanged(QTime);
  8618. void runStateChanged(bool);@/
  8619. private:@/
  8620. @<TimerDisplay Private Variables@>@;@t\2@>@/
  8621. }@t\kern-3pt@>;
  8622. @ Qt provides a property system based on its meta-object system. This allows for
  8623. a number of advanced features which \pn{} does not use. The properties available
  8624. for the TimerDisplay class exist for historical reasons, but there are some
  8625. plans for future development which may make use of them. The properties may also
  8626. be useful for someone using this class in another program.
  8627. @<TimerDisplay Properties@>=
  8628. Q_PROPERTY(QTime seconds READ seconds WRITE setTimer)@/
  8629. Q_PROPERTY(TimerMode mode READ mode WRITE setMode)@/
  8630. Q_PROPERTY(bool running READ isRunning)@/
  8631. Q_PROPERTY(QTime resetValue READ resetValue WRITE setResetValue)@/
  8632. Q_PROPERTY(QString displayFormat READ displayFormat WRITE setDisplayFormat)@/
  8633. Q_PROPERTY(bool autoReset READ autoReset WRITE setAutoReset)@/
  8634. @ A number of private variables are used to implement this class.
  8635. @<TimerDisplay Private Variables@>=
  8636. QTime s;
  8637. QTime r;
  8638. QTimer clock;
  8639. TimerDisplay::TimerMode m;
  8640. bool running;
  8641. bool ar;
  8642. QAction *startAction;
  8643. QAction *stopAction;
  8644. QAction *resetAction;
  8645. QString f;
  8646. QTime relative;
  8647. QTime base;
  8648. @ |TimerDisplay| is a specialization of |QLCDNumber| designed for time keeping
  8649. purposes. It sets up a timer that fires roughly every half second to see if it
  8650. needs to update itself. The constructor sets this up, but does not start the
  8651. timer. The class provides three actions which can be used to start, stop, or
  8652. reset the timer. These actions are also set up in the constructor.
  8653. By default, the timer will display its time in hours, minutes, and seconds. This
  8654. can be changed as is done with the batch timer (it is expected that nobody will
  8655. want to spend an hour or more to roast a batch of coffee). The display style is
  8656. also changed to a sensible default, but this can be changed with the usual
  8657. |QLCDNumber| methods.
  8658. @<TimerDisplay Implementation@>=
  8659. TimerDisplay::TimerDisplay(QWidget *parent) : QLCDNumber(8, parent),
  8660. s(QTime(0, 0, 0)), r(QTime(0, 0, 0)), clock(NULL),@/ m(TimerDisplay::CountUp),
  8661. running(false), ar(false), startAction(new QAction(tr("Start"), NULL)),@/
  8662. stopAction(new QAction(tr("Stop"), NULL)),
  8663. resetAction(new QAction(tr("Reset"), NULL)),@/ f(QString("hh:mm:ss")),
  8664. relative(QTime::currentTime()), base(QTime(0, 0, 0))@/
  8665. {
  8666. connect(startAction, SIGNAL(triggered(bool)), this, SLOT(startTimer()));
  8667. connect(stopAction, SIGNAL(triggered(bool)), this, SLOT(stopTimer()));
  8668. connect(resetAction, SIGNAL(triggered(bool)), this, SLOT(reset()));
  8669. clock.setInterval(500);
  8670. clock.setSingleShot(false);
  8671. connect(&clock, SIGNAL(timeout()), this, SLOT(updateTime()));
  8672. setSegmentStyle(Filled);
  8673. updateDisplay();
  8674. }
  8675. @ The complicated bits are all in the |updateTime()| method. The behavior of
  8676. this function depends on the current |TimerMode| of the display.
  8677. @<TimerDisplay Implementation@>=
  8678. void TimerDisplay::updateTime()
  8679. {
  8680. QTime time;
  8681. int cseconds = 0;
  8682. int oseconds = 0;
  8683. int r = 0;
  8684. QTime nt = QTime(0, 0, 0);
  8685. int n = 0;
  8686. int bseconds = 0;
  8687. switch(m)@/
  8688. {@t\1@>@/
  8689. case TimerDisplay::CountUp:@/
  8690. @<Check for Timer Increment@>;
  8691. break;
  8692. case TimerDisplay::CountDown:@/
  8693. @<Check for Timer Decrement@>;
  8694. break;
  8695. case TimerDisplay::Clock:@/
  8696. @<Check for Clock Change@>;
  8697. break;
  8698. default:@/
  8699. Q_ASSERT_X(false, "updateTime", "invalid timer mode");
  8700. break;@t\2@>@/
  8701. }
  8702. updateDisplay();
  8703. }
  8704. @ To have the timer count up, we calculate the value that the timer should
  8705. indicate and compare it to the time indicated. If there is a difference, we
  8706. update the time to the new value and send emit a signal.
  8707. @<Check for Timer Increment@>=
  8708. @<Load seconds since base time into r@>@;
  8709. nt = nt.addSecs(r);
  8710. if(nt != s)
  8711. {
  8712. s = nt;
  8713. emit valueChanged(s);
  8714. }
  8715. @ Here we want to calculate the number of seconds in the current time, the
  8716. number of seconds in a base time, and the difference between the two. The
  8717. value loaded into oseconds could probably be cached.
  8718. @<Load seconds since base time into r@>=
  8719. #define TIMETOINT(t) ((t.hour() * 60 * 60) + (t.minute() * 60) + (t.second()))
  8720. time = QTime::currentTime();
  8721. cseconds = TIMETOINT(time);
  8722. oseconds = TIMETOINT(relative);
  8723. r = cseconds - oseconds;
  8724. @ The logic for a count down timer is very similar to the logic for a count up
  8725. timer. A key difference is that we don't want to continue counting down if the
  8726. timer has already reached 0.
  8727. @<Check for Timer Decrement@>=
  8728. if(s > QTime(0, 0, 0))@/
  8729. {@/
  8730. @<Load seconds since base time into r@>@;
  8731. bseconds = TIMETOINT(base);
  8732. n = bseconds - r;
  8733. nt = nt.addSecs(n);
  8734. if(nt != s)
  8735. {
  8736. s = nt;
  8737. emit valueChanged(s);
  8738. }
  8739. }
  8740. @ The clock mode is the simplest case as it just needs to find out if the time
  8741. has changed.
  8742. @<Check for Clock Change@>=
  8743. time = QTime::currentTime();
  8744. if(time != s)
  8745. {
  8746. s = time;
  8747. emit valueChanged(s);
  8748. }
  8749. @ When counting up or down, it is important to record the time at which the
  8750. timer starts. The clock that triggers time updates must also be started. The
  8751. timer also needs to reset its value if that behavior is desired.
  8752. @<TimerDisplay Implementation@>=
  8753. #define TIMESUBTRACT(t1, t2) (t1.addSecs(-(TIMETOINT(t2))).addSecs(-t2.msec()))
  8754. void TimerDisplay::startTimer()@t\2\2@>@/
  8755. {@t\1@>@/
  8756. if(!running)@/
  8757. {@t\1@>@/
  8758. relative = QTime::currentTime();
  8759. if(ar)@/
  8760. {
  8761. reset();
  8762. }
  8763. else
  8764. {
  8765. relative = TIMESUBTRACT(relative, s);
  8766. }
  8767. if(m == Clock)@/
  8768. {
  8769. updateTime();
  8770. }
  8771. base = s;
  8772. clock.start();@/
  8773. running = true;
  8774. emit runStateChanged(true);@t\2@>@/
  8775. }@t\2@>@/
  8776. }
  8777. @ Stopping the timer is a little simpler. Remember to stop the clock so we
  8778. aren't updating senselessly.
  8779. @<TimerDisplay Implementation@>=
  8780. void TimerDisplay::stopTimer()@t\2\2@>@/
  8781. {@t\1@>@/
  8782. if(running)@/
  8783. {@t\1@>@/
  8784. clock.stop();@/
  8785. running = false;
  8786. emit runStateChanged(false);@t\2@>@/
  8787. }@t\2@>@/
  8788. }
  8789. @ The clock is also stopped in the destructor.
  8790. @<TimerDisplay Implementation@>=
  8791. TimerDisplay::~TimerDisplay()
  8792. {
  8793. clock.stop();
  8794. }
  8795. @ The rest of the functions are trivial. There are functions for changing the
  8796. timer mode:
  8797. @<TimerDisplay Implementation@>=
  8798. void TimerDisplay::setCountUpMode()
  8799. {
  8800. m = TimerDisplay::CountUp;
  8801. }
  8802. void TimerDisplay::setCountDownMode()
  8803. {
  8804. m = TimerDisplay::CountDown;
  8805. }
  8806. void TimerDisplay::setClockMode()
  8807. {
  8808. m = TimerDisplay::Clock;
  8809. }
  8810. @ There are a few functions to obtain information about the state of the timer.
  8811. @<TimerDisplay Implementation@>=
  8812. QString TimerDisplay::value()
  8813. {
  8814. return s.toString(f);
  8815. }
  8816. QTime TimerDisplay::seconds()
  8817. {
  8818. return s;
  8819. }
  8820. TimerDisplay::TimerMode TimerDisplay::mode()
  8821. {
  8822. return m;
  8823. }
  8824. bool TimerDisplay::isRunning()
  8825. {
  8826. return running;
  8827. }
  8828. QTime TimerDisplay::resetValue()
  8829. {
  8830. return r;
  8831. }
  8832. QString TimerDisplay::displayFormat()
  8833. {
  8834. return f;
  8835. }
  8836. bool TimerDisplay::autoReset()
  8837. {
  8838. return ar;
  8839. }
  8840. @ There are also some functions for setting aspects of the timer state.
  8841. @<TimerDisplay Implementation@>=
  8842. void TimerDisplay::setTimer(QTime value)
  8843. {
  8844. if(value.isValid())
  8845. {
  8846. s = value;
  8847. updateDisplay();
  8848. emit valueChanged(value);
  8849. }
  8850. }
  8851. void TimerDisplay::setMode(TimerDisplay::TimerMode mode)
  8852. {
  8853. m = mode;
  8854. }
  8855. void TimerDisplay::setResetValue(QTime value)
  8856. {
  8857. r = value;
  8858. }
  8859. void TimerDisplay::setDisplayFormat(QString format)
  8860. {
  8861. f = format;
  8862. setNumDigits(format.length());
  8863. }
  8864. void TimerDisplay::setAutoReset(bool reset)
  8865. {
  8866. ar = reset;
  8867. }
  8868. @ |TimerDisplay| supports using the system clipboard to copy the current timer
  8869. value.
  8870. @<TimerDisplay Implementation@>=
  8871. void TimerDisplay::copyTimer()
  8872. {
  8873. QApplication::clipboard()->setText(value());
  8874. }
  8875. @ Resetting the timer is simple. We don't reset the timer if it is still running
  8876. mainly to prevent accidents.
  8877. @<TimerDisplay Implementation@>=
  8878. void TimerDisplay::reset()
  8879. {
  8880. if(!running)
  8881. {
  8882. s = r;
  8883. updateDisplay();
  8884. }
  8885. }
  8886. @ Finally, there is the function for changing the text of the display to the
  8887. current time value.
  8888. @<TimerDisplay Implementation@>=
  8889. void TimerDisplay::updateDisplay()
  8890. {
  8891. display(value());
  8892. }
  8893. @ Exposing |TimerDisplay| to the host environment is simple.
  8894. @<Function prototypes for scripting@>=
  8895. QScriptValue constructTimerDisplay(QScriptContext *context,
  8896. QScriptEngine *engine);
  8897. void setTimerDisplayProperties(QScriptValue value, QScriptEngine *engine);
  8898. @ The engine must be informed of the script constructor.
  8899. @<Set up the scripting engine@>=
  8900. constructor = engine->newFunction(constructTimerDisplay);
  8901. value = engine->newQMetaObject(&TimerDisplay::staticMetaObject, constructor);
  8902. engine->globalObject().setProperty("TimerDisplay", value);
  8903. @ The implementation of these functions is trivial.
  8904. @<Functions for scripting@>=
  8905. QScriptValue constructTimerDisplay(QScriptContext *, QScriptEngine *engine)
  8906. {
  8907. QScriptValue object = engine->newQObject(new TimerDisplay);
  8908. setTimerDisplayProperties(object, engine);
  8909. return object;
  8910. }
  8911. void setTimerDisplayProperties(QScriptValue value, QScriptEngine *engine)
  8912. {
  8913. setQLCDNumberProperties(value, engine);
  8914. }
  8915. @** The Human Computer Interface.
  8916. \noindent A few classes are required for putting the rest of the program
  8917. together in a way that it can be used by a human. There is a layout class for
  8918. arranging widgets in a way that is not simple with the layouts provided by Qt.
  8919. There are classes for labeling the various indicators. There are also window
  8920. classes that put all of this together in a useful and usable way. One of these
  8921. classes is currently depreciated.
  8922. @* The PackLayout Class.
  8923. \noindent The |PackLayout| class provides functionality similar to the
  8924. |QBoxLayout| class in Qt. It allows the construction of a row or column of
  8925. widgets. Each item will take up space along the orientation of the layout equal
  8926. to its size hint except for the last widget which will take up all remaining
  8927. space. Widgets will be resized in the direction perpendicular to the orientation
  8928. of the layout to use all available space.
  8929. This class was originally written with the |WidgetDecorator| class which we will
  8930. get to later in mind, but it has found use in other places where the left or top
  8931. most widgets should not be resized.
  8932. By default, a new |PackLayout| will arrange widgets horizontally. This can be
  8933. changed with a call to |setOrientation()|.
  8934. @<Class declarations@>=
  8935. class PackLayout : public QLayout@/
  8936. {@/
  8937. int doLayout(const QRect &rect, bool testOnly) const;@/
  8938. QList<QLayoutItem *> itemList;@/
  8939. Qt::Orientations@, orientation;@/
  8940. public:@/
  8941. PackLayout(QWidget *parent, int margin = 0, int spacing = -1);
  8942. PackLayout(int spacing = -1);
  8943. ~PackLayout();
  8944. void addItem(QLayoutItem *item);
  8945. Qt::Orientations@, expandingDirections() const;
  8946. bool hasHeightForWidth() const;
  8947. int heightForWidth(int width) const;
  8948. int count() const;
  8949. QLayoutItem *itemAt(int index) const;
  8950. QSize minimumSize() const;
  8951. void setGeometry(const QRect &rect);
  8952. void setOrientation(Qt::Orientations direction);
  8953. QSize sizeHint() const;
  8954. QLayoutItem *takeAt(int index);
  8955. };
  8956. @ The interesting portion of this class is in |doLayout()|. This function goes
  8957. over the items in the layout and sets the geometry appropriately.
  8958. The seemingly odd choice of returning |y| at the end of this function (indeed of
  8959. having a return value at all) is to allow this function to provide the return
  8960. value needed in |heightForWidth()|.
  8961. If |testOnly| is set to |true|, |y| will be calculated, but the widget geometry
  8962. will not be changed.
  8963. @<PackLayout Implementation@>=
  8964. int PackLayout::doLayout(const QRect &rect, bool testOnly) const
  8965. {
  8966. int x = rect.x();
  8967. int y = rect.y();
  8968. QLayoutItem *item;
  8969. if(orientation == Qt::Horizontal)
  8970. {
  8971. @<Lay the widgets out horizontally@>@;
  8972. }
  8973. else
  8974. {
  8975. @<Lay the widgets out vertically@>@;
  8976. }
  8977. return y;
  8978. }
  8979. @ To lay the widgets out horizontally, we go over each item in the list taking
  8980. the width of the size hint and spacing into account unless the item is the last
  8981. item in the list, in which case the right of the widget needs to be at the end
  8982. of the available space. We use the foreach construction that Qt provides to
  8983. iterate over each item in the list in much the same way as foreach constructions
  8984. are used in languages that support them directly.
  8985. @<Lay the widgets out horizontally@>=
  8986. foreach(item, itemList)
  8987. {
  8988. int nextX = x + item->sizeHint().width() + spacing();
  8989. int right = x + item->sizeHint().width();
  8990. if(item == itemList.last())
  8991. {
  8992. right = rect.right();
  8993. }
  8994. int bottom = rect.bottom();
  8995. if(!testOnly)
  8996. {
  8997. item->setGeometry(QRect(QPoint(x, y), QPoint(right, bottom)));
  8998. }
  8999. x = nextX;
  9000. }
  9001. @ Laying out the widgets vertically is very similar.
  9002. @<Lay the widgets out vertically@>=
  9003. foreach(item, itemList)
  9004. {
  9005. int nextY = y + item->sizeHint().height() + spacing();
  9006. int bottom = y + item->sizeHint().height();
  9007. if(item == itemList.last())
  9008. {
  9009. bottom = rect.bottom();
  9010. }
  9011. int right = rect.right();
  9012. if(!testOnly)
  9013. {
  9014. item->setGeometry(QRect(QPoint(x, y), QPoint(right, bottom)));
  9015. }
  9016. y = nextY;
  9017. }
  9018. @ As a layout class, there are a number of things the class should be able to do
  9019. in order to play nicely with other classes. One of these is determining the
  9020. minimum size of the layout. The minimum size of the layout is equal to the space
  9021. required for each item in the layout plus the margin space. The margin space
  9022. will be equal to twice the specified margin in each direction to account for a
  9023. top, bottom, left, and right margin.
  9024. @<PackLayout Implementation@>=
  9025. QSize PackLayout::minimumSize() const
  9026. {
  9027. QSize size;
  9028. QLayoutItem *item;
  9029. foreach(item, itemList)
  9030. {
  9031. if(orientation == Qt::Horizontal)
  9032. {
  9033. size += QSize(item->minimumSize().width(), 0);
  9034. if(size.height() < item->minimumSize().height())
  9035. {
  9036. size.setHeight(item->minimumSize().height());
  9037. }
  9038. }
  9039. else
  9040. {
  9041. size += QSize(0, item->minimumSize().height());
  9042. if(size.width() < item->minimumSize().width())
  9043. {
  9044. size.setWidth(item->minimumSize().width());
  9045. }
  9046. }
  9047. }
  9048. size += QSize(2*margin(), 2*margin());
  9049. return size;
  9050. }
  9051. @ |PackLayout| features two constructors. One allows for setting the margin,
  9052. spacing, and a parent widget at the time of construction. The other creates a
  9053. parentless layout which will have to be added to another widget or layout.
  9054. @<PackLayout Implementation@>=
  9055. PackLayout::PackLayout(QWidget *parent, int margin, int spacing) :
  9056. QLayout(parent)@/
  9057. {
  9058. setMargin(margin);
  9059. setSpacing(spacing);
  9060. setOrientation(Qt::Horizontal);
  9061. }
  9062. PackLayout::PackLayout(int spacing)
  9063. {
  9064. setSpacing(spacing);
  9065. setOrientation(Qt::Horizontal);
  9066. }
  9067. @ In Qt, items in a layout are owned by that layout. When the layout is
  9068. destroyed, all of the items in that layout must also be deleted.
  9069. @<PackLayout Implementation@>=
  9070. PackLayout::~PackLayout()
  9071. {
  9072. QLayoutItem *item;
  9073. while((item = takeAt(0)))
  9074. {
  9075. delete item;
  9076. }
  9077. }
  9078. @ Deleting the items uses the |takeAt()| method to remove each widget from the
  9079. layout prior to deleting it. The item requested should exist, but if it doesn't,
  9080. |NULL| is returned.
  9081. @<PackLayout Implementation@>=
  9082. QLayoutItem* PackLayout::takeAt(int index)
  9083. {
  9084. if(index >= 0 && index < itemList.size())
  9085. {
  9086. return itemList.takeAt(index);
  9087. }
  9088. else
  9089. {
  9090. return NULL;
  9091. }
  9092. }
  9093. @ If we are interested in which item is in a particular position in the layout
  9094. but do not want to remove it from the layout, |itemAt()| provides that.
  9095. @<PackLayout Implementation@>=
  9096. QLayoutItem* PackLayout::itemAt(int index) const
  9097. {
  9098. if(index >= 0 && index < itemList.size())
  9099. {
  9100. return itemList.at(index);
  9101. }
  9102. else
  9103. {
  9104. return NULL;
  9105. }
  9106. }
  9107. @ A layout class is not very useful unless there is a way to get items into the
  9108. layout. The |QLayoutItem| class is designed in such a way that it is possible to
  9109. pass pointers to objects that inherit |QLayout| or |QWidget|.
  9110. The base |QLayout| class provides an |addWidget()| method that will use our
  9111. version of |addItem()|. That should be used when adding a widget to the layout.
  9112. The Qt documentation recommends also providing an |addLayout()| method so that
  9113. other code does not need to call this method, but that has not been provided
  9114. yet.
  9115. @<PackLayout Implementation@>=
  9116. void PackLayout::addItem(QLayoutItem *item)
  9117. {
  9118. itemList.append(item);
  9119. }
  9120. @ It is sometimes useful to know how many items are in a layout.
  9121. @<PackLayout Implementation@>=
  9122. int PackLayout::count() const@;@/
  9123. {@/
  9124. return itemList.size();@/
  9125. }
  9126. @ A few more functions are needed to make the layout class work well with other
  9127. classes. For more details, please consult the Qt Reference
  9128. Documentation\nfnote{Qt Reference Documentation\par\indent\hbox{%
  9129. \pdfURL{http://doc.trolltech.com/4.3/index.html}%
  9130. {http://doc.trolltech.com/4.3/index.html}}}
  9131. @<PackLayout Implementation@>=
  9132. Qt::Orientations PackLayout::expandingDirections() const
  9133. {
  9134. return Qt::Vertical | Qt::Horizontal;
  9135. }
  9136. bool PackLayout::hasHeightForWidth() const@t\2\2@>@/
  9137. {@t\1@>@/
  9138. return false;@t\2@>@/
  9139. }@/
  9140. int PackLayout::heightForWidth(int width) const
  9141. {
  9142. return doLayout(QRect(0, 0, width, 0), true);
  9143. }
  9144. void PackLayout::setGeometry(const QRect &rect)
  9145. {
  9146. QLayout::setGeometry(rect);
  9147. doLayout(rect, false);
  9148. }
  9149. QSize PackLayout::sizeHint() const
  9150. {
  9151. return minimumSize();
  9152. }
  9153. @ It was mentioned previously that this layout is capable of lining widgets up
  9154. in a row or presenting them in a column. This is done with the
  9155. |setOrientation()| method.
  9156. @<PackLayout Implementation@>=
  9157. void PackLayout::setOrientation(Qt::Orientations direction)
  9158. {
  9159. orientation = direction;
  9160. doLayout(geometry(), false);
  9161. }
  9162. @* The SceneButton Class.
  9163. \noindent Ordinarily, mouse down events that are passed from a |QGraphicsView|
  9164. to an interactive |QGraphicsScene| will continue to pass that click down to an
  9165. item in the scene. This class is used when we are interested in a click anywhere
  9166. in the view and it doesn't really matter where in the scene that click occurred
  9167. or even if there is a graphics item at that point. Any click passed to the
  9168. |SceneButton| will cause the scene to emit a signal containing the screen
  9169. coordinates of the click.
  9170. This was originally designed for use in the |WidgetDecorator| class. While the
  9171. functionality provided is not currently used, the original plan was to use this
  9172. to provide access to configuration options.
  9173. It is possible that this class is no longer necessary even if features it was
  9174. made for are implemented.
  9175. @<Class declarations@>=
  9176. class SceneButton : public QGraphicsScene@/
  9177. {@/
  9178. Q_OBJECT@;
  9179. public:@/
  9180. SceneButton();
  9181. ~SceneButton();
  9182. protected:@/
  9183. void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent);
  9184. signals:@/
  9185. void clicked(QPoint pos);
  9186. };
  9187. @ The implementation is trivial.
  9188. @<SceneButton Implementation@>=
  9189. SceneButton::SceneButton() : QGraphicsScene()@/
  9190. {
  9191. /* Nothing has to be done here. */
  9192. }
  9193. SceneButton::~SceneButton()
  9194. {
  9195. /* Nothing has to be done here. */
  9196. }
  9197. void SceneButton::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
  9198. {
  9199. emit clicked(mouseEvent->buttonDownScreenPos(mouseEvent->button()));
  9200. }
  9201. @* The WidgetDecorator Class.
  9202. \noindent The |WidgetDecorator| class provides a way to label various widgets
  9203. while also providing additional options for interacting with them. The
  9204. decoration can exist to the left or atop the widget being decorated. When the
  9205. label is to the left of the widget, the label text is rotated.
  9206. This class is likely to change considerably in the future as features are added
  9207. that allow actions to be added to the decoration to allow various configuration
  9208. options.
  9209. @<Class declarations@>=
  9210. class WidgetDecorator : public QWidget@/
  9211. {
  9212. Q_OBJECT@;
  9213. PackLayout *layout;
  9214. QGraphicsView *label;
  9215. QGraphicsTextItem *text;
  9216. SceneButton *scene;
  9217. public:@/
  9218. WidgetDecorator(QWidget *widget, const QString &labeltext,@|
  9219. Qt::Orientations@, orientation = Qt::Horizontal,@|
  9220. QWidget *parent = NULL, Qt::WindowFlags f = 0);
  9221. ~WidgetDecorator();
  9222. void setBackgroundBrush(QBrush background);
  9223. void setTextColor(QColor color);
  9224. };
  9225. @ Almost everything this class currently does is handled in the constructor.
  9226. @<WidgetDecorator Implementation@>=
  9227. WidgetDecorator::WidgetDecorator(QWidget *widget, const QString &labeltext,
  9228. Qt::Orientations orientation,
  9229. QWidget *parent, Qt::WindowFlags f)@/:
  9230. QWidget(parent, f), label(new QGraphicsView()),
  9231. scene(new SceneButton())@t\2@>@/
  9232. {
  9233. layout = new PackLayout(this);
  9234. layout->setOrientation(orientation);
  9235. @<Prepare the graphics view@>@;
  9236. @<Add the label to the scene@>@;
  9237. @<Adjust the decoration width@>@;
  9238. @<Pack widgets into the layout@>@;
  9239. }
  9240. @ The decoration is a |QGraphicsView|. To get this to look right, we need to
  9241. make sure there aren't any scroll bars and there shouldn't be a frame
  9242. surrounding it. While we're at it, we allow it to accept clicks, though this
  9243. functionality is not yet used.
  9244. @<Prepare the graphics view@>=
  9245. label->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  9246. label->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  9247. label->setFrameShape(QFrame::NoFrame);
  9248. label->setInteractive(true);
  9249. @ The |QGraphicsView| needs a scene to display anything. The scene consists of a
  9250. background which, by default is solid cyan. This can be changed later by setting
  9251. a different background brush. Text also needs to be added to the scene. If the
  9252. decoration is to the left of the widget, the text needs to be rotated.
  9253. @<Add the label to the scene@>=
  9254. scene->setBackgroundBrush(Qt::cyan);
  9255. text = scene->addText(labeltext);
  9256. if(orientation == Qt::Horizontal)
  9257. {
  9258. text->rotate(270.0);
  9259. }
  9260. label->setScene(scene);
  9261. @ The decoration should have the text centered in the view. The widget should
  9262. also be no wider (or taller for horizontal orientation) than necessary for the
  9263. text.
  9264. The case for horizontal orientation here may seem a little strange, however the
  9265. dimensions of the bounding rectangle are not affected by rotation. This means
  9266. that even though we want the width of the rotated text, this is the same as the
  9267. height of the text.
  9268. @<Adjust the decoration width@>=
  9269. if(orientation == Qt::Horizontal)
  9270. {
  9271. label->setMaximumWidth((int)(text->boundingRect().height() + 1));
  9272. }
  9273. else
  9274. {
  9275. label->setMaximumHeight((int)(text->boundingRect().height() + 1));
  9276. }
  9277. label->centerOn(text);
  9278. @ Once the decoration is ready, the decoration and the widget being decorated
  9279. can be added to the layout. A minimum size for the compound widget is also
  9280. calculated.
  9281. @<Pack widgets into the layout@>=
  9282. layout->addWidget(label);
  9283. layout->addWidget(widget);
  9284. if(orientation == Qt::Horizontal)
  9285. {
  9286. setMinimumSize(widget->sizeHint().width() + label->sizeHint().width(),
  9287. widget->sizeHint().height());
  9288. }
  9289. else
  9290. {
  9291. setMinimumSize(widget->sizeHint().width(),
  9292. widget->sizeHint().height() + label->sizeHint().height());
  9293. }
  9294. @ As mentioned previously, it is possible to change the background pattern for
  9295. the decoration. It is also possible to change the color of the text.
  9296. @<WidgetDecorator Implementation@>=
  9297. void WidgetDecorator::setBackgroundBrush(QBrush background)
  9298. {
  9299. scene->setBackgroundBrush(background);
  9300. }
  9301. void WidgetDecorator::setTextColor(QColor color)
  9302. {
  9303. text->setDefaultTextColor(color);
  9304. }
  9305. @ Finally, there is a destructor.
  9306. @<WidgetDecorator Implementation@>=
  9307. WidgetDecorator::~WidgetDecorator()
  9308. {
  9309. /* Nothing has to be done here. */
  9310. }
  9311. @ In order to create a decorated widget from a script, we need these functions.
  9312. @<Function prototypes for scripting@>=
  9313. void setWidgetDecoratorProperties(QScriptValue value, QScriptEngine *engine);
  9314. QScriptValue constructWidgetDecorator(QScriptContext *context,
  9315. QScriptEngine *engine);
  9316. @ The scripting engine must be informed of this function.
  9317. @<Set up the scripting engine@>=
  9318. constructor = engine->newFunction(constructWidgetDecorator);
  9319. value = engine->newQMetaObject(&WidgetDecorator::staticMetaObject, constructor);
  9320. engine->globalObject().setProperty("WidgetDecorator", value);
  9321. @ The constructor is slightly more complex than other script constructors, but
  9322. still simple.
  9323. @<Functions for scripting@>=
  9324. QScriptValue constructWidgetDecorator(QScriptContext *context,
  9325. QScriptEngine *engine)
  9326. {
  9327. QWidget *widget = argument<QWidget *>(0, context);
  9328. QString text = argument<QString>(1, context);
  9329. Qt::Orientations@, orientation;
  9330. switch(argument<int>(2, context))@/
  9331. {@t\1@>@/
  9332. case 2:@/
  9333. orientation = Qt::Vertical;
  9334. break;
  9335. default:@/
  9336. orientation = Qt::Horizontal;
  9337. break;@t\2@>@/
  9338. }
  9339. QScriptValue object =
  9340. engine->newQObject(new WidgetDecorator(widget, text, orientation));
  9341. setWidgetDecoratorProperties(object, engine);
  9342. return object;
  9343. }
  9344. void setWidgetDecoratorProperties(QScriptValue value, QScriptEngine *engine)
  9345. {
  9346. setQWidgetProperties(value, engine);
  9347. }
  9348. @* The LogEditWindow Class.
  9349. \noindent This class will be depreciated in a future release once I have
  9350. confirmed that the class can be replaced by the configuration system. It has not
  9351. been updated to support new functionality added in version 1.2.3 and use of this
  9352. class is highly discouraged.
  9353. While the logging window provided in the example configuration is fine for
  9354. recording an existing roast, there are some who would like to be able to use
  9355. \pn{} to work with data collected with a manual logger. Different controls are
  9356. useful in such a case. The |LogEditWindow| provides this.
  9357. @<Class declarations@>=
  9358. class LogEditWindow : public QMainWindow@/
  9359. {@t\1@>@/
  9360. Q_OBJECT@;
  9361. QWidget *centralWidget;
  9362. PackLayout *mainLayout;
  9363. QHBoxLayout *addRowsLayout;
  9364. QLabel *startTimeLabel;
  9365. QTimeEdit *startTime;
  9366. QLabel *endTimeLabel;
  9367. QTimeEdit *endTime;
  9368. QLabel *intervalLabel;
  9369. QSpinBox *interval;
  9370. QPushButton *addRows;
  9371. QAction *saveXml;
  9372. QAction *saveCsv;
  9373. QAction *openXml;
  9374. MeasurementModel *model;
  9375. QTableView *log;@/
  9376. @t\4@>private slots@t\kern-3pt@>:@/
  9377. void addTheRows();
  9378. void saveXML();
  9379. void saveCSV();
  9380. void openXML();@/
  9381. protected:@/
  9382. void closeEvent(QCloseEvent *event);@/
  9383. public:@/
  9384. LogEditWindow();@t\2@>@/
  9385. }@t\kern-3pt@>;
  9386. @ This window provides controls for adding rows to a measurement. Typically, the
  9387. data on a manual roast log will have measurements at regular intervals with the
  9388. possible exception of a few points where there are control changes or the end of
  9389. the batch. The routine for adding rows is capable of adding a single row, rows
  9390. in a range of times at regular intervals, or rows in a range of times at regular
  9391. intervals plus one time at the end.
  9392. @<LogEditWindow Implementation@>=
  9393. void LogEditWindow::addTheRows()
  9394. {
  9395. QTime s = startTime->time();
  9396. while(s < endTime->time())
  9397. {
  9398. model->newMeasurement(Measurement(0, s), 1);
  9399. s = s.addSecs(interval->value());
  9400. }
  9401. model->newMeasurement(Measurement(0, endTime->time()), 1);
  9402. }
  9403. @ The window is prepared in its constructor.
  9404. @<LogEditWindow Implementation@>=
  9405. LogEditWindow::LogEditWindow() : QMainWindow(NULL),
  9406. centralWidget(new QWidget(NULL)), mainLayout(new PackLayout(0)),@|
  9407. addRowsLayout(new QHBoxLayout(NULL)),
  9408. startTimeLabel(new QLabel("Start Time")),@|
  9409. startTime(new QTimeEdit(QTime(0, 0, 0, 0))),@|
  9410. endTimeLabel(new QLabel("End Time")),
  9411. endTime(new QTimeEdit(QTime(0, 20, 0, 0))),@|
  9412. intervalLabel(new QLabel("Interval (seconds)")),@|
  9413. interval(new QSpinBox()),
  9414. addRows(new QPushButton("Add Rows")),@|
  9415. saveXml(new QAction(tr("Save Profile As..."), NULL)),@|
  9416. saveCsv(new QAction(tr("Export CSV"), NULL)),@|
  9417. openXml(new QAction(tr("Load Target Profile..."), NULL)),@|
  9418. model(new MeasurementModel()),
  9419. log(new QTableView())@/
  9420. {
  9421. @<Restore editor window geometry from settings@>@;
  9422. @<Set up the editor control bar@>@;
  9423. @<Prepare the model@>@;
  9424. @<Prepare the log table@>@;
  9425. mainLayout->addItem(addRowsLayout);
  9426. mainLayout->addWidget(log);
  9427. centralWidget->setLayout(mainLayout);
  9428. setCentralWidget(centralWidget);
  9429. QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
  9430. fileMenu->addAction(openXml);
  9431. connect(openXml, SIGNAL(triggered()), this, SLOT(openXML()));
  9432. fileMenu->addAction(saveXml);
  9433. connect(saveXml, SIGNAL(triggered()), this, SLOT(saveXML()));
  9434. fileMenu->addAction(saveCsv);
  9435. connect(saveCsv, SIGNAL(triggered()), this, SLOT(saveCSV()));
  9436. }
  9437. @ The window keeps its previous size and location in settings. These need to be
  9438. restored when a new window is created.
  9439. @<Restore editor window geometry from settings@>=
  9440. QSettings settings;
  9441. resize(settings.value("logSize", QSize(620,400)).toSize());
  9442. move(settings.value("logPos", QPoint(200,60)).toPoint());
  9443. @ When a new window is opened, it starts with an empty profile. If this is used
  9444. to manually enter a profile rather than edit an existing profile, rows will need
  9445. to be added. For this, we provide a set of controls where a start time, an end
  9446. time, and an interval in seconds is specified along with a button that, when
  9447. pressed, will produce a row in the model for the starting time, the ending time,
  9448. and regularly spaced times between the two. If only a single row is needed, this
  9449. can be produced by setting the start and end times the same.
  9450. @<Set up the editor control bar@>=
  9451. mainLayout->setOrientation(Qt::Vertical);
  9452. addRowsLayout->addSpacing(10);
  9453. addRowsLayout->addWidget(startTimeLabel);
  9454. addRowsLayout->addWidget(startTime);
  9455. addRowsLayout->addSpacing(10);
  9456. startTime->setDisplayFormat("mm:ss");
  9457. addRowsLayout->addWidget(endTimeLabel);
  9458. addRowsLayout->addWidget(endTime);
  9459. addRowsLayout->addSpacing(10);
  9460. endTime->setDisplayFormat("mm:ss");
  9461. addRowsLayout->addWidget(intervalLabel);
  9462. addRowsLayout->addWidget(interval);
  9463. addRowsLayout->addSpacing(10);
  9464. interval->setRange(0, 60);
  9465. interval->setValue(30);
  9466. addRowsLayout->addWidget(addRows);
  9467. addRowsLayout->addSpacing(10);
  9468. connect(addRows, SIGNAL(clicked()), this, SLOT(addTheRows()));
  9469. @ The model will have three columns: Time, Temperature, and Annotation. This
  9470. probably should not be hard coded.
  9471. @<Prepare the model@>=
  9472. model->setHeaderData(0, Qt::Horizontal, "Time");
  9473. model->setHeaderData(1, Qt::Horizontal, "Temperature");
  9474. model->setHeaderData(2, Qt::Horizontal, "Annotation");
  9475. model->clear();
  9476. @ The profile is presented in a table view. The columns should be wide enough to
  9477. contain a label, the data contained in the column, and an editor delegate.
  9478. @<Prepare the log table@>=
  9479. log->setModel(model);
  9480. log->setColumnWidth(0, 100);
  9481. log->setColumnWidth(1, 100);
  9482. log->setColumnWidth(2, 100);
  9483. @ Most users will want to save a profile after they've edited it. We also
  9484. provide CSV export here. Note that this class only supports logs with a single
  9485. temperature and a single annotation column. As the class is considered
  9486. depreciated, it will not be extended to support arbitrarily many columns.
  9487. @<LogEditWindow Implementation@>=
  9488. void LogEditWindow::saveXML()
  9489. {
  9490. QSettings settings;
  9491. QString lastDir = settings.value("lastDirectory").toString();
  9492. QString filename = QFileDialog::getSaveFileName(this, tr("Save Log As..."),
  9493. lastDir, "", 0);
  9494. QFile file(filename);
  9495. XMLOutput writer(model, &file, 0);
  9496. writer.addTemperatureColumn("Temperature", 1);
  9497. writer.addAnnotationColumn("Annotation", 2);
  9498. if(writer.output())
  9499. {
  9500. QFileInfo info(filename);
  9501. QDir directory = info.dir();
  9502. lastDir = directory.path();
  9503. settings.setValue("lastDirectory", lastDir);
  9504. }
  9505. }
  9506. void LogEditWindow::saveCSV()
  9507. {
  9508. QSettings settings;
  9509. QString lastDir = settings.value("lastDirectory").toString();
  9510. QString filename = QFileDialog::getSaveFileName(this, tr("Export As..."),
  9511. lastDir, "", 0);
  9512. QFile file(filename);
  9513. CSVOutput writer(model, &file, 0);
  9514. writer.addTemperatureColumn("Temperature", 1);
  9515. writer.addAnnotationColumn("Annotation", 2);
  9516. if(writer.output())
  9517. {
  9518. QFileInfo info(filename);
  9519. QDir directory = info.dir();
  9520. lastDir = directory.path();
  9521. settings.setValue("lastDirectory", lastDir);
  9522. }
  9523. }
  9524. @ Some may want to open a previously saved profile, for example, to adjust the
  9525. position of an annotation. Note that this class is not appropriate for editing
  9526. profiles with more than one temperature column.
  9527. @<LogEditWindow Implementation@>=
  9528. void LogEditWindow::openXML()
  9529. {
  9530. QSettings settings;
  9531. QString lastDir = settings.value("lastDirectory").toString();
  9532. QString filename = QFileDialog::getOpenFileName(this, tr("Open XML Log..."),
  9533. lastDir, "", 0);
  9534. if(filename.isNull())
  9535. {
  9536. return;
  9537. }
  9538. QFile file(filename);
  9539. XMLInput reader(&file, 1);
  9540. connect(&reader, SIGNAL(measure(Measurement, int)),
  9541. model, SLOT(newMeasurement(Measurement, int)));
  9542. connect(&reader, SIGNAL(annotation(QString, int, int)),
  9543. model, SLOT(newAnnotation(QString, int, int)));
  9544. if(reader.input())
  9545. {
  9546. QFileInfo info(filename);
  9547. setWindowTitle(QString(tr("%1 - %2")).@|
  9548. arg(QCoreApplication::applicationName()).arg(info.baseName()));
  9549. QDir directory = info.dir();
  9550. lastDir = directory.path();
  9551. settings.setValue("lastDirectory", lastDir);
  9552. }
  9553. }
  9554. @ The window should remember its last size and position, so we store this
  9555. information in settings when the window is closed.
  9556. @<LogEditWindow Implementation@>=
  9557. void LogEditWindow::closeEvent(QCloseEvent *event)
  9558. {
  9559. QSettings settings;
  9560. settings.setValue("logSize", size());
  9561. settings.setValue("logPos", pos());
  9562. event->accept();
  9563. }
  9564. @ One function is required to instantiate this class from a script.
  9565. @<Function prototypes for scripting@>=
  9566. QScriptValue constructLogEditWindow(QScriptContext *context,
  9567. QScriptEngine *engine);
  9568. @ The engine must be informed of this function.
  9569. @<Set up the scripting engine@>=
  9570. constructor = engine->newFunction(constructLogEditWindow);
  9571. value = engine->newQMetaObject(&LogEditWindow::staticMetaObject, constructor);
  9572. engine->globalObject().setProperty("LogEditWindow", value);
  9573. @ The constructor just creates the window and passes it back to the engine.
  9574. @<Functions for scripting@>=
  9575. QScriptValue constructLogEditWindow(QScriptContext *, QScriptEngine *engine)
  9576. {
  9577. QScriptValue object = engine->newQObject(new LogEditWindow);
  9578. return object;
  9579. }
  9580. @** File IO.
  9581. \noindent So far, the data is all stored in memory. It is often useful to save
  9582. data to a file or read back previously saved data. Presently, two formats are
  9583. supported: an XML format which can also be read back in and CSV which can easily
  9584. be used with many external tools.
  9585. File IO is handled by a few classes: one per input format and one per output
  9586. format. The classes in the following sections should be simple enough to follow
  9587. that it should be clear how to extend \pn{} to support other formats if needed.
  9588. Should additional output formats be required, it may be beneficial to
  9589. reimplement the serializers as subclasses of a new abstract serializer class in
  9590. order to share common code among them where reusing \cweb{} chunks is not an
  9591. appropriate technique.
  9592. @* XML Output.
  9593. \noindent An XML format has been chosen as the native format for \pn{} because
  9594. of Qt's excellent support for reading and writing such documents. Using this
  9595. capability is less error prone than developing a new, more compact format.
  9596. Another reason to choose XML is that it becomes quite easy to modify saved data
  9597. in a text editor and still end up with something \pn{} will understand.
  9598. The structure of the file we will produce is simple, however it has been
  9599. modified from a simpler structure that was used in versions of Typica prior to
  9600. 1.2.3. How to read these files can be determined by the document type found at
  9601. the start of the file. At the start of the file, there should be one or more
  9602. {\tt <tempseries>} elements and one or more {\tt <noteseries>} elements. These
  9603. are empty elements with a {\tt name} attribute which can be used to label the
  9604. column in a view. Once these column declarations have been written, a
  9605. {\tt <roast>} element is produced which contains a set of zero or more
  9606. {\tt <tuple>} elements. Each tuple contains one {\tt <time>} element containing
  9607. the time of the measurement relative to the start of the batch and optionally
  9608. one or more {\tt <temperature>} and {\tt <annotation>} elements containing
  9609. measurement and annotation data associated with that time. The
  9610. {\tt <temperature>} and {\tt <annotation>} elements have a {\tt series}
  9611. attribute where the value of the attribute matches the {\tt name} attribute of a
  9612. {\tt <tempseries>} or {\tt <noteseries>} element which allows each measurement
  9613. to be placed in the correct data series regardless of element ordering in the
  9614. document.
  9615. There are certain oddities about this format compared with other XML based
  9616. formats. The order of some elements in the current implementation affects the
  9617. behavior of the program and there is no longer a proper root element. This
  9618. format may be extended in future versions of \pn{} to support additional
  9619. functionality or to improve the robustness of the format. Should such
  9620. modifications occur, an effort should be made to ensure that \pn{} continues to
  9621. support the import of old data.
  9622. As of version 1.0.8, this class is derived from |QObject| for easier integration
  9623. with the scripting engine.
  9624. The |temperatureColumns| and |annotationColumns| member data structures are
  9625. currently a |QMap| rather than a |QHash| because the number of data series in a
  9626. single file is likely to be small enough that the difference in lookup time
  9627. should be negligeable and the ability to iterate over the keys in the |QMap| in
  9628. sorted order is useful.
  9629. @<Class declarations@>=
  9630. class XMLOutput : public QObject@/
  9631. {@/
  9632. Q_OBJECT@;@/
  9633. MeasurementModel *data;
  9634. QIODevice *out;
  9635. int time;
  9636. QMap<int, QString> temperatureColumns;
  9637. QMap<int, QString> annotationColumns;
  9638. public:@/
  9639. XMLOutput(MeasurementModel *model, QIODevice *device, int timec = 0);
  9640. void addTemperatureColumn(const QString &series, int column);
  9641. void addAnnotationColumn(const QString &series, int column);
  9642. void setModel(MeasurementModel *model);
  9643. void setTimeColumn(int column);
  9644. void setDevice(QIODevice *device);
  9645. bool output();
  9646. };
  9647. @ The interesting part of this class is the |output| routine. This goes over the
  9648. data in the model and constructs an appropriate XML document. If the operation
  9649. fails, the function returns |false|, otherwise it returns |true|.
  9650. @<XMLOutput Implementation@>=
  9651. bool XMLOutput::output()@t\2\2@>@/
  9652. {@t\1@>@/
  9653. if(!out->open(QIODevice::WriteOnly | QIODevice::Text))@/
  9654. {@t\1@>@/
  9655. return false;@t\2@>@/
  9656. }@/
  9657. QXmlStreamWriter xmlout(out);
  9658. xmlout.writeStartDocument("1.0");
  9659. xmlout.writeDTD("<!DOCTYPE roastlog2.0>");
  9660. xmlout.writeStartElement("roastlog");
  9661. @<Output the column declarations@>@;
  9662. xmlout.writeStartElement("roast");
  9663. bool oresult;
  9664. for(int i = 0; i < data->rowCount(); i++)@/
  9665. {
  9666. @<Check if row should be output@>@;
  9667. if(oresult)
  9668. {
  9669. @<Output tuple element@>@;
  9670. }
  9671. }
  9672. xmlout.writeEndElement();
  9673. xmlout.writeEndElement();
  9674. xmlout.writeEndDocument();
  9675. out->close();@/
  9676. return true;@t\2@>@/
  9677. }
  9678. @ Temperature column declarations are output before annotation column
  9679. declarations. Within each category, column declarations are output in order by
  9680. column number.
  9681. @<Output the column declarations@>=
  9682. foreach(int c, temperatureColumns.keys())
  9683. {
  9684. xmlout.writeStartElement("tempseries");
  9685. xmlout.writeAttribute("name", temperatureColumns.value(c));
  9686. xmlout.writeEndElement();
  9687. }
  9688. foreach(int c, annotationColumns.keys())
  9689. {
  9690. xmlout.writeStartElement("noteseries");
  9691. xmlout.writeAttribute("name", annotationColumns.value(c));
  9692. xmlout.writeEndElement();
  9693. }
  9694. @ When checking a row in the model to determine if it contains values that need
  9695. to be written, we want to know if any of the temperature or annotation columns
  9696. contain a value. If at least one of these columns is not empty for this row, we
  9697. need to output a tuple for that row.
  9698. @<Check if row should be output@>=
  9699. oresult = false;@/
  9700. foreach(int c, temperatureColumns.keys())@/
  9701. {@t\1@>@/
  9702. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  9703. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  9704. {@t\1@>@/
  9705. oresult = true;
  9706. break;@t\2@>@/
  9707. }@t\2@>@/
  9708. }@/
  9709. if(oresult == false)@/
  9710. {@t\1@>@/
  9711. foreach(int c, annotationColumns.keys())@/
  9712. {@t\1@>@/
  9713. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  9714. !(data->data(data->index(i, c), Qt::DisplayRole).toString().
  9715. isEmpty()))@/
  9716. {@t\1@>@/
  9717. oresult = true;
  9718. break;@t\2@>@/
  9719. }@t\2@>@/
  9720. }@t\2@>@/
  9721. }
  9722. @ Now that we know that values from the current row should be output, we can
  9723. produce a {\tt <tuple>} element, a {\tt <time>} element for that tuple, and then
  9724. iterate over the set of columns we might want to output, producing an
  9725. appropriate element for each non-empty column for that row.
  9726. @<Output tuple element@>=
  9727. xmlout.writeStartElement("tuple");
  9728. xmlout.writeTextElement("time", data->data(data->index(i, time),
  9729. Qt::DisplayRole).toString());
  9730. foreach(int c, temperatureColumns.keys())@/
  9731. {
  9732. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  9733. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  9734. {
  9735. xmlout.writeStartElement("temperature");
  9736. xmlout.writeAttribute("series", temperatureColumns.value(c));
  9737. xmlout.writeCharacters(data->data(data->index(i, c), Qt::DisplayRole).
  9738. toString());
  9739. xmlout.writeEndElement();
  9740. }
  9741. }
  9742. foreach(int c, annotationColumns.keys())@/
  9743. {
  9744. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  9745. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  9746. {
  9747. xmlout.writeStartElement("annotation");
  9748. xmlout.writeAttribute("series", annotationColumns.value(c));
  9749. xmlout.writeCharacters(data->data(data->index(i, c), Qt::DisplayRole).
  9750. toString());
  9751. xmlout.writeEndElement();
  9752. }
  9753. }
  9754. xmlout.writeEndElement();
  9755. @ The rest of the class just initializes the private member data.
  9756. @<XMLOutput Implementation@>=
  9757. XMLOutput::XMLOutput(MeasurementModel *model, QIODevice *device, int timec)
  9758. : QObject(NULL), data(model), out(device), time(timec)@/
  9759. {
  9760. /* Nothing has to be done here. */
  9761. }@;
  9762. void XMLOutput::setModel(MeasurementModel *model)
  9763. {
  9764. data = model;
  9765. }
  9766. void XMLOutput::setTimeColumn(int column)
  9767. {
  9768. time = column;
  9769. }
  9770. void XMLOutput::setDevice(QIODevice *device)
  9771. {
  9772. out = device;
  9773. }
  9774. @ As of version 1.2.3, the old |setTemperatureColumn()| and
  9775. |setAnnotationColumn()| methods have been replaced with the
  9776. |addTemperatureColumn()| and |addAnnotationColumn()| methods respectively. The
  9777. main difference is that the new methods take a column name in addition to a
  9778. number and it is now possible to specify multiple columns of each category for
  9779. export.
  9780. @<XMLOutput Implementation@>=
  9781. void XMLOutput::addTemperatureColumn(const QString &series, int column)
  9782. {
  9783. temperatureColumns.insert(column, series);
  9784. }
  9785. void XMLOutput::addAnnotationColumn(const QString &series, int column)
  9786. {
  9787. annotationColumns.insert(column, series);
  9788. }
  9789. @* XML Input.
  9790. \noindent Once model data can be saved to a file, it is useful to be able to
  9791. read that data back in. This is a little different from reading data out of a
  9792. model as more than one object is potentially interested in the data. Instead, we
  9793. emit signals for measurements and annotations. This class has been modified to
  9794. support both the current (as of version 1.2.3) output of the |XMLOutput| class
  9795. and the older version. If changes are made to |XMLOutput| this class may also
  9796. need to be modified.
  9797. The main differences in the current version of this class are that the first
  9798. column is specified rather than specifying temperature and annotation columns
  9799. separately and additional signals are emitted to allow views to prepare for an
  9800. arbitrary number of columns.
  9801. The |newTemperatureColumn| and |newAnnotationColumn| signals can be used to set
  9802. up column headers while the |lastColumn| signal can be used to shift live data
  9803. streams to unoccupied columns.
  9804. @<Class declarations@>=
  9805. class XMLInput : public QObject@/
  9806. {
  9807. Q_OBJECT@;
  9808. int firstc;
  9809. QIODevice *in;
  9810. public:@/
  9811. XMLInput(QIODevice *input, int c);
  9812. void setFirstColumn(int column);
  9813. void setDevice(QIODevice *device);
  9814. bool input();
  9815. signals:@/
  9816. void measure(Measurement, int);
  9817. void annotation(QString, int, int);
  9818. void newTemperatureColumn(int, QString);
  9819. void newAnnotationColumn(int, QString);
  9820. void lastColumn(int);
  9821. };
  9822. @ The main point of interest here is the |input()| method. If the file is read
  9823. successfully, |true| is returned. Otherwise, |false| is returned.
  9824. @<XMLInput Implementation@>=
  9825. bool XMLInput::input()@t\2\2@>@/
  9826. {@t\1@>@/
  9827. if(!in->open(QIODevice::ReadOnly | QIODevice::Text))@/
  9828. {@t\1@>@/
  9829. return false;@t\2@>@/
  9830. }@/
  9831. QXmlStreamReader xmlin(in);
  9832. QMap<QString, int> temperatureColumns;
  9833. QMap<QString, int> annotationColumns;
  9834. int nextColumn = firstc;
  9835. @<Read column declarations@>@;
  9836. QTime timeval = QTime();
  9837. double tempval = 0;
  9838. QString noteval = QString();
  9839. int column;
  9840. int counter = 0;@/
  9841. while(!xmlin.atEnd())@/
  9842. {@/
  9843. @<Read XML file@>@;
  9844. }@/
  9845. return true;@t\2@>@/
  9846. }
  9847. @ A data file may or may not contain elements that specify the name of a column.
  9848. In order to determine how to proceed, we should check the doctype of the input
  9849. file. This should be the first element of the input file encountered.
  9850. \danger There is not nearly enough error checking here.
  9851. \endanger
  9852. @<Read column declarations@>=
  9853. while(!xmlin.isDTD())
  9854. {
  9855. xmlin.readNext();
  9856. }
  9857. if(xmlin.isDTD())
  9858. {
  9859. if(xmlin.text() == "<!DOCTYPE roastlog>")
  9860. {
  9861. @<Emit old format column specification@>@;
  9862. }
  9863. else
  9864. {
  9865. xmlin.readNext();
  9866. @<Scan for column declarations and emit@>@;
  9867. }
  9868. }
  9869. @ Old format data will not have column declarations. This means that we must
  9870. produce a default set of signals rather than waiting to read elements describing
  9871. the columns.
  9872. @<Emit old format column specification@>=
  9873. emit newTemperatureColumn(firstc, "Bean");
  9874. emit newAnnotationColumn(firstc + 1, "Note");
  9875. emit lastColumn(firstc + 1);
  9876. @ The current format will have column declarations prior to the {\tt <roast>}
  9877. element. We can just read until we hit that element and emit the appropriate
  9878. signals as elements are encountered.
  9879. @<Scan for column declarations and emit@>=
  9880. while(xmlin.name() != "roast")
  9881. {
  9882. if(xmlin.isStartElement())
  9883. {
  9884. if(xmlin.name() == "tempseries")
  9885. {
  9886. temperatureColumns.insert(xmlin.attributes().value("name").
  9887. toString(),
  9888. nextColumn);
  9889. emit newTemperatureColumn(nextColumn,
  9890. xmlin.attributes().value("name").
  9891. toString());
  9892. nextColumn++;
  9893. }
  9894. else if(xmlin.name() == "noteseries")
  9895. {
  9896. annotationColumns.insert(xmlin.attributes().value("name").
  9897. toString(), nextColumn);
  9898. emit newAnnotationColumn(nextColumn,
  9899. xmlin.attributes().value("name").
  9900. toString());
  9901. nextColumn++;
  9902. }
  9903. }
  9904. xmlin.readNext();
  9905. }
  9906. emit lastColumn(nextColumn - 1);
  9907. @ Now we are ready to read measurements from the file. When encountering a
  9908. {\tt <time>} element, we record the time and move on. For {\tt <temperature>}
  9909. and {\tt <annotation>} elements, we emit the appropriate signal. This is handled
  9910. slightly differently depending on which version of the file format is being
  9911. used. Note that there is not nearly enough error checking here and we are
  9912. basically ignoring {\tt <tuple>} elements.
  9913. Due to the typically large number of measurements taken over the course of a
  9914. roast and the amount of time often taken to process these measurements when they
  9915. are read from a file, there is a need to periodically pass control back to the
  9916. event loop to remain responsive to user input.
  9917. @<Read XML file@>=
  9918. xmlin.readNext();
  9919. if(xmlin.isStartElement())
  9920. {
  9921. @<Read measurement data@>@;
  9922. }
  9923. counter++;
  9924. if(counter % 100 == 0)
  9925. {
  9926. QCoreApplication::processEvents();
  9927. }
  9928. @ When reading start elements, it is safe to ignore {\tt <tuple>} and
  9929. {\tt <roast>}. Technically, this means that the program can read certain types
  9930. of invalid data. The Robustness Principle\nfnote{``Be liberal in what you
  9931. accept, and conservative in what you send,'' --- Robert Braden, {\it RFC 1122
  9932. \S 1.2.2}} is generally applicable to any type of data exchange. That said,
  9933. malformed data is not guaranteed readable in the future, even if it does work
  9934. now.
  9935. \danger One set of test input caused this code to emit an empty annotation for
  9936. every measurement. This is the reason for wrapping the annotation signal
  9937. emission to check for this. The detected annotation elements were not present in
  9938. the input stream and I have absolutely no idea where the program came up with
  9939. them. \endanger
  9940. @<Read measurement data@>=
  9941. if(xmlin.name() == "time")
  9942. {
  9943. timeval = QTime::fromString(xmlin.readElementText(), "mm:ss.zzz");
  9944. }
  9945. else if(xmlin.name() == "temperature")
  9946. {
  9947. column = xmlin.attributes().value("series").toString().isEmpty() ?
  9948. firstc : temperatureColumns.value(xmlin.attributes().
  9949. value("series").toString());
  9950. tempval = xmlin.readElementText().toDouble();
  9951. Measurement measurement(tempval, timeval);
  9952. emit measure(measurement, column);
  9953. }
  9954. else if(xmlin.name() == "annotation")
  9955. {
  9956. column = xmlin.attributes().value("series").toString().isEmpty() ?
  9957. firstc + 1 : annotationColumns.value(xmlin.attributes().
  9958. value("series").toString());
  9959. noteval = xmlin.readElementText();
  9960. if(!noteval.isEmpty())
  9961. {
  9962. emit annotation(noteval, firstc, column);
  9963. }
  9964. }
  9965. @ The other methods just set the private member data.
  9966. @<XMLInput Implementation@>=
  9967. XMLInput::XMLInput(QIODevice *input, int c) :
  9968. firstc(c), in(input)@/
  9969. {@/
  9970. /* Nothing has to be done here. */
  9971. }
  9972. void XMLInput::setFirstColumn(int column)
  9973. {
  9974. firstc = column;
  9975. }
  9976. void XMLInput::setDevice(QIODevice *device)
  9977. {
  9978. in = device;
  9979. }
  9980. @ In order to allow scripts to instantiate the |XMLInput| class, we need a
  9981. constructor and a wrapper around the |input()| method.
  9982. @<Function prototypes for scripting@>=
  9983. QScriptValue constructXMLInput(QScriptContext *context, QScriptEngine *engine);
  9984. QScriptValue XMLInput_input(QScriptContext *context, QScriptEngine *engine);
  9985. @ The script constructor is passed to the scripting engine.
  9986. @<Set up the scripting engine@>=
  9987. constructor = engine->newFunction(constructXMLInput);
  9988. value = engine->newQMetaObject(&XMLInput::staticMetaObject, constructor);
  9989. engine->globalObject().setProperty("XMLInput", value);
  9990. @ The implementation should seem familiar.
  9991. @<Functions for scripting@>=
  9992. QScriptValue constructXMLInput(QScriptContext *context, QScriptEngine *engine)
  9993. {
  9994. QIODevice *device = argument<QIODevice *>(0, context);
  9995. QScriptValue object = engine->newQObject(new XMLInput(&*device,
  9996. argument<int>(1, context)));
  9997. object.setProperty("input", engine->newFunction(XMLInput_input));
  9998. return object;
  9999. }
  10000. QScriptValue XMLInput_input(QScriptContext *context, QScriptEngine *)
  10001. {
  10002. XMLInput *self = getself<@[XMLInput *@]>(context);
  10003. self->input();
  10004. return QScriptValue();
  10005. }
  10006. @* CSV Output.
  10007. \noindent While XML is convenient for \pn{}, other programs may not handle this
  10008. format well. For this purpose, we use a text file with comma separated values.
  10009. Data in this format can easily be handled by shell scripts, simple programs, and
  10010. any spreadsheet (though some may handle the time column poorly).
  10011. We do not need to concern ourselves with reading data in this format back in,
  10012. but there is no reason a class could not be written to do this.
  10013. The structure of this class is very similar to the |XMLOutput| class.
  10014. @<Class declarations@>=
  10015. class CSVOutput@/
  10016. {@/
  10017. MeasurementModel *data;
  10018. QIODevice *out;
  10019. int time;
  10020. QMap<int, QString> temperatureColumns;
  10021. QMap<int, QString> annotationColumns;@/
  10022. public:@/
  10023. CSVOutput(MeasurementModel *model, QIODevice *device, int timec = 0);
  10024. void addTemperatureColumn(const QString &series, int column);
  10025. void addAnnotationColumn(const QString &series, int column);
  10026. void setModel(MeasurementModel *model);
  10027. void setTimeColumn(int column);
  10028. void setDevice(QIODevice *device);
  10029. bool output();@/
  10030. };
  10031. @ Very little needs to be done to output the data. We open the output stream
  10032. and, if the output stream was successfully opened, we look for measurements and
  10033. output the text, remembering to output a comma between items and a newline after
  10034. each record. If the data is successfully output, |true| is returned, otherwise
  10035. we return |false|.
  10036. The comparably simple structure of the CSV format allows us to just fling the
  10037. data onto a text stream.
  10038. @<CSVOutput Implementation@>=
  10039. bool CSVOutput::output()@t\2\2@>@/
  10040. {@t\1@>@/
  10041. if(!out->open(QIODevice::WriteOnly | QIODevice::Text))@/
  10042. {@t\1@>@/
  10043. return false;@t\2@>@/
  10044. }@/
  10045. QTextStream output(out);
  10046. @<Output CSV column headers@>@;
  10047. bool oresult;
  10048. for(int i = 0; i < data->rowCount(); i++)@/
  10049. {
  10050. @<Check if row should be output@>@;
  10051. if(oresult)
  10052. {
  10053. @<Output CSV row@>@;
  10054. }
  10055. }
  10056. out->close();@/
  10057. return true;@t\2@>@/
  10058. }
  10059. @ Before writing the data, we output a row containing the name of each column.
  10060. @<Output CSV column headers@>=
  10061. output << "Time";
  10062. foreach(int c, temperatureColumns.keys())
  10063. {
  10064. output << ',' << temperatureColumns.value(c);
  10065. }
  10066. foreach(int c, annotationColumns.keys())
  10067. {
  10068. output << ',' << annotationColumns.value(c);
  10069. }
  10070. output << '\n';
  10071. @ Once the header information has been written, we can proceed to output the
  10072. real data. The algorithm for doing this has been changed as of version 1.2.3
  10073. with the result that most uses will now produce more delimiters than the same
  10074. data in previous versions. This should have no impact on the ability of other
  10075. programs to interact with data produced by \pn{}. The code to handle output in
  10076. this way is much easier to read. A future version might once again suppress
  10077. superfluous commas, however the presence of these commas is not considered a
  10078. serious issue at this time.
  10079. @<Output CSV row@>=
  10080. output << data->data(data->index(i, time), Qt::DisplayRole).toString();
  10081. foreach(int c, temperatureColumns.keys())
  10082. {
  10083. output << ',' << data->data(data->index(i, c), Qt::DisplayRole).toString();
  10084. }
  10085. foreach(int c, annotationColumns.keys())
  10086. {
  10087. output << ',' << data->data(data->index(i, c), Qt::DisplayRole).toString();
  10088. }
  10089. output << '\n';
  10090. @ The rest of the class just initializes the private member data. See notes
  10091. on the implementation of |XMLOutput|.
  10092. @<CSVOutput Implementation@>=
  10093. CSVOutput::CSVOutput(MeasurementModel *model, QIODevice *device, int timec) :
  10094. data(model), out(device), time(timec)@/
  10095. {
  10096. /* Nothing has to be done here. */
  10097. }@;
  10098. void CSVOutput::setModel(MeasurementModel *model)
  10099. {
  10100. data = model;
  10101. }
  10102. void CSVOutput::setTimeColumn(int column)
  10103. {
  10104. time = column;
  10105. }
  10106. void CSVOutput::addTemperatureColumn(const QString &series, int column)
  10107. {
  10108. temperatureColumns.insert(column, series);
  10109. }
  10110. void CSVOutput::addAnnotationColumn(const QString &series, int column)
  10111. {
  10112. annotationColumns.insert(column, series);
  10113. }
  10114. void CSVOutput::setDevice(QIODevice *device)
  10115. {
  10116. out = device;
  10117. }
  10118. @* Web views.
  10119. The |QWebView| class was initially brought in to handle printing roast profile
  10120. data. This works by transforming the roasting data to an XHTML+SVG document,
  10121. loading it into a web view, and calling the |print()| method on that. Support
  10122. has since been extended to make it easier to produce reports that require either
  10123. postprocessing database results or database capabilities that are not readily
  10124. available in the reporting framework.
  10125. With this new use, future development should allow inclusion of a web view in
  10126. the user interface without needing to instantiate it from a script.
  10127. @<Set up the scripting engine@>=
  10128. constructor = engine->newFunction(constructWebView);
  10129. value = engine->newQMetaObject(&QWebView::staticMetaObject, constructor);
  10130. engine->globalObject().setProperty("WebView", value);
  10131. @ A few properties are required. These should be available regardless of how the
  10132. object was created.
  10133. @<Functions for scripting@>=
  10134. QScriptValue constructWebView(QScriptContext *, QScriptEngine *engine)
  10135. {
  10136. QScriptValue object = engine->newQObject(new QWebView());
  10137. setQWebViewProperties(object, engine);
  10138. return object;
  10139. }
  10140. void setQWebViewProperties(QScriptValue value, QScriptEngine *engine)
  10141. {
  10142. setQWidgetProperties(value, engine);
  10143. value.setProperty("load", engine->newFunction(WebView_load));
  10144. value.setProperty("print", engine->newFunction(WebView_print));
  10145. value.setProperty("setHtml", engine->newFunction(WebView_setHtml));
  10146. value.setProperty("setContent", engine->newFunction(WebView_setContent));
  10147. value.setProperty("saveXml", engine->newFunction(WebView_saveXml));
  10148. }
  10149. @ To get data into the web view, we load it from a URL passed in the form of a
  10150. string. This will usually be a local file, but it doesn't have to be.
  10151. @<Functions for scripting@>=
  10152. QScriptValue WebView_load(QScriptContext *context, QScriptEngine *)
  10153. {
  10154. QWebView *self = getself<QWebView *>(context);
  10155. QString file = argument<QString>(0, context);
  10156. self->load(QUrl(file));
  10157. return QScriptValue();
  10158. }
  10159. @ When wrapping |QWebView::print()|, we need to obtain a |QPrinter| which that
  10160. method expects. In order to set everything up properly, we display a standard
  10161. print dialog.
  10162. @<Functions for scripting@>=
  10163. QScriptValue WebView_print(QScriptContext *context, QScriptEngine *)
  10164. {
  10165. QWebView *self = getself<QWebView *>(context);
  10166. QPrinter *printer = new QPrinter(QPrinter::HighResolution);
  10167. QPrintDialog printDialog(printer, NULL);
  10168. if(printDialog.exec() == QDialog::Accepted)
  10169. {
  10170. self->print(printer);
  10171. }
  10172. return QScriptValue();
  10173. }
  10174. @ When wrapping |QWebView::setHtml()|, only the first argument containing the
  10175. content is required.
  10176. @<Functions for scripting@>=
  10177. QScriptValue WebView_setHtml(QScriptContext *context, QScriptEngine *)
  10178. {
  10179. QWebView *self = getself<QWebView *>(context);
  10180. QString content = argument<QString>(0, context);
  10181. self->setHtml(content);
  10182. return QScriptValue();
  10183. }
  10184. @ This is a simple wrapper around |QWebView::setContent()|, but it obtains its
  10185. argument from the data in a |QIODevice|. A MIME type of application/xhtml+xml is
  10186. specified by default to allow embedding SVG.
  10187. @<Functions for scripting@>=
  10188. QScriptValue WebView_setContent(QScriptContext *context, QScriptEngine *)
  10189. {
  10190. QWebView *self = getself<QWebView *>(context);
  10191. QIODevice *device = argument<QIODevice *>(0, context);
  10192. device->reset();
  10193. QByteArray content = device->readAll();
  10194. self->setContent(content, "application/xhtml+xml");
  10195. return QScriptValue();
  10196. }
  10197. @ It should be possible to save the XHTML documents generated for reports. The
  10198. saveXml property provides one way to do this.
  10199. @<Functions for scripting@>=
  10200. QScriptValue WebView_saveXml(QScriptContext *context, QScriptEngine *)
  10201. {
  10202. QWebView *self = getself<QWebView *>(context);
  10203. return QScriptValue(self->page()->currentFrame()->documentElement().toOuterXml());
  10204. }
  10205. @ The web view can be created from the XML portion of the configuration
  10206. document. This function adds the view to a box layout.
  10207. @<Functions for scripting@>=
  10208. void addWebViewToLayout(QDomElement element, QStack<QWidget *> *,
  10209. QStack<QLayout *> *layoutStack)
  10210. {
  10211. QWebView *view = new QWebView;
  10212. if(element.hasAttribute("id"))
  10213. {
  10214. view->setObjectName(element.attribute("id"));
  10215. }
  10216. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  10217. layout->addWidget(view);
  10218. }
  10219. @ The function prototypes used above follow.
  10220. @<Function prototypes for scripting@>=
  10221. QScriptValue constructWebView(QScriptContext *context, QScriptEngine *engine);
  10222. QScriptValue WebView_load(QScriptContext *context, QScriptEngine *engine);
  10223. QScriptValue WebView_print(QScriptContext *context, QScriptEngine *engine);
  10224. QScriptValue WebView_setContent(QScriptContext *context, QScriptEngine *engine);
  10225. QScriptValue WebView_setHtml(QScriptContext *context, QScriptEngine *engine);
  10226. QScriptValue WebView_saveXml(QScriptContext *context, QScriptEngine *);
  10227. void addWebViewToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  10228. QStack<QLayout *> *layoutStack);
  10229. void setQWebViewProperties(QScriptValue value, QScriptEngine *engine);
  10230. @* The Application class.
  10231. The |Application| class represents the \pn{} program. It is responsible for
  10232. setting up the settings object and localization in addition to the normal
  10233. responsibilities of |QApplication|. In addition to declaring the class, we also
  10234. define a macro that returns the |Application| instance.
  10235. @<Class declarations@>=
  10236. #define AppInstance (qobject_cast<@[Application *@]>(qApp))
  10237. class NodeInserter;
  10238. class DeviceTreeModel;
  10239. class Application : public QApplication@/
  10240. {@/
  10241. @[Q_OBJECT@]@;
  10242. public:@/
  10243. Application(int &argc, char **argv);
  10244. QDomDocument* configuration();
  10245. @<Device configuration members@>@;
  10246. QSqlDatabase database();
  10247. QScriptEngine *engine;@/
  10248. @[public slots@]:@/
  10249. @<Extended Application slots@>@;
  10250. private:@/
  10251. @<Application private data members@>@;
  10252. QDomDocument conf;
  10253. };
  10254. @ The constructor for this class handles a few things that had previously been
  10255. handled in |main()|.
  10256. @<Application Implementation@>=
  10257. Application::Application(int &argc, char **argv) : QApplication(argc, argv)@/
  10258. {
  10259. @<Allow use of the default QSettings constructor@>@;
  10260. @<Load translation objects@>@;
  10261. @<Register meta-types@>@;
  10262. @<Register top level device configuration nodes@>@;
  10263. }
  10264. @ We use |QSettings| objects throughout \pn{} to remember details such as the
  10265. size and position of windows and the most recently used directory. To simplify
  10266. the creation of these objects, we specify some details up front. This allows us
  10267. to use the default constructor rather than specifying these things every time we
  10268. need an object.
  10269. @<Allow use of the default QSettings constructor@>=
  10270. setOrganizationName("Wilson's Coffee & Tea");
  10271. setOrganizationDomain("wilsonscoffee.com");
  10272. setApplicationName(PROGRAM_NAME);
  10273. @ Much of the user visible text in \pn{} is wrapped in a call to |tr()|. Such
  10274. text can be replaced with translated text based on the user's locale. For more
  10275. details, see the Qt Linguist manual.
  10276. @<Load translation objects@>=
  10277. QTranslator base;
  10278. if(base.load(QString("qt_%1").arg(QLocale::system().name())))
  10279. {
  10280. installTranslator(&base);
  10281. }
  10282. QTranslator app;
  10283. if(app.load(QString("%1_%2").arg("Typica").arg(QLocale::system().name())))
  10284. {
  10285. installTranslator(&app);
  10286. }
  10287. @ We also want to be able to access the application instance from within the
  10288. scripting engine. We don't need to be able to create new instances, just access
  10289. the one that already exists.
  10290. @<Set up the scripting engine@>=
  10291. value = engine->newQObject(AppInstance);
  10292. engine->globalObject().setProperty("Application", value);
  10293. @ The |configuration()| method provides access to an XML document containing the
  10294. current application configuration. The object is populated in |main()|.
  10295. @<Application Implementation@>=
  10296. QDomDocument* Application::configuration()
  10297. {
  10298. return &conf;
  10299. }
  10300. @ The |database()| method provides access to a database connection for use by
  10301. database aware widgets.
  10302. @<Application Implementation@>=
  10303. QSqlDatabase Application::database()
  10304. {
  10305. QString connectionName;
  10306. QSqlDatabase connection = QSqlDatabase::database();
  10307. do
  10308. {
  10309. connectionName = QUuid::createUuid().toString();
  10310. } while (QSqlDatabase::connectionNames().contains(connectionName));
  10311. return QSqlDatabase::cloneDatabase(connection, connectionName);
  10312. }
  10313. @** Table editor for ordered arrays with SQL relations.
  10314. \noindent A database in use at Wilson's Coffee \char'046~Tea stores information
  10315. for a roasting log and uses entered information to adjust inventory tracking
  10316. tables. This roasting log connects the use of unroasted coffee with the creation
  10317. of roasted coffee. In order to support roasting coffee from more than one lot at
  10318. the same time, the columns that specify the types of coffee used and the amount
  10319. of each coffee are entered as ordered arrays in which the first entry in the
  10320. array specifying an unroasted coffee is associated with the first entry in the
  10321. array specifying the amount of coffee used. While most batches will involve only
  10322. a single unroasted coffee, the database has no limitation on the number of
  10323. coffees that may be roasted in a single batch. An additional characteristic of
  10324. this table is that the database requires an identification number for unroasted
  10325. coffee items, but it would be better to provide a list of acceptable items with
  10326. human readable names.
  10327. A scrollable area containing a table view which can provide the necessary input
  10328. delegates (such as a combo box for SQL relations) and validators which ensures
  10329. that there is always at least one empty row available for input with convenience
  10330. functions for extracting the arrays needed for database insertion would be ideal
  10331. for this.
  10332. To get this, we need a simple table model based on |QStandardItemModel|
  10333. or |QAbstractItemModel|. The model should ensure that there is always at least
  10334. one empty row available for editing. It should also provide a function for
  10335. obtaining a string that presents all values from a specified column with a given
  10336. role as an array literal suitable for binding to an SQL query.
  10337. A class based on |QComboBox| providing options selected from an SQL query will
  10338. be needed. This can be used as a standalone widget elsewhere, but here it is
  10339. also needed as an editor class for a column delegate. Another delegate class
  10340. allows input in another column to be constrained by a |QValidator| (in this case
  10341. a |QDoubleValidator|).
  10342. A class based on |QTableView| brings all of these classes together and presents
  10343. them to the user.
  10344. @* A table model for producing SQL array literals.
  10345. \noindent This is a simple table model which provides two somewhat unusual
  10346. features. First, it always provides at least one empty row at the end of the
  10347. data. Second, it provides SQL array literals for columns in the model.
  10348. \danger At some point I would like to replace this model and |MeasurementModel|
  10349. with an improved table model suitable to replace both. Some preliminary design
  10350. work suggests that this improvement simplifies \pn{} considerably both
  10351. internally and in the data flow configuration. This has not yet been done due to
  10352. development time constraints.\endanger
  10353. @<Class declarations@>=
  10354. class SaltModel : public QAbstractItemModel@/
  10355. {
  10356. Q_OBJECT@t\2\2@>@/
  10357. QList<QList<QMap<int, QVariant> > > modelData;
  10358. QStringList hData;
  10359. int colcount;@t\1\1@>@/
  10360. public:@/
  10361. SaltModel(int columns);
  10362. ~SaltModel();
  10363. int rowCount(const QModelIndex &parent = QModelIndex()) const;
  10364. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  10365. bool setHeaderData(int section, Qt::Orientation@, orientation,
  10366. const QVariant &value, int role = Qt::DisplayRole);
  10367. QVariant data(const QModelIndex &index, int role) const;
  10368. bool setData(const QModelIndex &index, const QVariant &value,
  10369. int role = Qt::EditRole);
  10370. Qt::ItemFlags@, flags(const QModelIndex &index) const;
  10371. QVariant headerData(int section, Qt::Orientation@, orientation,
  10372. int role = Qt::DisplayRole) const;
  10373. QModelIndex index(int row, int column,
  10374. const QModelIndex &parent = QModelIndex()) const;
  10375. QModelIndex parent(const QModelIndex &index) const;
  10376. QString arrayLiteral(int column, int role) const;
  10377. QString quotedArrayLiteral(int column, int role) const;
  10378. };
  10379. @ The only unique methods in this class are the |arrayLiteral| and
  10380. |quotedArrayLiteral| methods. These take a column number and a data role and
  10381. produce a SQL array literal for every entry in that column with the specified
  10382. role. The string will take the form of
  10383. {\tt{'\LB row 1, row 2, }}$\dots$ {\tt{row N\RB '}}.
  10384. This is done simply by starting with a string identifying the start of an array
  10385. literal, looping over the rows in the model while appending any data found along
  10386. with the commas to separate values. If any data is found, the extra comma and
  10387. space are removed from the constructed string. Finally, text marking the end of
  10388. the array literal is added.
  10389. The |arrayLiteral| method is appropriate where the expected values are numeric.
  10390. The |quotedArrayLiteral| method is appropriate where the expected values are
  10391. text. The values in the array will have quotation marks around them for the
  10392. |quotedArrayLiteral|. Note that when binding these values to placeholders in a
  10393. SQL query the leading and trailing single quote characters should be removed.
  10394. \danger The way this method is currently used is quite harmless. Data from one
  10395. column is integer data obtained as a result of a previous database query and
  10396. data from the other column is restricted by the view to numeric data. Please
  10397. note, however, that it would be extremely stupid to use code such as this when
  10398. user input cannot be controlled so tightly. Were this model used with a view
  10399. that allows general text input, it would be trivial to construct an SQL
  10400. injection attack.
  10401. \medskip
  10402. \centerline{\includegraphics[width=6in]{exploits_of_a_mom}}
  10403. \smallskip
  10404. \centerline{Figure \secno: An Example of an SQL injection attack.\nfnote{%
  10405. Comic copyright Randall Munroe. Original can be found at:~%
  10406. \pdfURL{%
  10407. http://xkcd.com/327/}%
  10408. {http://xkcd.com/327/}}}
  10409. \medskip
  10410. \endanger
  10411. @<SaltModel Implementation@>=
  10412. QString SaltModel::arrayLiteral(int column, int role) const
  10413. {
  10414. QString literal = "'{";
  10415. for(int i = 0; i < rowCount(); i++)
  10416. {
  10417. QString datum = data(index(i, column), role).toString();
  10418. if(!datum.isEmpty())
  10419. {
  10420. literal.append(datum);
  10421. literal.append(", ");
  10422. }
  10423. }
  10424. if(literal.size() > 2)
  10425. {
  10426. literal.chop(2);
  10427. }
  10428. literal.append("}'");
  10429. return literal;
  10430. }
  10431. QString SaltModel::quotedArrayLiteral(int column, int role) const
  10432. {
  10433. QString literal = "'{";
  10434. for(int i = 0; i < rowCount(); i++)
  10435. {
  10436. QString datum = data(index(i, column), role).toString();
  10437. if(!datum.isEmpty())
  10438. {
  10439. literal.append("\"");
  10440. literal.append(datum);
  10441. literal.append("\", ");
  10442. }
  10443. }
  10444. if(literal.size() > 2)
  10445. {
  10446. literal.chop(2);
  10447. }
  10448. literal.append("}'");
  10449. return literal;
  10450. }
  10451. @ No entries in this model have children.
  10452. @<SaltModel Implementation@>=
  10453. QModelIndex SaltModel::parent(const QModelIndex &) const
  10454. {
  10455. return QModelIndex();
  10456. }
  10457. @ The |setData()| method is called by delegates on views when the user enters
  10458. new data. This method must check to determine if the data is being entered in
  10459. the last row to increase the size of the table.
  10460. The end of this function may seem a little strange. Why not simply look up the
  10461. map and insert information directly into the model data? Well, as of this
  10462. writing, that doesn't work. There are two ways around that problem. One is to
  10463. have the lists store references and dereference the real data. The other option
  10464. is to obtain a copy of the row, then a copy of the cell, update the cell, then
  10465. replace the old value of the cell in the copy of the row, then replace the old
  10466. values of the row in the real data. The other option would probably be more
  10467. efficient, but this does work.
  10468. @<SaltModel Implementation@>=
  10469. bool SaltModel::setData(const QModelIndex &index, const QVariant &value,
  10470. int role)@t\2\2@>@/
  10471. {@t\1@>@/
  10472. @<Check that the SaltModel index is valid@>@;
  10473. if(!valid)@/
  10474. {@t\1@>@/
  10475. return false;@t\2@>@/
  10476. }
  10477. if(index.row() == modelData.size() - 1)@/
  10478. {
  10479. beginInsertRows(QModelIndex(), modelData.size(), modelData.size());
  10480. @<Expand the SaltModel@>@;
  10481. endInsertRows();
  10482. }
  10483. QList<QMap<int, QVariant> > row = modelData.at(index.row());
  10484. QMap<int, QVariant> cell = row.at(index.column());
  10485. cell.insert(role, value);
  10486. if(role == Qt::EditRole)@/
  10487. {
  10488. cell.insert(Qt::DisplayRole, value);
  10489. }
  10490. row.replace(index.column(), cell);
  10491. modelData.replace(index.row(), row);
  10492. emit dataChanged(index, index);@/
  10493. return true;@t\2@>@/
  10494. }
  10495. @ Some model operations require checking that a model index is valid. This
  10496. chunk is used in these cases.
  10497. @<Check that the SaltModel index is valid@>=
  10498. bool valid = false;@/
  10499. if(index.isValid())@/
  10500. {@t\1@>@/
  10501. if(index.row() < modelData.size())@/
  10502. {@t\1@>@/
  10503. if(index.column() < colcount)@/
  10504. {@t\1@>@/
  10505. valid = true;@t\2@>@/
  10506. }@t\2@>@/
  10507. }@t\2@>@/
  10508. }
  10509. @ When data is modified in the last row of the table, the model must be expanded
  10510. to allow for additional data.
  10511. @<Expand the SaltModel@>=
  10512. QList<QMap<int, QVariant> > newRow;
  10513. QMap<int, QVariant> defaults;
  10514. for(int i = 0; i < colcount; i++)
  10515. {
  10516. newRow.append(defaults);
  10517. }
  10518. modelData.append(newRow);
  10519. @ The number of columns in the table is specified in the model constructor.
  10520. @<SaltModel Implementation@>=
  10521. SaltModel::SaltModel(int columns) : QAbstractItemModel(), colcount(columns)
  10522. {
  10523. for(int i = 0; i < columns; i++)
  10524. {
  10525. hData << "";
  10526. }
  10527. @<Expand the SaltModel@>@;
  10528. }
  10529. @ The destructor doesn't need to do anything.
  10530. @<SaltModel Implementation@>=
  10531. SaltModel::~SaltModel()
  10532. {
  10533. /* Nothing needs to be done here. */
  10534. }
  10535. @ A pair of methods provide the number of rows and columns in the model. No
  10536. entries in the model have children, so the parent should always be the invisible
  10537. root object.
  10538. @<SaltModel Implementation@>=
  10539. int SaltModel::rowCount(const QModelIndex &parent) const
  10540. {
  10541. return (parent == QModelIndex() ? modelData.size() : 0);
  10542. }
  10543. int SaltModel::columnCount(const QModelIndex &parent) const
  10544. {
  10545. return (parent == QModelIndex() ? colcount : 0);
  10546. }
  10547. @ The model maintains header data for labeling the model columns.
  10548. @<SaltModel Implementation@>=
  10549. bool SaltModel::setHeaderData(int section, Qt::Orientation@, orientation,@|
  10550. const QVariant &value, int)@t\2\2@>@/
  10551. {@t\1@>@/
  10552. if(orientation == Qt::Horizontal && section < colcount)@/
  10553. {@t\1@>@/
  10554. hData.replace(section, value.toString());@/
  10555. emit headerDataChanged(orientation, section, section);@/
  10556. return true;@t\2@>@/
  10557. }@/
  10558. return false;@t\2@>@/
  10559. }
  10560. @ Views need to be able to retrieve model and header data.
  10561. @<SaltModel Implementation@>=
  10562. QVariant SaltModel::data(const QModelIndex &index, int role) const
  10563. {
  10564. @<Check that the SaltModel index is valid@>@;
  10565. if(!valid)
  10566. {
  10567. return QVariant();
  10568. }
  10569. QList<QMap<int,QVariant> > row = modelData.at(index.row());
  10570. QMap<int,QVariant> cell = row.at(index.column());
  10571. return cell.value(role, QVariant());
  10572. }
  10573. QVariant SaltModel::headerData(int section, Qt::Orientation@, orientation,
  10574. int role) const
  10575. {
  10576. if(orientation == Qt::Horizontal && role == Qt::DisplayRole &&
  10577. section < colcount)
  10578. {
  10579. return QVariant(hData.at(section));
  10580. }
  10581. return QVariant();
  10582. }
  10583. @ Views need to know certain details such as if an item in the view can be
  10584. altered by the view. For this model, all valid indices can be edited.
  10585. @<SaltModel Implementation@>=
  10586. Qt::ItemFlags SaltModel::flags(const QModelIndex &index) const
  10587. {
  10588. @<Check that the SaltModel index is valid@>@;
  10589. if(valid)
  10590. {
  10591. return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable;
  10592. }
  10593. return 0;
  10594. }
  10595. @ So far, many of the methods use model indices. The model is responsible for
  10596. creating these.
  10597. @<SaltModel Implementation@>=
  10598. QModelIndex SaltModel::index(int row, int column,
  10599. const QModelIndex &parent) const
  10600. {
  10601. if(parent == QModelIndex())
  10602. {
  10603. if(row < modelData.size() && column < colcount)
  10604. {
  10605. return createIndex(row, column);
  10606. }
  10607. }
  10608. return QModelIndex();
  10609. }
  10610. @* A Delegate for SQL Relations.
  10611. \noindent The first column of the table view being described is responsible for
  10612. providing item numbers to the database. Requiring that these numbers be entered
  10613. directly is prone to not particularly user friendly and almost encourages input
  10614. errors. These item numbers, however, refer to the items table in the database
  10615. which includes, among other details, a human readable text string naming the
  10616. item. This delegate provides the user with a drop down menu from which such a
  10617. string may be selected with this information provided by the database itself.
  10618. When the user selects an item, it informs the model not only of the text string
  10619. in the display role, but also of the id number in a user data role which can
  10620. later be queried in order to properly craft the appropriate query.
  10621. This is implemented with two classes. The first is a |QComboBox| which queries
  10622. the database and maintains a mapping of id to text. This is made its own widget
  10623. as it is useful without being turned into a delegate. The second class provides
  10624. this widget as a delegate and handles communications between it and the model.
  10625. @<Class declarations@>=
  10626. class SqlComboBox : public QComboBox@/
  10627. {@t\1@>@/
  10628. Q_OBJECT@;
  10629. int dataColumn;
  10630. int displayColumn;
  10631. bool dataColumnShown;
  10632. public:@/
  10633. SqlComboBox();
  10634. ~SqlComboBox();
  10635. SqlComboBox* clone(QWidget *parent);@/
  10636. @t\4@>public slots@t\kern-3pt@>:@/
  10637. void addNullOption();
  10638. void addSqlOptions(QString query);
  10639. void setDataColumn(int column);
  10640. void setDisplayColumn(int column);
  10641. void showData(bool show);@t\2@>@/
  10642. }@t\kern-3pt@>;
  10643. @ In order to make this class work a little more nicely as an item delegate,
  10644. the |clone()| method has been provided to create a new object with the same
  10645. options as a prototype.
  10646. @<SqlComboBox Implementation@>=
  10647. SqlComboBox* SqlComboBox::clone(QWidget *parent)
  10648. {
  10649. SqlComboBox *widget = new SqlComboBox();
  10650. widget->setParent(parent);
  10651. for(int i = 0; i < count(); i++)
  10652. {
  10653. widget->addItem(itemText(i), itemData(i));
  10654. }
  10655. return widget;
  10656. }
  10657. @ When using this class, we must first decide if the data column is shown. If
  10658. this is desired, the entries displayed will contain both the value from the
  10659. display column followed by the value from the data column. This can be useful in
  10660. cases where the same text is used for two different items.
  10661. @<SqlComboBox Implementation@>=
  10662. void SqlComboBox::showData(bool show)
  10663. {
  10664. dataColumnShown = show;
  10665. }
  10666. @ Next, there is a need to know if the NULL value may legally be selected. Where
  10667. this is the case, we generally want this to be inserted first. As the
  10668. |QComboBox| supports storing both display and user data, much of the code is a
  10669. thin wrapper around calls to the base class.
  10670. @<SqlComboBox Implementation@>=
  10671. void SqlComboBox::addNullOption()
  10672. {
  10673. addItem(tr("Unknown"), QVariant(QVariant::String));
  10674. }
  10675. @ Typically, the SQL query used to populate this widget will request two columns
  10676. of data. One column is used as the display data, the other as user data. This is
  10677. done to present a human readable string where a database query needs an
  10678. identification number. By default, column |0| is used in both roles. If this
  10679. is not desired, the methods to change that must be called before specifying the
  10680. query.
  10681. @<SqlComboBox Implementation@>=
  10682. void SqlComboBox::setDataColumn(int column)
  10683. {
  10684. dataColumn = column;
  10685. }
  10686. void SqlComboBox::setDisplayColumn(int column)
  10687. {
  10688. displayColumn = column;
  10689. }
  10690. @ Once the widget is properly configured, we can run the SQL query and populate
  10691. the combo box with the results.
  10692. @<SqlComboBox Implementation@>=
  10693. void SqlComboBox::addSqlOptions(QString query)
  10694. {
  10695. SqlQueryConnection *dbquery = new SqlQueryConnection;
  10696. if(!dbquery->exec(query))
  10697. {
  10698. QSqlError error = dbquery->lastError();
  10699. qDebug() << error.databaseText();
  10700. qDebug() << error.driverText();
  10701. qDebug() << error.text();
  10702. qDebug() << dbquery->lastQuery();
  10703. /* Throw an error here, please. */
  10704. }
  10705. while(dbquery->next())
  10706. {
  10707. QString displayValue(dbquery->value(displayColumn).toString());
  10708. QString dataValue(dbquery->value(dataColumn).toString());
  10709. if(dataColumnShown)
  10710. {
  10711. displayValue.append(QString(" (%1)").arg(dataValue));
  10712. }
  10713. addItem(displayValue, dataValue);
  10714. }
  10715. delete dbquery;
  10716. }
  10717. @ The constructor only needs to initialize some private member data. The
  10718. destructor has even less to do.
  10719. @<SqlComboBox Implementation@>=
  10720. SqlComboBox::SqlComboBox() :
  10721. dataColumn(0), displayColumn(0), dataColumnShown(false)
  10722. {
  10723. /* Nothing needs to be done here. */
  10724. }
  10725. SqlComboBox::~SqlComboBox()
  10726. {
  10727. /* Nothing needs to be done here. */
  10728. }
  10729. @ To use this class as an editor delegate in a model we wrap the class in a
  10730. |QItemDelegate|.
  10731. @<Class declarations@>=
  10732. class SqlComboBoxDelegate : public QItemDelegate@/
  10733. {
  10734. Q_OBJECT@;
  10735. SqlComboBox *delegate;
  10736. public:@/
  10737. SqlComboBoxDelegate(QObject *parent = NULL);
  10738. QWidget *createEditor(QWidget *parent,
  10739. const QStyleOptionViewItem &option,@|
  10740. const QModelIndex &index) const;
  10741. void setEditorData(QWidget *editor, const QModelIndex &index) const;
  10742. void setModelData(QWidget *editor, QAbstractItemModel *model,@|
  10743. const QModelIndex &index) const;
  10744. void setWidget(SqlComboBox *widget);
  10745. virtual QSize sizeHint() const;
  10746. void updateEditorGeometry(QWidget *editor,
  10747. const QStyleOptionViewItem &option,@|
  10748. const QModelIndex &index) const;
  10749. };
  10750. @ Rather than set the values for the combo box through the delegate class, we
  10751. create the editor and pass it in to the delegate.
  10752. @<SqlComboBoxDelegate Implementation@>=
  10753. void SqlComboBoxDelegate::setWidget(SqlComboBox *widget)
  10754. {
  10755. delegate = widget;
  10756. }
  10757. @ When a view requests this delegate, we simply return the widget that was
  10758. previously passed in.
  10759. @<SqlComboBoxDelegate Implementation@>=
  10760. QWidget* SqlComboBoxDelegate::createEditor(QWidget *parent,@|
  10761. const QStyleOptionViewItem &,
  10762. const QModelIndex &) const
  10763. {
  10764. return delegate->clone(parent);
  10765. }
  10766. @ To set the appropriate editor data, we check the value in the model and
  10767. attempt to set the value to match that.
  10768. @<SqlComboBoxDelegate Implementation@>=
  10769. void SqlComboBoxDelegate::setEditorData(QWidget *editor,
  10770. const QModelIndex &index) const
  10771. {
  10772. SqlComboBox *self = qobject_cast<SqlComboBox *>(editor);
  10773. self->setCurrentIndex(self->findData(
  10774. index.model()->data(index,
  10775. Qt::UserRole).toString()));
  10776. }
  10777. @ When setting the model data, we need to specify both the display role and the
  10778. user data role.
  10779. @<SqlComboBoxDelegate Implementation@>=
  10780. void SqlComboBoxDelegate::setModelData(QWidget *editor,@|
  10781. QAbstractItemModel *model,
  10782. const QModelIndex &index) const
  10783. {
  10784. SqlComboBox *self = qobject_cast<SqlComboBox *>(editor);
  10785. model->setData(index, self->itemData(self->currentIndex(), Qt::UserRole),
  10786. Qt::UserRole);
  10787. model->setData(index, self->currentText(), Qt::DisplayRole);
  10788. }
  10789. @ This is needed to play nicely with the model view architecture.
  10790. @<SqlComboBoxDelegate Implementation@>=
  10791. void SqlComboBoxDelegate::updateEditorGeometry(QWidget *editor,
  10792. const QStyleOptionViewItem &option,
  10793. const QModelIndex &) const
  10794. {
  10795. editor->setGeometry(option.rect);
  10796. }
  10797. @ When this delegate is used in a table view, we want to be able to provide a
  10798. size hint that can be used to resize the column in order to fit the delegate.
  10799. @<SqlComboBoxDelegate Implementation@>=
  10800. QSize SqlComboBoxDelegate::sizeHint() const
  10801. {
  10802. return delegate->sizeHint();
  10803. }
  10804. @ Finally, we need a constructor.
  10805. @<SqlComboBoxDelegate Implementation@>=
  10806. SqlComboBoxDelegate::SqlComboBoxDelegate(QObject *parent)
  10807. : QItemDelegate(parent)@/
  10808. {
  10809. /* Nothing needs to be done here. */
  10810. }
  10811. @** The main program.
  10812. The |main()| function is where program execution starts. Most of the work
  10813. required here is taken care of for us by the |Application| object.
  10814. The odd handling of argc is required to prevent segmentation faults in the Linux
  10815. build.
  10816. @<The main program@>=
  10817. int main(int argc, char **argv)@/
  10818. {@/
  10819. int *c = &argc;
  10820. Application app(*c, argv);
  10821. @<Set up icons@>@;
  10822. @<Set up fonts@>@;
  10823. QSettings settings;
  10824. @<Register device configuration widgets@>@;
  10825. @<Prepare the database connection@>@;
  10826. @<Load the application configuration@>@;
  10827. @<Set up the scripting engine@>@;
  10828. app.engine = engine;
  10829. @<Find and evaluate starting script@>@;
  10830. int retval = app.exec();
  10831. delete engine;
  10832. return retval;@/
  10833. }
  10834. @ \pn{} 1.4 introduces the ability to use icons in certain interface elements.
  10835. Some commonly desired public domain graphics are provided by the Tango Desktop
  10836. Project. We also set an application level default window icon.
  10837. @<Set up icons@>=
  10838. QStringList themeSearchPath = QIcon::themeSearchPaths();
  10839. themeSearchPath.append(":/resources/icons/tango");
  10840. QIcon::setThemeSearchPaths(themeSearchPath);
  10841. QIcon::setThemeName(":/resources/icons/tango");
  10842. app.setWindowIcon(QIcon(":/resources/icons/appicons/logo.svg"));
  10843. @ Similarly some elements make use of a special font which is loaded from
  10844. resource data.
  10845. @<Set up fonts@>=
  10846. QFile entypo(":/resources/fonts/entypo.ttf");
  10847. entypo.open(QIODevice::ReadOnly);
  10848. QFontDatabase::addApplicationFontFromData(entypo.readAll());
  10849. entypo.close();
  10850. @ Some widgets provided by \pn{} require access to a database in order to work.
  10851. To simplify using these widgets, the application will request information
  10852. needed to connect to a database. The use of two distinct |if| blocks rather than
  10853. an |if|$\dots$|else| construction is used because the data from settings can be
  10854. changed if an attempt to connect to the database fails.
  10855. @<Prepare the database connection@>=
  10856. if(settings.value("database/exists", "false").toString() == "true")
  10857. {
  10858. @<Try connecting to the database@>@;
  10859. }
  10860. if(settings.value("database/exists", "false").toString() == "false")
  10861. {
  10862. @<Prompt for database connection information@>@;
  10863. }
  10864. @ In order to connect to the database, we need five pieces of information: the
  10865. name of a database driver (PostgreSQL is recommended for now), the host name of
  10866. the computer running the database, the name of the database, the name of the
  10867. user connecting to the database, and that user's password. This information will
  10868. be stored in the user settings for the application so that the database
  10869. connection can be established without prompting the user next time. A class is
  10870. provided to gather this information.
  10871. @<Class declarations@>=
  10872. class SqlConnectionSetup : public QDialog@/
  10873. {@t\1@>@/
  10874. Q_OBJECT@;
  10875. public:@/
  10876. SqlConnectionSetup();
  10877. ~SqlConnectionSetup();@/
  10878. @t\4@>public slots@t\kern-3pt@>:@/
  10879. void testConnection();
  10880. private:@/
  10881. QFormLayout *formLayout;
  10882. QComboBox *driver;
  10883. QLineEdit *hostname;
  10884. QLineEdit *dbname;
  10885. QLineEdit *user;
  10886. QLineEdit *password;
  10887. QVBoxLayout *layout;
  10888. QHBoxLayout *buttons;
  10889. QPushButton *cancelButton;
  10890. QPushButton *connectButton;@t\2@>@/
  10891. }@t\kern-3pt@>;
  10892. @ The constructor sets up this widget. The destructor does nothing.
  10893. @<SqlConnectionSetup implementation@>=
  10894. SqlConnectionSetup::SqlConnectionSetup() :
  10895. formLayout(new QFormLayout), driver(new QComboBox), hostname(new QLineEdit),
  10896. dbname(new QLineEdit), user(new QLineEdit), password(new QLineEdit),
  10897. layout(new QVBoxLayout), buttons(new QHBoxLayout),
  10898. cancelButton(new QPushButton(tr("Cancel"))),
  10899. connectButton(new QPushButton(tr("Connect")))@/
  10900. {
  10901. driver->addItem("PostgreSQL", "QPSQL");
  10902. formLayout->addRow(tr("Database driver:"), driver);
  10903. formLayout->addRow(tr("Host name:"), hostname);
  10904. formLayout->addRow(tr("Database name:"), dbname);
  10905. formLayout->addRow(tr("User name:"), user);
  10906. password->setEchoMode(QLineEdit::Password);
  10907. formLayout->addRow(tr("Password:"), password);
  10908. layout->addLayout(formLayout);
  10909. buttons->addStretch(1);
  10910. buttons->addWidget(cancelButton);
  10911. connect(cancelButton, SIGNAL(clicked(bool)), this, SLOT(reject()));
  10912. buttons->addWidget(connectButton);
  10913. layout->addLayout(buttons);
  10914. connect(connectButton, SIGNAL(clicked(bool)), this, SLOT(testConnection()));
  10915. setLayout(layout);
  10916. setModal(true);
  10917. }
  10918. SqlConnectionSetup::~SqlConnectionSetup()
  10919. {
  10920. /* Nothing needs to be done here. */
  10921. }
  10922. @ The |testConnection()| method checks if the information provided can be used
  10923. to open a new database connection.
  10924. @<SqlConnectionSetup implementation@>=
  10925. void SqlConnectionSetup::testConnection()
  10926. {
  10927. QSqlDatabase database =
  10928. QSqlDatabase::addDatabase(driver->itemData(driver->currentIndex()).
  10929. toString());
  10930. database.setHostName(hostname->text());
  10931. database.setDatabaseName(dbname->text());
  10932. database.setUserName(user->text());
  10933. database.setPassword(password->text());
  10934. if(database.open())
  10935. {
  10936. QSettings settings;
  10937. settings.setValue("database/exists", "true");
  10938. settings.setValue("database/driver",
  10939. driver->itemData(driver->currentIndex()).toString());
  10940. settings.setValue("database/hostname", hostname->text());
  10941. settings.setValue("database/dbname", dbname->text());
  10942. settings.setValue("database/user", user->text());
  10943. settings.setValue("database/password", password->text());
  10944. accept();
  10945. }
  10946. else
  10947. {
  10948. QMessageBox::information(this, tr("Database connection failed"),
  10949. tr("Failed to connect to database."));
  10950. }
  10951. }
  10952. @ In order to prompt for connection information, we simply create a
  10953. |SqlConnectionSetup| object and call |exec()|. When control returns, the
  10954. settings will either contain appropriate connection information or we have to
  10955. give up on getting that information from the user for now.
  10956. @<Prompt for database connection information@>=
  10957. SqlConnectionSetup dialog;
  10958. dialog.exec();
  10959. @ If we have connected to a database in the previous running of the application,
  10960. we try to connect to the same database automatically rather than prompt the
  10961. user. If the connection attempt fails, we can fall back on asking the user for
  10962. help.
  10963. @<Try connecting to the database@>=
  10964. QSqlDatabase database =
  10965. QSqlDatabase::addDatabase(settings.value("database/driver").toString());
  10966. database.setHostName(settings.value("database/hostname").toString());
  10967. database.setDatabaseName(settings.value("database/dbname").toString());
  10968. database.setUserName(settings.value("database/user").toString());
  10969. database.setPassword(settings.value("database/password").toString());
  10970. if(!database.open())
  10971. {
  10972. settings.setValue("database/exists", "false");
  10973. }
  10974. @** Viewing a record of batches.
  10975. \noindent It is frequently useful to present a table view with the results of a
  10976. SQL query and have a way of interacting with that view to obtain more details
  10977. related to a given record in that table. For this purpose, \pn{} provides a
  10978. widget based on |QTableView| which presents information from a
  10979. |QSqlQueryModel|. The table emits signals when an entry in the table is double
  10980. clicked. One of these contains the data from the first column of that row and
  10981. is suitable for use when a primary key is presented in that column and this is
  10982. sufficient for the desired drill down. The other signal provides the row number
  10983. which can be used along with a reference to the table to obtain the data in any
  10984. column.
  10985. This class also automatically persists column widths when these are changed.
  10986. @<Class declarations@>=
  10987. class SqlQueryView : public QTableView@/
  10988. {@t\1@>@/
  10989. Q_OBJECT@;
  10990. public:@/
  10991. SqlQueryView(QWidget *parent = NULL);
  10992. void setQuery(const QString &query);
  10993. bool setHeaderData(int section, Qt::Orientation@, orientation,
  10994. const QVariant &value, int role);
  10995. Q_INVOKABLE QVariant data(int row, int column,
  10996. int role = Qt::DisplayRole);@/
  10997. signals:@/
  10998. void openEntry(QString key);
  10999. void openEntryRow(int row);@t\2@>@/
  11000. protected:@/
  11001. virtual void showEvent(QShowEvent *event);
  11002. private slots@t\kern-3pt@>:@t\1@>@/
  11003. void openRow(const QModelIndex &index);
  11004. void persistColumnResize(int column, int oldsize, int newsize);@t\2@>@/
  11005. }@t\kern-3pt@>;
  11006. @ The constructor sets up the communication between the model and the view and
  11007. also provides the connection needed to notice when columns change size to
  11008. persist that preference.
  11009. @<SqlQueryView implementation@>=
  11010. SqlQueryView::SqlQueryView(QWidget *parent) : QTableView(parent)
  11011. {
  11012. setModel(new QSqlQueryModel);
  11013. connect(this, SIGNAL(doubleClicked(QModelIndex)),
  11014. this, SLOT(openRow(QModelIndex)));
  11015. connect(horizontalHeader(), SIGNAL(sectionResized(int, int, int)),
  11016. this, SLOT(persistColumnResize(int, int, int)));
  11017. }
  11018. @ Column width persistance requires two methods. First we have a slot
  11019. method which is called when a column width is changed. This is saved with
  11020. |QSettings| under a key utilizing the name of the window, the name of the
  11021. table, and the column number.
  11022. @<SqlQueryView implementation@>=
  11023. void SqlQueryView::persistColumnResize(int column, int, int newsize)
  11024. {
  11025. @<Save updated column size@>@;
  11026. }
  11027. @ The body of this function has been split out so that it can be shared with
  11028. other table views without the need to introduce a new common base class.
  11029. @<Save updated column size@>=
  11030. QSettings settings;
  11031. @<Obtain top level widget@>@;
  11032. settings.setValue(QString("columnWidths/%1/%2/%3").
  11033. arg(topLevelWidget->objectName()).
  11034. arg(objectName()).arg(column),
  11035. QVariant(newsize));
  11036. @ To determine which window a given table is in, we just follow
  11037. |parentWidget()| until there isn't one. It is possible that the table view
  11038. will also be the window, however this is not advised as it is easier for the
  11039. settings key to be non-unique in such a case.
  11040. @<Obtain top level widget@>=
  11041. QWidget *topLevelWidget = this;
  11042. while(topLevelWidget->parentWidget())
  11043. {
  11044. topLevelWidget = topLevelWidget->parentWidget();
  11045. }
  11046. @ We restore column widths in response to a show event. One of these should be
  11047. received just before the widget is shown so the widget should appear correctly.
  11048. @<SqlQueryView implementation@>=
  11049. void SqlQueryView::showEvent(QShowEvent *event)
  11050. {
  11051. @<Restore table column widths@>@;
  11052. event->accept();
  11053. }
  11054. @ Similarly, most of the body of this method has also been split into a chunk
  11055. so that it might be shared with other classes.
  11056. @<Restore table column widths@>=
  11057. QSettings settings;
  11058. @<Obtain top level widget@>
  11059. QString baseKey =
  11060. QString("columnWidths/%1/%2").arg(topLevelWidget->objectName()).
  11061. arg(objectName());
  11062. for(int i = 0; i < model()->columnCount(); i++)
  11063. {
  11064. QString key = QString("%1/%2").arg(baseKey).arg(i);
  11065. if(settings.contains(key))
  11066. {
  11067. setColumnWidth(i, settings.value(key).toInt());
  11068. }
  11069. }
  11070. @ A slot is required for obtaining the information to send out in our signals.
  11071. @<SqlQueryView implementation@>=
  11072. void SqlQueryView::openRow(const QModelIndex &index)
  11073. {
  11074. emit openEntry(((QSqlQueryModel *)model())->record(index.row()).value(0).toString());
  11075. emit openEntryRow(index.row());
  11076. }
  11077. @ The other functions are wrappers around model methods.
  11078. \danger |setQuery()| leaks database connections.
  11079. @<SqlQueryView implementation@>=
  11080. void SqlQueryView::setQuery(const QString &query)
  11081. {
  11082. QSqlDatabase database = AppInstance->database();
  11083. database.open();
  11084. QSqlQuery q(query, database);
  11085. ((QSqlQueryModel*)model())->setQuery(q);
  11086. }
  11087. bool SqlQueryView::setHeaderData(int section, Qt::Orientation@, orientation,
  11088. const QVariant &value, int role)
  11089. {
  11090. return model()->setHeaderData(section, orientation, value, role);
  11091. }
  11092. @ A method is also provided to allow scripts to access the data.
  11093. @<SqlQueryView implementation@>=
  11094. QVariant SqlQueryView::data(int row, int column, int role)
  11095. {
  11096. return model()->data(model()->index(row, column), role);
  11097. }
  11098. @ To use this class, it is useful to expose it to the host environment.
  11099. @<Function prototypes for scripting@>=
  11100. void setSqlQueryViewProperties(QScriptValue value, QScriptEngine *engine);
  11101. QScriptValue constructSqlQueryView(QScriptContext *context,
  11102. QScriptEngine *engine);
  11103. QScriptValue SqlQueryView_setQuery(QScriptContext *context,
  11104. QScriptEngine *engine);
  11105. QScriptValue SqlQueryView_setHeaderData(QScriptContext *context,
  11106. QScriptEngine *engine);
  11107. @ The script constructor is passed to the host environment.
  11108. @<Set up the scripting engine@>=
  11109. constructor = engine->newFunction(constructSqlQueryView);
  11110. value = engine->newQMetaObject(&SqlQueryView::staticMetaObject, constructor);
  11111. engine->globalObject().setProperty("SqlQueryView", value);
  11112. @ Next we construct the view, add properties to access its methods from the host
  11113. environment, and pass that back.
  11114. @<Functions for scripting@>=
  11115. QScriptValue constructSqlQueryView(QScriptContext *, QScriptEngine *engine)
  11116. {
  11117. QScriptValue object = engine->newQObject(new SqlQueryView);
  11118. setSqlQueryViewProperties(object, engine);
  11119. return object;
  11120. }
  11121. void setSqlQueryViewProperties(QScriptValue value, QScriptEngine *engine)
  11122. {
  11123. setQTableViewProperties(value, engine);
  11124. value.setProperty("setHeaderData",
  11125. engine->newFunction(SqlQueryView_setHeaderData));
  11126. value.setProperty("setQuery", engine->newFunction(SqlQueryView_setQuery));
  11127. }
  11128. @ The properties added are simplified wrappers around the class methods.
  11129. @<Functions for scripting@>=
  11130. QScriptValue SqlQueryView_setQuery(QScriptContext *context, QScriptEngine *)
  11131. {
  11132. SqlQueryView *self = getself<SqlQueryView *>(context);
  11133. QString query = argument<QString>(0, context);
  11134. self->setQuery(query);
  11135. self->reset();
  11136. return QScriptValue();
  11137. }
  11138. QScriptValue SqlQueryView_setHeaderData(QScriptContext *context,
  11139. QScriptEngine *)
  11140. {
  11141. SqlQueryView *self = getself<SqlQueryView *>(context);
  11142. int section = argument<int>(0, context);
  11143. QString data = argument<QString>(1, context);
  11144. self->setHeaderData(section, Qt::Horizontal, data, Qt::DisplayRole);
  11145. return QScriptValue();
  11146. }
  11147. @** Reporting.
  11148. \noindent \pn{} version 1.4 added a new type of menu which is designed to
  11149. handle reports. This makes extensive use of the previously existing reporting
  11150. system at present which makes modifying existing reports to work with the new
  11151. system very simple. Further changes may be introduced in the future that
  11152. substantially depart from this in order to simplify report files.
  11153. Previously to add a new report to a configuration, you needed to create the
  11154. report, add an {\tt <include>} tag in the main configuration file to bring that
  11155. report into the application configuration, then in any window with a Reports
  11156. menu you would need to add the report to that menu in its configuration file
  11157. and write a small bit of JavaScript to obtain a reference to that new menu
  11158. item and create the report when that menu item is triggered. This is highly
  11159. repetetive, error prone, and with the new approach it is not needed at all.
  11160. To add a new report to a configuration using the new approach one need only
  11161. save the new report file in the appropriate directory and \pn{} will detect
  11162. this, add it to any Reports menus that may exist, and handle all of the details
  11163. of generating these reports on demand.
  11164. The Reports menu is created in a configuration as a {\tt <menu>} element with
  11165. three attributes. The {\tt name} attribute as usual is the name of the menu
  11166. item. The {\tt type} attribute will have a value of {\tt "reports"} and the
  11167. {\tt src} attribute will indicate the directory to search for reports to
  11168. populate that menu. This allows for multiple Reports menus with different
  11169. reports in each menu if desired.
  11170. Reports are added to the menu in the order of the file names in the reports
  11171. directory.
  11172. \danger While it should not be an issue with the limited number of reports
  11173. presently distributed with Typica, the approach taken to implementing this menu
  11174. type is highly inefficient. There are many optimizations available if this
  11175. becomes problematic.\endanger
  11176. @<Populate reports menu@>=
  11177. QSettings settings;
  11178. QDir directory(QString("%1/%2").arg(settings.value("config").toString()).
  11179. arg(element.attribute("src")));
  11180. directory.setFilter(QDir::Files);
  11181. directory.setSorting(QDir::Name);
  11182. QStringList nameFilter;
  11183. nameFilter << "*.xml";
  11184. directory.setNameFilters(nameFilter);
  11185. QFileInfoList reportFiles = directory.entryInfoList();
  11186. for(int i = 0; i < reportFiles.size(); i++)
  11187. {
  11188. QFileInfo reportFile = reportFiles.at(i);
  11189. @<Add report to reports menu@>@;
  11190. }
  11191. @ The menu items themselves are a subclass of |QAction| which holds all of the
  11192. information needed to respond to its activation by generating the appropriate
  11193. report.
  11194. @<Class declarations@>=
  11195. class ReportAction : public QAction
  11196. {
  11197. Q_OBJECT
  11198. public:
  11199. ReportAction(const QString &fileName, const QString &reportName,
  11200. QObject *parent = NULL);
  11201. private slots:
  11202. void createReport();
  11203. private:
  11204. QString reportFile;
  11205. };
  11206. @ The constructor receives the name of the report file which is used to
  11207. generate the report when needed and the name of the report which is used as the
  11208. name presented in the menu.
  11209. @<ReportAction implementation@>=
  11210. ReportAction::ReportAction(const QString &fileName, const QString &reportName,
  11211. QObject *parent) :
  11212. QAction(reportName, parent), reportFile(fileName)
  11213. {
  11214. connect(this, SIGNAL(triggered()), this, SLOT(createReport()));
  11215. }
  11216. @ The slot method is responsible for creating the new report. This is very
  11217. similar to the old approach and reuses much of the same code. Of particular
  11218. note is the |targetID| variable. This is set to facilitate window geometry
  11219. management, though this should probably be set from the {\tt id} attribute
  11220. of the {\tt <window>} element in the file to preserve window geometry
  11221. settings if the configuration is moved to another location in the file
  11222. system.
  11223. @<ReportAction implementation@>=
  11224. void ReportAction::createReport()
  11225. {
  11226. QFile file(reportFile);
  11227. QDomDocument document;
  11228. if(file.open(QIODevice::ReadOnly))
  11229. {
  11230. document.setContent(&file, true);
  11231. QDomElement element = document.documentElement();
  11232. QScriptEngine *engine = AppInstance->engine;
  11233. QScriptContext *context = engine->pushContext();
  11234. QScriptValue object;
  11235. QString targetID = reportFile;
  11236. @<Display the window@>@;
  11237. file.close();
  11238. engine->popContext();
  11239. }
  11240. }
  11241. @ With the |ReportAction| available, we are now ready to add reports to the
  11242. Reports menu. To do this we check each file in the given directory to determine
  11243. if it is a report file, obtain the report title and location within the menu
  11244. hierarchy from the file data, create the actions, and add them to the menu.
  11245. @<Add report to reports menu@>=
  11246. QString path = reportFile.absoluteFilePath();
  11247. QFile file(path);
  11248. if(file.open(QIODevice::ReadOnly))
  11249. {
  11250. QDomDocument document;
  11251. document.setContent(&file, true);
  11252. QDomElement root = document.documentElement();
  11253. QDomNode titleNode = root.elementsByTagName("reporttitle").at(0);
  11254. if(!titleNode.isNull())
  11255. {
  11256. QDomElement titleElement = titleNode.toElement();
  11257. QString title = titleElement.text();
  11258. if(!title.isEmpty())
  11259. {
  11260. QStringList hierarchy = title.split(":->");
  11261. QMenu *insertionPoint = menu;
  11262. @<Traverse report menu hierarchy@>
  11263. ReportAction *action = new ReportAction(path, hierarchy.last());
  11264. insertionPoint->addAction(action);
  11265. }
  11266. }
  11267. }
  11268. @ \pn{} allows the Reports menu to contain arbitrarily deep menu hierarchies.
  11269. It is advised to keep these hierarchies shallow.
  11270. @<Traverse report menu hierarchy@>=
  11271. for(int j = 0; j < hierarchy.size() - 1; j++)
  11272. {
  11273. QObjectList menuList = insertionPoint->children();
  11274. bool menuFound = false;
  11275. for(int k = 0; k < menuList.size(); k++)
  11276. {
  11277. QMenu *currentItem = qobject_cast<QMenu*>(menuList.at(k));
  11278. if(currentItem)
  11279. {
  11280. if(currentItem->title() == hierarchy.at(j))
  11281. {
  11282. menuFound = true;
  11283. insertionPoint = currentItem;
  11284. break;
  11285. }
  11286. }
  11287. }
  11288. if(!menuFound)
  11289. {
  11290. insertionPoint = insertionPoint->addMenu(hierarchy.at(j));
  11291. }
  11292. }
  11293. @ \noindent The reporting functionality in \pn{} is based on the Scribe framework
  11294. in Qt. This brings several benefits, including making it easy to print reports
  11295. or save reports as plain text or HTML.
  11296. Reports are specified in the \pn{}'s configuration document and can include both
  11297. static elements and elements that are populated by external data such as the
  11298. result of a SQL query.
  11299. @<Function prototypes for scripting@>=
  11300. void addReportToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  11301. QStack<QLayout *> *layoutStack);
  11302. @ When adding a report to a layout, we must not only add the widget to the
  11303. layout, but also construct the document.
  11304. @<Functions for scripting@>=
  11305. void addReportToLayout(QDomElement element, QStack<QWidget *> *,@|
  11306. QStack<QLayout *> *layoutStack)
  11307. {
  11308. QTextEdit *widget = new QTextEdit;
  11309. if(element.hasAttribute("id"))
  11310. {
  11311. widget->setObjectName(element.attribute("id"));
  11312. }
  11313. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  11314. layout->addWidget(widget);
  11315. QTextDocument *document = new QTextDocument;
  11316. QFont defaultFont;
  11317. defaultFont.setPointSize(11);
  11318. document->setDefaultFont(defaultFont);
  11319. QTextCursor cursor(document);
  11320. @<Construct report document@>@;
  11321. widget->setDocument(document);
  11322. }
  11323. @ Several child elements are allowed under the {\tt <report>} element. These
  11324. should be processed in order to produce the final report document.
  11325. @<Construct report document@>=
  11326. QDomNodeList children = element.childNodes();
  11327. for(int i = 0; i < children.count(); i++)
  11328. {
  11329. QDomNode current;
  11330. QDomElement currentElement;
  11331. current = children.at(i);
  11332. if(current.isElement())
  11333. {
  11334. currentElement = current.toElement();
  11335. @<Process report document elements@>@;
  11336. }
  11337. }
  11338. @ If any custom styling for HTML content is required, a {\tt <style>} element
  11339. should be placed in the report description before any such content.
  11340. @<Process report document elements@>=
  11341. if(currentElement.tagName() == "style")
  11342. {
  11343. document->setDefaultStyleSheet(currentElement.text());
  11344. }
  11345. @ One common need is the ability to insert static text, such as the title of the
  11346. report. In order to simplify formatting, the text can be interpreted as HTML.
  11347. Note that to avoid having HTML tags eaten by the parser, the text of this
  11348. element should be a CDATA section.
  11349. @<Process report document elements@>=
  11350. if(currentElement.tagName() == "html")
  11351. {
  11352. cursor.insertHtml(currentElement.text());
  11353. }
  11354. @ If no special formatting is needed, a plain text element can be used. This
  11355. might be extended in the future to allow attributes for specifying the character
  11356. formatting to be used with the text.
  11357. @<Process report document elements@>=
  11358. if(currentElement.tagName() == "text")
  11359. {
  11360. cursor.insertText(currentElement.text());
  11361. }
  11362. @ One of the more interesting elements of a report is the {\tt <table>} element.
  11363. This is an element which can change its contents in response to changes in user
  11364. controls.
  11365. @<Process report document elements@>=
  11366. if(currentElement.tagName() == "table")
  11367. {
  11368. QTextFrame *frame = cursor.insertFrame(QTextFrameFormat());
  11369. ReportTable *table = new ReportTable(frame, currentElement);
  11370. table->setParent(widget);
  11371. if(currentElement.hasAttribute("id"))
  11372. {
  11373. table->setObjectName(currentElement.attribute("id"));
  11374. }
  11375. }
  11376. @ The |ReportTable| class is responsible for parsing {\tt <table>} child
  11377. elements and inserting the table into the document at the correct location.
  11378. @<Class declarations@>=
  11379. class ReportTable : public QObject@/
  11380. {@t\1@>@/
  11381. Q_OBJECT@;
  11382. QTextFrame *area;
  11383. QDomElement configuration;
  11384. QMap<QString, QVariant> bindings;
  11385. public:@/
  11386. ReportTable(QTextFrame *frame, QDomElement description);
  11387. ~ReportTable();
  11388. @[Q_INVOKABLE@,@, void@]@, bind(QString placeholder, QVariant value);@t\2\2@>@/
  11389. @t\4@>public slots@t\kern-3pt@>:@/
  11390. void refresh();@t\2@>@/
  11391. }@t\kern-3pt@>;
  11392. @ The |ReportTable| class takes a |QTextFrame| and |QDomElement| pointer in
  11393. its constructor. The former is used to establish the bounds of the table within
  11394. a document and the latter is used for generating the table contents.
  11395. @<ReportTable implementation@>=
  11396. ReportTable::ReportTable(QTextFrame *frame, QDomElement description) :
  11397. area(frame), configuration(description)
  11398. {
  11399. refresh();
  11400. }
  11401. ReportTable::~ReportTable()
  11402. {
  11403. }
  11404. @ In order to change the table contents based on user controls, the |bind()|
  11405. method allows a placeholder to be replaced with a value when evaluating a SQL
  11406. query.
  11407. @<ReportTable implementation@>=
  11408. void ReportTable::bind(QString placeholder, QVariant value)
  11409. {
  11410. bindings.insert(placeholder, value);
  11411. }
  11412. @ All of the interesting work is done in the |refresh()| slot. This method
  11413. deletes the current content of the frame and creates a table based on the
  11414. description of the table in the configuration document.
  11415. @<ReportTable implementation@>=
  11416. void ReportTable::refresh()
  11417. {
  11418. @<Delete current report table content@>@;
  11419. int rows = 1;
  11420. int columns = 1;
  11421. int currentRow = 0;
  11422. QTextTable *table = cursor.insertTable(rows, columns);
  11423. @<Set table formatting@>@;
  11424. @<Reconstruct report table content@>@;
  11425. if(rows > 1)
  11426. {
  11427. table->removeRows(0, 1);
  11428. }
  11429. }
  11430. @ Deleting the current content of the table involves using a cursor to select
  11431. everything in the frame and then removing that selection. There are more optimal
  11432. ways to do this but if there are performance problems with this, you may want to
  11433. reconsider what you are trying to do.
  11434. @<Delete current report table content@>=
  11435. QTextCursor cursor = area->firstCursorPosition();
  11436. while(cursor < area->lastCursorPosition())
  11437. {
  11438. cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
  11439. }
  11440. cursor.removeSelectedText();
  11441. @ When creating a new table, we may need to alter the formatting of that table.
  11442. To do this, we get the current format, modify that based on attributes of the
  11443. {\tt <table>} element, and apply the modified copy to the newly constructed
  11444. table.
  11445. @<Set table formatting@>=
  11446. QTextTableFormat format = table->format();
  11447. format.setBorderStyle(QTextFrameFormat::BorderStyle_None);
  11448. if(configuration.hasAttribute("align"))
  11449. {
  11450. if(configuration.attribute("align") == "center")
  11451. {
  11452. format.setAlignment(Qt::AlignHCenter);
  11453. }
  11454. }
  11455. table->setFormat(format);
  11456. @ To reconstruct the table, we need to parse the description of the table.
  11457. @<Reconstruct report table content@>=
  11458. QDomNodeList children = configuration.childNodes();
  11459. for(int i = 0; i < children.count(); i++)
  11460. {
  11461. QDomNode current;
  11462. QDomElement currentElement;
  11463. current = children.at(i);
  11464. if(current.isElement())
  11465. {
  11466. currentElement = current.toElement();
  11467. if(currentElement.tagName() == "query")
  11468. {
  11469. @<Add SQL query results to report table@>@;
  11470. }
  11471. else if(currentElement.tagName() == "row")
  11472. {
  11473. @<Add new row to report table@>@;
  11474. }
  11475. }
  11476. }
  11477. @ The text of a {\tt <query>} element will be the query desired in the table.
  11478. This might include placeholders that must be bound to values before the query is
  11479. executed. If query execution results in an error (as it will if it contains
  11480. placeholders that have not yet had values bound to them), there will be no
  11481. change to the table and the next child element, if any, will be processed.
  11482. @<Add SQL query results to report table@>=
  11483. SqlQueryConnection query;
  11484. query.prepare(currentElement.text());
  11485. foreach(QString key, bindings.uniqueKeys())
  11486. {
  11487. if(currentElement.text().contains(key))
  11488. {
  11489. query.bindValue(key, bindings.value(key));
  11490. }
  11491. }
  11492. query.exec();
  11493. if(!query.next())
  11494. {
  11495. continue;
  11496. }
  11497. if(query.record().count() > columns)
  11498. {
  11499. table->appendColumns(query.record().count() - columns);
  11500. }
  11501. do
  11502. {
  11503. table->appendRows(1);
  11504. rows++;
  11505. currentRow++;
  11506. for(int j = 0; j < query.record().count(); j++)
  11507. {
  11508. QTextTableCell cell = table->cellAt(currentRow, j);
  11509. cursor = cell.firstCursorPosition();
  11510. cursor.insertText(query.value(j).toString());
  11511. }
  11512. } while(query.next());
  11513. @ It is sometimes desirable to add fixed data such as column headers to a table.
  11514. This is done with the {\tt <row>} element.
  11515. Technically, this isn't needed. The same results can be produced by using a
  11516. {\tt <query>} element to select constant data, but this approach saves a trip to
  11517. the database.
  11518. @<Add new row to report table@>=
  11519. table->appendRows(1);
  11520. currentRow++;
  11521. rows++;
  11522. QDomNodeList rowChildren = currentElement.childNodes();
  11523. int currentColumn = 0;
  11524. for(int j = 0; j < rowChildren.count(); j++)
  11525. {
  11526. QDomNode node;
  11527. QDomElement nodeElement;
  11528. node = rowChildren.at(j);
  11529. if(node.isElement())
  11530. {
  11531. nodeElement = node.toElement();
  11532. if(nodeElement.tagName() == "cell")
  11533. {
  11534. if(currentColumn == columns)
  11535. {
  11536. table->appendColumns(1);
  11537. columns++;
  11538. }
  11539. QTextTableCell cell = table->cellAt(currentRow, currentColumn);
  11540. cursor = cell.firstCursorPosition();
  11541. cursor.insertText(nodeElement.text());
  11542. currentColumn++;
  11543. }
  11544. }
  11545. }
  11546. @ In order to expose report printing capabilities, we provide a property on
  11547. |QTextEdit| objects to handle this.
  11548. @<Function prototypes for scripting@>=
  11549. void setQTextEditProperties(QScriptValue value, QScriptEngine *engine);
  11550. QScriptValue QTextEdit_print(QScriptContext *context, QScriptEngine *engine);
  11551. @ This function is a trivial adaptation from the Qt documentation.
  11552. @<Functions for scripting@>=
  11553. QScriptValue QTextEdit_print(QScriptContext *context, QScriptEngine *)
  11554. {
  11555. QTextEdit *self = getself<QTextEdit *>(context);
  11556. QTextDocument *document = self->document();
  11557. QPrinter printer;
  11558. QPrintDialog printwindow(&printer, self);
  11559. if(printwindow.exec() != QDialog::Accepted)
  11560. {
  11561. return QScriptValue();
  11562. }
  11563. document->print(&printer);
  11564. return QScriptValue();
  11565. }
  11566. @ The host environment must be informed of this function.
  11567. @<Functions for scripting@>=
  11568. void setQTextEditProperties(QScriptValue value, QScriptEngine *engine)
  11569. {
  11570. setQAbstractScrollAreaProperties(value, engine);
  11571. value.setProperty("print", engine->newFunction(QTextEdit_print));
  11572. }
  11573. @** An area for repeated user interface elements.
  11574. \noindent There are multiple use cases in which it is useful to specify a
  11575. complex aggregation of user interface elements to be repeated arbitrarily many
  11576. times. For example, placing multiple copies of a cupping form in a single area
  11577. for conveniently entering observations for all coffees in a particular session
  11578. or providing any number of copies of the form for entering coffee purchase
  11579. information. The |FormArray| widget provides this capability, allowing the
  11580. XML portion of the configuration document to specify the form once and allowing
  11581. the host environment to access the copies.
  11582. Slots and the |Q_INVOKABLE| macro are used to simplify the use of this class
  11583. from the host environment.
  11584. @<Class declarations@>=
  11585. class FormArray : public QScrollArea@/
  11586. {@t\1@>@/
  11587. Q_OBJECT@;
  11588. QDomElement configuration;
  11589. QWidget itemContainer;
  11590. QVBoxLayout itemLayout;
  11591. int maxwidth;
  11592. int maxheight;
  11593. public:@/
  11594. FormArray(QDomElement description);
  11595. @[Q_INVOKABLE@,@, QWidget*@] elementAt(int index);@t\2\2@>@/
  11596. @[Q_INVOKABLE@,@, int@] elements();@t\2\2@>@/
  11597. @t\4@>public slots@t\kern-3pt@>:@/
  11598. void addElements(int copies = 1);
  11599. void removeAllElements();
  11600. void setMaximumElementWidth(int width);
  11601. void setMaximumElementHeight(int height);@t\2@>@/
  11602. }@t\kern-3pt@>;
  11603. @ The |FormArray| is just a |QScrollArea| providing a view onto a |QWidget|
  11604. containing a layout which has arbitrarily many copies of a |QWidget| with
  11605. contents determined by the configuration document used to create the
  11606. |FormArray|.
  11607. @<FormArray implementation@>=
  11608. FormArray::FormArray(QDomElement description) : configuration(description),
  11609. maxwidth(-1), maxheight(-1)@/
  11610. {
  11611. setWidget(&itemContainer);
  11612. itemContainer.setLayout(&itemLayout);
  11613. }
  11614. @ The |FormArray| was initially created by an XML element. A copy of this is
  11615. stored in the private variable |configuration|. This can have the same child
  11616. elements as {\tt <widget>}, allowing us to reuse the function for creating
  11617. populating the widget. When adding a new element, we must resize the
  11618. |itemContainer|, otherwise Qt will attempt to cram all widgets in the layout
  11619. into the same vertical space as was previously required. The result is not
  11620. attractive. We also set a minimum width just in case the newly created widget is
  11621. the first one added to the area.
  11622. @<FormArray implementation@>=
  11623. void FormArray::addElements(int copies)
  11624. {
  11625. QStack<QWidget *> *widgetStack = new QStack<QWidget *>;
  11626. QStack<QLayout *> *layoutStack = new QStack<QLayout *>;
  11627. QWidget *widget;
  11628. for(int i = 0; i < copies; i++)
  11629. {
  11630. widget = new QWidget;
  11631. if(maxwidth > -1)
  11632. {
  11633. widget->setMaximumWidth(maxwidth);
  11634. }
  11635. if(maxheight > -1)
  11636. {
  11637. widget->setMaximumHeight(maxheight);
  11638. }
  11639. if(configuration.hasChildNodes())
  11640. {
  11641. widgetStack->push(widget);
  11642. populateWidget(configuration, widgetStack, layoutStack);
  11643. widgetStack->pop();
  11644. widget->setMinimumHeight(widget->sizeHint().height());
  11645. itemLayout.addWidget(widget);
  11646. if(widget->sizeHint().height() > maxheight && maxheight > -1)
  11647. {
  11648. itemContainer.setMinimumHeight(maxheight * elements() + 50);
  11649. }
  11650. else
  11651. {
  11652. itemContainer.setMinimumHeight(itemContainer.sizeHint().height()
  11653. + widget->sizeHint().height());
  11654. }
  11655. if(maxwidth > -1)
  11656. {
  11657. itemContainer.setMinimumWidth(maxwidth + 50);
  11658. }
  11659. else
  11660. {
  11661. itemContainer.setMinimumWidth(widget->sizeHint().width() + 50);
  11662. }
  11663. }
  11664. }
  11665. }
  11666. @ In order to retrieve a widget from the area, we use the |elementAt()| method.
  11667. The pointer returned by this function can be used as the first argument to
  11668. |findChildObject()| in the host environment in order to find any widget in the
  11669. form.
  11670. @<FormArray implementation@>=
  11671. QWidget* FormArray::elementAt(int index)
  11672. {
  11673. if(index < itemLayout.count())
  11674. {
  11675. QLayoutItem *item = itemLayout.itemAt(index);
  11676. return item->widget();
  11677. }
  11678. else
  11679. {
  11680. return NULL;
  11681. }
  11682. }
  11683. @ Removing all elements is trivial, however we must be sure to reset the size of
  11684. |itemContainer|.
  11685. @<FormArray implementation@>=
  11686. void FormArray::removeAllElements()
  11687. {
  11688. while(itemLayout.count() > 0)
  11689. {
  11690. QLayoutItem *item;
  11691. item = itemLayout.itemAt(0);
  11692. item->widget()->hide();
  11693. itemLayout.removeWidget(item->widget());
  11694. }
  11695. itemContainer.setMinimumHeight(0);
  11696. }
  11697. @ This just leaves a method for determining the number of elements already in
  11698. the view. This is equal to the number of items in the layout.
  11699. @<FormArray implementation@>=
  11700. int FormArray::elements()
  11701. {
  11702. return itemLayout.count();
  11703. }
  11704. @ Some widgets do not behave well in a |FormArray| setting and will try to use
  11705. an excess of screen space. In these cases, constraining the size of the elements
  11706. can be beneficial. These just set private member variables which are used when
  11707. adding new elements.
  11708. @<FormArray implementation@>=
  11709. void FormArray::setMaximumElementWidth(int width)
  11710. {
  11711. maxwidth = width;
  11712. }
  11713. void FormArray::setMaximumElementHeight(int height)
  11714. {
  11715. maxheight = height;
  11716. }
  11717. @ In order to create an instance of this class from the configuration document,
  11718. a {\tt <formarray>} element is used. This can be added to any layout.
  11719. @<Function prototypes for scripting@>=
  11720. void addFormArrayToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  11721. QStack<QLayout *> *layoutStack);
  11722. @ Processing child elements is deferred until a call to
  11723. |FormArray::addElements()| has been made.
  11724. @<Functions for scripting@>=
  11725. void addFormArrayToLayout(QDomElement element, QStack<QWidget *> *,@|
  11726. QStack<QLayout *> *layoutStack)
  11727. {
  11728. FormArray *widget = new FormArray(element);
  11729. if(element.hasAttribute("id"))
  11730. {
  11731. widget->setObjectName(element.attribute("id"));
  11732. }
  11733. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  11734. layout->addWidget(widget);
  11735. }
  11736. @** Scale widgets.
  11737. \noindent One of the most commonly used methods of documenting the properties of
  11738. a coffee is through a cupping form. Several such forms exist to meet different
  11739. needs, however most involve several scales which can be marked to determine some
  11740. aspect of a particular attribute. Some of these scales are scored values which,
  11741. when considered with other scored values produce a numerical representation of
  11742. the quality of a given coffee. Others are unscored values which serve to provide
  11743. additional documentation of a property. For example, when the SCAA cupping form
  11744. expanded to the current form of ten scored properties with defects subtracted
  11745. from the total, a second scale was added for the acidity property. The scored
  11746. scale is used for marking the quality of the acidity while another unscored
  11747. scale is used for marking the intensity of that acidity.
  11748. Previously, in order to enter cupping information in \pn{}, numeric entry fields
  11749. were used. While this was very efficient for transcribing paper cupping forms
  11750. (and this was, in fact, the principal use case for our prototype cupping form
  11751. database software), it is not a form that lends itself to convenient use at the
  11752. cupping table.
  11753. Two new widgets are therefore introduced which allows a cupper to simply click
  11754. at some point on the scale to record that impression. Unfortunately, this is
  11755. still something of a tradeoff. It is not quite so efficient as using a paper
  11756. form in my experience, however it is faster than transcribing a stack of cupping
  11757. forms, particularly when working with cuppers with ambiguous handwriting. By
  11758. moving data acquisition to the point of data generation, a more useful record
  11759. can be produced for use in aggregate analysis.
  11760. @* The Horizontal Scale.
  11761. \noindent Several cupping forms make use of 10 point scales for the quality of
  11762. various attributes. The |ScaleControl| widget provides such a scale. It
  11763. consists of a bar with major ticks at 0, 5, and 10 and minor ticks at integer
  11764. values within this range. The first click sets both the initial and final value
  11765. of the scale while subsequent clicks adjust only the final value. A pair of
  11766. controls at each end of the scale allows the user to adjust either of these
  11767. values to compensate for imprecision at the point of the click. The two values,
  11768. an initial unscored value and a final scored value, provide some limited
  11769. temporal documentation. That is, it documents how the perception of a coffee
  11770. changes as it cools.
  11771. The widget is implemented as a |QGraphicsView| subclass. Please note that the
  11772. scale widgets are not particularly robust. In order to support a broader range
  11773. of cupping forms, there are plans to extend this class to allow user defined
  11774. range and tick patterns and user defined colors for the indicators.
  11775. @<Class declarations@>=
  11776. class ScaleControl : public QGraphicsView@/
  11777. {@t\1@>@/
  11778. Q_OBJECT@/
  11779. Q_PROPERTY(double initialValue READ initialValue WRITE setInitialValue)@/
  11780. Q_PROPERTY(double finalValue READ finalValue WRITE setFinalValue)@/
  11781. @<ScaleControl private members@>@t\2\2@>@/
  11782. public:@/
  11783. ScaleControl();
  11784. double initialValue(void);
  11785. double finalValue(void);
  11786. virtual QSize sizeHint() const;@/
  11787. @[public slots@]:@/
  11788. void setInitialValue(double value);
  11789. void setFinalValue(double value);@/
  11790. signals:@/
  11791. void initialChanged(double);
  11792. void finalChanged(double);@/
  11793. protected:@/
  11794. virtual void mousePressEvent(QMouseEvent *event);
  11795. virtual void mouseReleaseEvent(QMouseEvent *event);@t\2@>@/
  11796. }@t\kern-4pt@>;
  11797. @ The private variables available to instances of this class are used for
  11798. managing various aspects of the widget.
  11799. @<ScaleControl private members@>=
  11800. QGraphicsScene scene;
  11801. QGraphicsPolygonItem initialDecrement;
  11802. QGraphicsPolygonItem initialIncrement;
  11803. QGraphicsPolygonItem finalDecrement;
  11804. QGraphicsPolygonItem finalIncrement;
  11805. QGraphicsPolygonItem initialIndicator;
  11806. QGraphicsPolygonItem finalIndicator;
  11807. QGraphicsPathItem scaleLine;
  11808. QPolygonF left;
  11809. QPolygonF right;
  11810. QPolygonF down;
  11811. QPolygonF up;
  11812. QPainterPath scalePath;
  11813. QBrush initialBrush;
  11814. QBrush finalBrush;
  11815. double nonScoredValue;
  11816. double scoredValue;
  11817. bool initialSet;
  11818. bool finalSet;
  11819. bool scaleDown;
  11820. @ The constructor sets up the scene displayed by this widget. There is
  11821. considerable room for improvement here.
  11822. @<ScaleControl implementation@>=
  11823. ScaleControl::ScaleControl() : QGraphicsView(NULL, NULL), nonScoredValue(-1),
  11824. scoredValue(-1), initialSet(false), finalSet(false), scaleDown(false)
  11825. {
  11826. left << QPointF(0, 5) << QPointF(10, 0) << QPointF(10, 10) <<
  11827. QPointF(0, 5);
  11828. right << QPointF(10, 5) << QPointF(0, 0) << QPointF(0, 10) <<
  11829. QPointF(10, 5);
  11830. down << QPointF(0, 0) << QPointF(-5, -10) << QPointF(5, -10) <<
  11831. QPointF(0, 0);
  11832. up << QPointF(0, 0) << QPointF(-5, 10) << QPointF(4, 10) << QPointF(0, 0);
  11833. initialBrush.setColor(QColor(170, 170, 255));
  11834. initialBrush.setStyle(Qt::SolidPattern);
  11835. finalBrush.setColor(Qt::blue);
  11836. finalBrush.setStyle(Qt::SolidPattern);
  11837. initialDecrement.setPolygon(left);
  11838. initialDecrement.setBrush(initialBrush);
  11839. initialDecrement.setPos(0, 0);
  11840. scene.addItem(&initialDecrement);
  11841. initialIncrement.setPolygon(right);
  11842. initialIncrement.setBrush(initialBrush);
  11843. initialIncrement.setPos(122, 0);
  11844. scene.addItem(&initialIncrement);
  11845. finalDecrement.setPolygon(left);
  11846. finalDecrement.setBrush(finalBrush);
  11847. finalDecrement.setPos(0, 12);
  11848. scene.addItem(&finalDecrement);
  11849. finalIncrement.setPolygon(right);
  11850. finalIncrement.setBrush(finalBrush);
  11851. finalIncrement.setPos(122, 12);
  11852. scene.addItem(&finalIncrement);
  11853. scalePath.moveTo(0, 10);
  11854. scalePath.lineTo(100, 10);
  11855. scalePath.moveTo(0, 0);
  11856. scalePath.lineTo(0, 20);
  11857. scalePath.moveTo(10, 5);
  11858. scalePath.lineTo(10, 15);
  11859. scalePath.moveTo(20, 5);
  11860. scalePath.lineTo(20, 15);
  11861. scalePath.moveTo(30, 5);
  11862. scalePath.lineTo(30, 15);
  11863. scalePath.moveTo(40, 5);
  11864. scalePath.lineTo(40, 15);
  11865. scalePath.moveTo(50, 0);
  11866. scalePath.lineTo(50, 20);
  11867. scalePath.moveTo(60, 5);
  11868. scalePath.lineTo(60, 15);
  11869. scalePath.moveTo(70, 5);
  11870. scalePath.lineTo(70, 15);
  11871. scalePath.moveTo(80, 5);
  11872. scalePath.lineTo(80, 15);
  11873. scalePath.moveTo(90, 5);
  11874. scalePath.lineTo(90, 15);
  11875. scalePath.moveTo(100, 0);
  11876. scalePath.lineTo(100, 20);
  11877. scaleLine.setPath(scalePath);
  11878. scaleLine.setPos(16, 1);
  11879. scene.addItem(&scaleLine);
  11880. setScene(&scene);
  11881. initialIndicator.setPolygon(down);
  11882. initialIndicator.setBrush(initialBrush);
  11883. finalIndicator.setPolygon(up);
  11884. finalIndicator.setBrush(finalBrush);
  11885. setMinimumSize(sizeHint());
  11886. setMaximumSize(sizeHint());
  11887. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  11888. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  11889. setMinimumSize(sizeHint());
  11890. }
  11891. @ The size hint forces a smaller representation of the widget, making it easier
  11892. to arrange with other widgets.
  11893. @<ScaleControl implementation@>=
  11894. QSize ScaleControl::sizeHint() const
  11895. {
  11896. return QSize(140, 30);
  11897. }
  11898. @ The methods for setting the values represented on the scale must ensure that
  11899. the appropriate indicator is drawn and position it appropriately.
  11900. @<ScaleControl implementation@>=
  11901. void ScaleControl::setInitialValue(double value)@t\2\2@>@/
  11902. {@t\1@>@/
  11903. if(value >= 0 && value <= 10)@/
  11904. {@t\1@>@/
  11905. nonScoredValue = value;
  11906. if(!initialSet)
  11907. {
  11908. scene.addItem(&initialIndicator);
  11909. }
  11910. initialSet = true;
  11911. initialIndicator.setPos(value * 10 + 16, 10);
  11912. emit initialChanged(value);
  11913. if(!finalSet)
  11914. {
  11915. setFinalValue(value);
  11916. }@t\2@>@/
  11917. }@t\2@>@/
  11918. }@/@/
  11919. void ScaleControl::setFinalValue(double value)@t\2\2@>@/
  11920. {@t\1@>@/
  11921. if(value >= 0 && value <= 10)@/
  11922. {@t\1@>@/
  11923. scoredValue = value;
  11924. if(!finalSet)@/
  11925. {
  11926. scene.addItem(&finalIndicator);
  11927. }
  11928. finalSet = true;
  11929. finalIndicator.setPos(value * 10 + 16, 11);
  11930. emit finalChanged(value);@t\2@>@/
  11931. }@t\2@>@/
  11932. }
  11933. @ These values can, of course, be retrieved programmatically.
  11934. @<ScaleControl implementation@>=
  11935. double ScaleControl::initialValue(void)
  11936. {
  11937. return nonScoredValue;
  11938. }
  11939. double ScaleControl::finalValue(void)
  11940. {
  11941. return scoredValue;
  11942. }
  11943. @ This only leaves the matter of handling interaction with the widget. A future
  11944. version of this class might split the various interface elements in the scene
  11945. into distinct classes capable of using the event propagation capabilities
  11946. provided by the graphics view framework, however with the current design, we
  11947. must do a little more work.
  11948. There are two events which must be accepted in order to register a click on a
  11949. given portion of the scale. One event is generated when the mouse button is
  11950. pressed.
  11951. @<ScaleControl implementation@>=
  11952. void ScaleControl::mousePressEvent(QMouseEvent *event)@t\2\2@>@/
  11953. {@t\1@>@/
  11954. @<Check that the left button was pressed@>@;
  11955. scaleDown = true;
  11956. event->accept();@t\2@>@/
  11957. }
  11958. @ The primary action button on the mouse is the left button. While there might
  11959. be sensible interactions to provide in response to other buttons, these are not
  11960. presently supported.
  11961. @<Check that the left button was pressed@>=
  11962. if(event->button() != Qt::LeftButton)
  11963. {
  11964. event->ignore();
  11965. return;
  11966. }
  11967. @ Most of the click event handling is done in response to releasing the mouse
  11968. button. In this event handler we must determine if the click occurred in a
  11969. clickable portion of the scale and take the appropriate action in response.
  11970. @<ScaleControl implementation@>=
  11971. void ScaleControl::mouseReleaseEvent(QMouseEvent *event)@t\2\2@>@/
  11972. {@t\1@>@/
  11973. @<Check that the left button was pressed@>@;
  11974. if(!scaleDown)
  11975. {
  11976. event->ignore();
  11977. return;
  11978. }
  11979. scaleDown = false;
  11980. QPointF sceneCoordinate = mapToScene(event->x(), event->y());
  11981. @<Handle clicks in the decrement controls@>@;
  11982. @<Handle clicks in the increment controls@>@;
  11983. @<Handle clicks in the scale area@>@;
  11984. event->ignore();
  11985. return;@t\2@>@/
  11986. }
  11987. @ As currently implemented, each horizontal pixel position represents a value
  11988. evenly divisible by $0.1$. It is, however, quite common to see vaues with a
  11989. $.25$ or $.75$ after the whole number on cupping forms. In order to make it
  11990. possible to select such values without vastly increasing the length of the
  11991. scale, the increment and decrement controls adjust the represented value by
  11992. $0.05$.
  11993. @<Handle clicks in the decrement controls@>=
  11994. if(sceneCoordinate.x() >= 0 && sceneCoordinate.x() <= 10)
  11995. {
  11996. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  11997. {
  11998. if(initialSet)
  11999. {
  12000. setInitialValue(nonScoredValue - 0.05);
  12001. }
  12002. event->accept();
  12003. return;
  12004. }
  12005. else if(sceneCoordinate.y() >= 12 && sceneCoordinate.y() <= 22)
  12006. {
  12007. if(finalSet)
  12008. {
  12009. setFinalValue(scoredValue - 0.05);
  12010. event->accept();
  12011. return;
  12012. }
  12013. }
  12014. }
  12015. @ Incrementing represented values is done in the same manner as decrementing
  12016. them.
  12017. @<Handle clicks in the increment controls@>=
  12018. else if(sceneCoordinate.x() >= 122 && sceneCoordinate.x() <= 132)
  12019. {
  12020. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  12021. {
  12022. if(initialSet)
  12023. {
  12024. setInitialValue(nonScoredValue + 0.05);
  12025. event->accept();
  12026. return;
  12027. }
  12028. }
  12029. else if(sceneCoordinate.y() >= 12 && sceneCoordinate.y() <= 22)
  12030. {
  12031. if(finalSet)
  12032. {
  12033. setFinalValue(scoredValue + 0.05);
  12034. event->accept();
  12035. return;
  12036. }
  12037. }
  12038. }
  12039. @ When handling clicks in the scale area, there is a difference between the
  12040. first click and any subsequent click.
  12041. @<Handle clicks in the scale area@>=
  12042. double relativeX = sceneCoordinate.x() - 16;
  12043. if(initialSet)
  12044. {
  12045. if(relativeX >= 0 && relativeX <= 100)
  12046. {
  12047. setFinalValue(relativeX / 10.0);
  12048. event->accept();
  12049. return;
  12050. }
  12051. }
  12052. else
  12053. {
  12054. if(relativeX >= 0 && relativeX <= 100)
  12055. {
  12056. setInitialValue(relativeX / 10.0);
  12057. event->accept();
  12058. return;
  12059. }
  12060. }
  12061. @* The Vertical Scale.
  12062. \noindent In addition to the horizontal scale, there is also a vertical scale.
  12063. The implementation of this class is in some ways a bit simpler as only one value
  12064. must be retained. While there is no prohibition on using this scale for scored
  12065. values (and this might enable a rather compact representation which might be
  12066. useful in some applications), its intent is for unscored values which are less
  12067. likely to change over time. If the dry aroma of a coffee changes significantly
  12068. during a cupping session, you are most likely waiting far too long to pour the
  12069. water.
  12070. @<Class declarations@>=
  12071. class IntensityControl : public QGraphicsView
  12072. {
  12073. Q_OBJECT
  12074. Q_PROPERTY(double value READ value WRITE setValue)
  12075. QGraphicsScene scene;
  12076. QGraphicsPolygonItem decrement;
  12077. QGraphicsPolygonItem increment;
  12078. QGraphicsPolygonItem indicator;
  12079. QGraphicsPathItem scaleLine;
  12080. QPolygonF left;
  12081. QPolygonF up;
  12082. QPolygonF down;
  12083. QPainterPath scalePath;
  12084. QBrush theBrush;
  12085. double theValue;
  12086. bool valueSet;
  12087. bool scaleDown;
  12088. public:
  12089. IntensityControl();
  12090. double value();
  12091. virtual QSize sizeHint() const;
  12092. public slots:
  12093. void setValue(double val);
  12094. signals:
  12095. void valueChanged(double);
  12096. protected:
  12097. virtual void mousePressEvent(QMouseEvent *event);
  12098. virtual void mouseReleaseEvent(QMouseEvent *event);
  12099. };
  12100. @ Note the similarity between this constructor and the the |ScaleControl|
  12101. constructor.
  12102. @<IntensityControl implementation@>=
  12103. IntensityControl::IntensityControl() : QGraphicsView(NULL, NULL), theValue(-1),
  12104. valueSet(false), scaleDown(false)
  12105. {
  12106. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  12107. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  12108. left << QPointF(0, 0) << QPointF(10, -5) << QPointF(10, 5) << QPointF(0, 0);
  12109. down << QPointF(0, 0) << QPointF(10, 0) << QPointF(5, 10) << QPointF(0, 0);
  12110. up << QPointF(0, 10) << QPointF(10, 10) << QPointF(5, 0) << QPointF(0, 10);
  12111. theBrush.setColor(Qt::blue);
  12112. theBrush.setStyle(Qt::SolidPattern);
  12113. increment.setPolygon(up);
  12114. increment.setBrush(theBrush);
  12115. increment.setPos(0, 0);
  12116. scene.addItem(&increment);
  12117. decrement.setPolygon(down);
  12118. decrement.setBrush(theBrush);
  12119. decrement.setPos(0, 122);
  12120. scene.addItem(&decrement);
  12121. scalePath.moveTo(5, 0);
  12122. scalePath.lineTo(5, 100);
  12123. scalePath.moveTo(0, 0);
  12124. scalePath.lineTo(10, 0);
  12125. scalePath.moveTo(0, 10);
  12126. scalePath.lineTo(10, 10);
  12127. scalePath.moveTo(0, 20);
  12128. scalePath.lineTo(10, 20);
  12129. scalePath.moveTo(0, 30);
  12130. scalePath.lineTo(10, 30);
  12131. scalePath.moveTo(0, 40);
  12132. scalePath.lineTo(10, 40);
  12133. scalePath.moveTo(0, 50);
  12134. scalePath.lineTo(10, 50);
  12135. scalePath.moveTo(0, 60);
  12136. scalePath.lineTo(10, 60);
  12137. scalePath.moveTo(0, 70);
  12138. scalePath.lineTo(10, 70);
  12139. scalePath.moveTo(0, 80);
  12140. scalePath.lineTo(10, 80);
  12141. scalePath.moveTo(0, 90);
  12142. scalePath.lineTo(10, 90);
  12143. scalePath.moveTo(0, 100);
  12144. scalePath.lineTo(10, 100);
  12145. scaleLine.setPath(scalePath);
  12146. scaleLine.setPos(0, 16);
  12147. scene.addItem(&scaleLine);
  12148. setScene(&scene);
  12149. indicator.setPolygon(left);
  12150. indicator.setBrush(theBrush);
  12151. setMinimumSize(sizeHint());
  12152. setMaximumSize(sizeHint());
  12153. }
  12154. @ Once again, the size hint reduces the default size of the widget.
  12155. @<IntensityControl implementation@>=
  12156. QSize IntensityControl::sizeHint() const
  12157. {
  12158. return QSize(25, 160);
  12159. }
  12160. @ To support a more intuitive numerical representation, higher values should map
  12161. to higher positions on the scale. This is contrary to the coordinate system
  12162. provided by Qt, so the code setting the position of the indicator on the scale
  12163. must account for this.
  12164. During testing of this class, I found that it was impossible to select the
  12165. values 0 or 10 either through a click or with the increment or decrement
  12166. controls. Adding two additional execution branches corrects this issue.
  12167. @<IntensityControl implementation@>=
  12168. void IntensityControl::setValue(double val)
  12169. {
  12170. if(val >= 0 && val <= 10)
  12171. {
  12172. theValue = val;
  12173. if(!valueSet)
  12174. {
  12175. scene.addItem(&indicator);
  12176. }
  12177. valueSet = true;
  12178. indicator.setPos(6, (100 - (val * 10)) + 16);
  12179. emit(valueChanged(val));
  12180. }
  12181. else if(val < 1)
  12182. {
  12183. setValue(0);
  12184. }
  12185. else
  12186. {
  12187. setValue(10);
  12188. }
  12189. }
  12190. double IntensityControl::value()
  12191. {
  12192. return theValue;
  12193. }
  12194. @ Mouse event handling is similar as well. The mouse press event simply notes
  12195. that the button has been pressed.
  12196. @<IntensityControl implementation@>=
  12197. void IntensityControl::mousePressEvent(QMouseEvent *event)
  12198. {
  12199. @<Check that the left button was pressed@>@;
  12200. scaleDown = true;
  12201. event->accept();
  12202. }
  12203. @ Since there are fewer clickable areas there are fewer regions to check while
  12204. handling the mouse release event. Just as the |setValue()| method must
  12205. compensate for a mismatch between the scale and the underlying coordinate
  12206. system, so must click handling in the scale area take this into consideration
  12207. when determining which value the click intends.
  12208. @<IntensityControl implementation@>=
  12209. void IntensityControl::mouseReleaseEvent(QMouseEvent *event)
  12210. {
  12211. @<Check that the left button was pressed@>@;
  12212. if(!scaleDown)
  12213. {
  12214. event->ignore();
  12215. return;
  12216. }
  12217. scaleDown = false;
  12218. QPointF sceneCoordinate = mapToScene(event->x(), event->y());
  12219. if(sceneCoordinate.x() >= 0 && sceneCoordinate.x() <= 16)
  12220. {
  12221. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  12222. {
  12223. if(valueSet)
  12224. {
  12225. setValue(theValue + 0.05);
  12226. }
  12227. event->accept();
  12228. return;
  12229. }
  12230. else if(sceneCoordinate.y() >= 122 && sceneCoordinate.y() <= 132)
  12231. {
  12232. if(valueSet)
  12233. {
  12234. setValue(theValue - 0.05);
  12235. }
  12236. event->accept();
  12237. return;
  12238. }
  12239. else if(sceneCoordinate.y() >= 16 && sceneCoordinate.y() <= 116)
  12240. {
  12241. setValue(10 - ((sceneCoordinate.y() - 16) / 10.0));
  12242. event->accept();
  12243. return;
  12244. }
  12245. }
  12246. }
  12247. @* Scripting the Scale Widgets.
  12248. \noindent Scale widgets can be added through the configuration system with
  12249. {\tt <hscale>} and {\tt <vscale>} elements. These can be added to layouts.
  12250. @<Function prototypes for scripting@>=
  12251. void addScaleControlToLayout(QDomElement element,
  12252. QStack<QWidget *> *widgetStack,
  12253. QStack<QLayout *> *layoutStack);
  12254. void addIntensityControlToLayout(QDomElement element,
  12255. QStack<QWidget *> *widgetStack,
  12256. QStack<QLayout *> *layoutStack);
  12257. @ Adding these widgets is done in the same way as adding other widgets.
  12258. @<Functions for scripting@>=
  12259. void addScaleControlToLayout(QDomElement element, QStack<QWidget *> *,
  12260. QStack<QLayout *> *layoutStack)
  12261. {
  12262. ScaleControl *scale = new ScaleControl;
  12263. if(element.hasAttribute("id"))
  12264. {
  12265. scale->setObjectName(element.attribute("id"));
  12266. }
  12267. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  12268. layout->addWidget(scale);
  12269. }
  12270. void addIntensityControlToLayout(QDomElement element, QStack<QWidget *> *,
  12271. QStack<QLayout *> *layoutStack)
  12272. {
  12273. IntensityControl *scale = new IntensityControl;
  12274. if(element.hasAttribute("id"))
  12275. {
  12276. scale->setObjectName(element.attribute("id"));
  12277. }
  12278. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  12279. layout->addWidget(scale);
  12280. }
  12281. @** Device Configuration.
  12282. \noindent Starting in \pn{} 1.4, all supported measurement hardware is
  12283. available from the same build and it is possible to use multiple devices from
  12284. differernt vendors at the same time. In previous versions, there were very few
  12285. available hardware configurations and a small number of example configuration
  12286. documents covered the needs of most people using the software. As more hardware
  12287. is supported and more people with distinct needs start using \pn{}, that
  12288. approach becomes unsustainable and the need for in-program configuration
  12289. becomes increasingly pronounced.
  12290. Device configuration is coupled to configuration of the logging window and
  12291. it is possible to configure multiple different roasters with different hardware
  12292. and other customizations of the logging window specific to a particular
  12293. machine.
  12294. The core of this is the use of an XML document saved with |QSettings| under
  12295. the |"DeviceConfiguration"| key. Within the root {\tt <DeviceConfiguration>}
  12296. element there are two grouping elements: {\tt <devices>} and
  12297. {\tt <references>}. The terminology was developed at a time when it was
  12298. thought that hardware configuration and logging view configuration would be
  12299. decoupled from each other, however the benefits of combining these far
  12300. outweighed the minor loss of flexibility with this approach.
  12301. Within the {\tt <devices>} tag there are arbitrarily many {\tt <node>} tags
  12302. which themselves may contain {\tt <node>} tags nested to any depth. Each of
  12303. these has two attributes, a {\tt name} attribute which specifies the display
  12304. text used to represent that node and a {\tt reference} attribute with a
  12305. unique value. Typica will generate a UUID for each node to use as the unique
  12306. value but this is not strictly required. The {\tt name} attribute does not
  12307. need to be unique and will generally be supplied by the person using the
  12308. software. The top level {\tt node} elements represent a coffee roaster and
  12309. the sub-elements can represent hardware, annotation controls, and possibly
  12310. other configurable features.
  12311. Within the {\tt <references>} tag there are as many {\tt <reference>} tags as
  12312. there are {\tt <node>} tags. Each of these has an {\tt id} attribute which
  12313. matches the {\tt reference} attribute in a {\tt <node>} tag and a {\tt driver}
  12314. attribute which is used to determine which class should be used to interact
  12315. with these settings. In the case of device configuration, this allows a
  12316. determination of which class should be used to generate an editor for settings
  12317. related to that node. Within each {\tt <reference>} tag is an arbitrary number
  12318. of {\tt <attribute>} tags with {\tt name} and {\tt value} attributes. Code for
  12319. providing the settings widgets and device interfaces can use these for any
  12320. desired purpose, but it is common to have one {\tt <attribute>} tag per setting
  12321. appropriate for a given node and possibly more to identify the concept a
  12322. particular node represents.
  12323. The global |Application| object is extended to maintain a |QDomDocument|
  12324. representation of this XML document.
  12325. @<Application private data members@>=
  12326. QDomDocument deviceConfigurationDocument;
  12327. @ Two methods are also provided for interacting with this document. The
  12328. |deviceConfiguration()| method returns a pointer to the private data member,
  12329. loading the XML from |QSettings| if required and creating a new document with
  12330. no {\tt <node>} tags if the document does not exist in settings. The
  12331. |saveDeviceConfiguration()| method serializes the |QDomDocument| to settings.
  12332. @<Device configuration members@>=
  12333. QDomDocument deviceConfiguration();
  12334. @ The method for saving should be a slot so a model representing this data
  12335. can persist changes through the signals and slots mechanism rather than
  12336. requiring the calls to be explicitn.
  12337. @<Extended Application slots@>=
  12338. void saveDeviceConfiguration();
  12339. @ Serializing the current configuration is trivial.
  12340. @<Application Implementation@>=
  12341. void Application::saveDeviceConfiguration()
  12342. {
  12343. QSettings settings;
  12344. settings.setValue("DeviceConfiguration",
  12345. QVariant(deviceConfigurationDocument.toByteArray()));
  12346. }
  12347. @ Producing a pointer to a loaded configuration only slightly more complicated.
  12348. If the configuration has been previously loaded we just return the pointer.
  12349. Otherwise, we attempt to load the document.
  12350. @<Application Implementation@>=
  12351. QDomDocument Application::deviceConfiguration()
  12352. {
  12353. if(deviceConfigurationDocument.isNull())
  12354. {
  12355. @<Load device configuration document from settings@>@;
  12356. }
  12357. return deviceConfigurationDocument;
  12358. }
  12359. @ In most cases a document will already exist in settings, but we must verify
  12360. this and create a new document if it does not exist. We also clear device
  12361. configuration settings if the configuration document is invalid.
  12362. @<Load device configuration document from settings@>=
  12363. QSettings settings;
  12364. QByteArray document = settings.value("DeviceConfiguration").toByteArray();
  12365. QString etext;
  12366. int eline;
  12367. int ecol;
  12368. if(document.length() == 0)
  12369. {
  12370. qDebug() << "Loaded settings length is 0. Creating new configuration.";
  12371. @<Create device configuration document@>@;
  12372. }
  12373. else
  12374. {
  12375. if(!deviceConfigurationDocument.setContent(document, false,
  12376. &etext, &eline, &ecol))
  12377. {
  12378. @<Report configuration loading error@>@;
  12379. @<Create device configuration document@>@;
  12380. }
  12381. }
  12382. @ Rather than generate the empty device configuration programmatically, we keep
  12383. an empty device configuration document as a resource.
  12384. @<Create device configuration document@>=
  12385. QFile emptyDocument(":/resources/xml/EmptyDeviceConfiguration.xml");
  12386. emptyDocument.open(QIODevice::ReadOnly);
  12387. if(!deviceConfigurationDocument.setContent(&emptyDocument, false,
  12388. &etext, &eline, &ecol))
  12389. {
  12390. @<Report configuration loading error@>@;
  12391. }
  12392. else
  12393. {
  12394. saveDeviceConfiguration();
  12395. }
  12396. @ There isn't really anything that can be done if the device configuration data
  12397. is corrupt, but an error message can be produced if the program happens to have
  12398. access to a debugging console.
  12399. @<Report configuration loading error@>=
  12400. qDebug() << QString(tr("An error occurred loading device configuration."));
  12401. qDebug() << QString(tr("Line %1, Column %2")).arg(eline).arg(ecol);
  12402. qDebug() << etext;
  12403. @* Model and view for device configuration hierarchy.
  12404. \noindent When manipulating device configuration data, it can be useful to
  12405. present the device hierarchy in a tree view. To do this, we use two classes to
  12406. produce a tree model. This is slightly extended and modified from an example
  12407. in the Qt documentation.\nfnote{Simple DOM Model Example:\par\indent\pdfURL{%
  12408. http://doc.qt.nokia.com/4.7-snapshot/itemviews-simpledommodel.html}
  12409. {http://doc.qt.nokia.com/4.7-snapshot/itemviews-simpledommodel.html}}
  12410. Our model uses the |DeviceTreeModelNode| class to cache the |QDomNode|
  12411. instances with the data we want.
  12412. @<Class declarations@>=
  12413. class DeviceTreeModelNode
  12414. {
  12415. public:
  12416. DeviceTreeModelNode(QDomNode &node, int row,
  12417. DeviceTreeModelNode *parent = NULL);
  12418. ~DeviceTreeModelNode();
  12419. DeviceTreeModelNode *child(int index);
  12420. DeviceTreeModelNode *parent();
  12421. QDomNode node() const;
  12422. int row();
  12423. private:
  12424. QDomNode domNode;
  12425. QHash<int, DeviceTreeModelNode*> children;
  12426. int rowNumber;
  12427. DeviceTreeModelNode *parentItem;
  12428. };
  12429. @ Implementation of this helper class is trivial.
  12430. @<DeviceTreeModelNode implementation@>=
  12431. DeviceTreeModelNode::DeviceTreeModelNode(QDomNode &node, int row,
  12432. DeviceTreeModelNode *parent)
  12433. : domNode(node), rowNumber(row), parentItem(parent)
  12434. {
  12435. /* Nothing needs to be done here. */
  12436. }
  12437. DeviceTreeModelNode::~DeviceTreeModelNode()
  12438. {
  12439. QHash<int, DeviceTreeModelNode *>::iterator@, i;
  12440. for(i = children.begin(); i != children.end(); i++)
  12441. {
  12442. delete i.value();
  12443. }
  12444. }
  12445. DeviceTreeModelNode *DeviceTreeModelNode::parent()
  12446. {
  12447. return parentItem;
  12448. }
  12449. int DeviceTreeModelNode::row()
  12450. {
  12451. return rowNumber;
  12452. }
  12453. QDomNode DeviceTreeModelNode::node() const
  12454. {
  12455. return domNode;
  12456. }
  12457. DeviceTreeModelNode *DeviceTreeModelNode::child(int index)
  12458. {
  12459. if(children.contains(index))
  12460. {
  12461. return children[index];
  12462. }
  12463. if(index >= 0 && index < domNode.childNodes().count())
  12464. {
  12465. QDomNode childNode = domNode.childNodes().item(index);
  12466. DeviceTreeModelNode *childItem = new DeviceTreeModelNode(childNode,
  12467. index, this);
  12468. children[index] = childItem;
  12469. return childItem;
  12470. }
  12471. return NULL;
  12472. }
  12473. @ The model class provides a single column representation of the {\tt devices}
  12474. section of the device configuration document. It provides methods for editing
  12475. the name of any node, for adding new nodes to the model, for deleting any node
  12476. in the model, and for obtaining the {\tt reference} element corresponding to
  12477. a given node.
  12478. @<Class declarations@>=
  12479. class DeviceTreeModel : public QAbstractItemModel@/
  12480. {@/
  12481. @[Q_OBJECT@]@;
  12482. public:@/
  12483. DeviceTreeModel(QObject *parent = NULL);
  12484. ~DeviceTreeModel();
  12485. QVariant data(const QModelIndex &index, int role) const;
  12486. Qt::ItemFlags flags(const QModelIndex &index) const;
  12487. QVariant headerData(int section, Qt::Orientation orientation,
  12488. int role = Qt::DisplayRole) const;
  12489. QModelIndex index(int row, int column,
  12490. const QModelIndex &parent = QModelIndex()) const;
  12491. QModelIndex parent(const QModelIndex &child) const;
  12492. int rowCount(const QModelIndex &parent = QModelIndex()) const;
  12493. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  12494. bool setData(const QModelIndex &index, const QVariant &value,
  12495. int role);
  12496. bool removeRows(int row, int count, const QModelIndex &parent);
  12497. QDomElement referenceElement(const QString &id);
  12498. @[public slots@]:@/
  12499. void newNode(const QString &name, const QString &driver,
  12500. const QModelIndex &parent);
  12501. private:@/
  12502. QDomDocument document;
  12503. DeviceTreeModelNode *root;
  12504. QDomNode referenceSection;
  12505. QDomNode treeRoot;
  12506. };
  12507. @ In the constructor we locate the {\tt devices} and {\tt references} sections
  12508. of the passed in document. Our tree of cached |QDomNode| elements starts with
  12509. the former and is expanded as needed.
  12510. @<DeviceTreeModel implementation@>=
  12511. DeviceTreeModel::DeviceTreeModel(QObject *parent)
  12512. : QAbstractItemModel(parent)
  12513. {
  12514. document = AppInstance->deviceConfiguration();
  12515. QDomNodeList elements = document.elementsByTagName("devices");
  12516. if(elements.size() != 1)
  12517. {
  12518. qDebug() << "Unexpected result when loading device map.";
  12519. }
  12520. treeRoot = elements.at(0);
  12521. root = new DeviceTreeModelNode(treeRoot, 0);
  12522. elements = document.elementsByTagName("references");
  12523. if(elements.size() != 1)
  12524. {
  12525. qDebug() << "No references section. Creating.";
  12526. referenceSection = document.createElement("references");
  12527. document.appendChild(referenceSection);
  12528. }
  12529. else
  12530. {
  12531. referenceSection = elements.at(0);
  12532. }
  12533. connect(this, SIGNAL(dataChanged(QModelIndex, QModelIndex)),
  12534. AppInstance, SLOT(saveDeviceConfiguration()));
  12535. connect(this, SIGNAL(modelReset()),
  12536. AppInstance, SLOT(saveDeviceConfiguration()));
  12537. connect(this, SIGNAL(rowsInserted(QModelIndex, int, int)),
  12538. AppInstance, SLOT(saveDeviceConfiguration()));
  12539. }
  12540. @ We only provide a single column for our model, so |columnCount()| can simply
  12541. return a constant. The |rowCount()| method can return a variety of values
  12542. depending on the parent node.
  12543. @<DeviceTreeModel implementation@>=
  12544. int DeviceTreeModel::columnCount(const QModelIndex &) const
  12545. {
  12546. return 1;
  12547. }
  12548. int DeviceTreeModel::rowCount(const QModelIndex &parent) const
  12549. {
  12550. if(parent.column() > 0)
  12551. {
  12552. return 0;
  12553. }
  12554. @<Get parent item from index@>@;
  12555. return parentItem->node().childNodes().count();
  12556. }
  12557. @ If an invalid index is passed as the parent index, we assume the parent to
  12558. be the root element.
  12559. @<Get parent item from index@>=
  12560. DeviceTreeModelNode *parentItem;
  12561. if(!parent.isValid())
  12562. {
  12563. parentItem = root;
  12564. }
  12565. else
  12566. {
  12567. parentItem = static_cast<DeviceTreeModelNode *>(parent.internalPointer());
  12568. }
  12569. @ As seen in |rowCount()|, we keep a pointer to the cached node in our model
  12570. indices.
  12571. @<DeviceTreeModel implementation@>=
  12572. QModelIndex DeviceTreeModel::index(int row, int column,
  12573. const QModelIndex &parent) const
  12574. {
  12575. if(!hasIndex(row, column, parent))
  12576. {
  12577. return QModelIndex();
  12578. }
  12579. @<Get parent item from index@>@;
  12580. DeviceTreeModelNode *childItem = parentItem->child(row);
  12581. if(childItem)
  12582. {
  12583. return createIndex(row, column, childItem);
  12584. }
  12585. return QModelIndex();
  12586. }
  12587. @ We can also request an index for the parent of a given index.
  12588. @<DeviceTreeModel implementation@>=
  12589. QModelIndex DeviceTreeModel::parent(const QModelIndex &child) const
  12590. {
  12591. if(!child.isValid())
  12592. {
  12593. return QModelIndex();
  12594. }
  12595. DeviceTreeModelNode *childItem =
  12596. static_cast<DeviceTreeModelNode *>(child.internalPointer());
  12597. DeviceTreeModelNode *parentItem = childItem->parent();
  12598. if(!parentItem || parentItem == root)
  12599. {
  12600. return QModelIndex();
  12601. }
  12602. return createIndex(parentItem->row(), 0, parentItem);
  12603. }
  12604. @ All items should be enabled, selectable, and editable.
  12605. @<DeviceTreeModel implementation@>=
  12606. Qt::ItemFlags DeviceTreeModel::flags(const QModelIndex &index) const
  12607. {
  12608. if(!index.isValid())
  12609. {
  12610. return 0;
  12611. }
  12612. return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
  12613. }
  12614. @ Each node in the model maintains two pieces of information. One is the
  12615. display value for the node which is held in the {\tt name} attribute of the
  12616. corresponding XML element. The other is a reference ID held in the
  12617. {\tt reference} attribute.
  12618. @<DeviceTreeModel implementation@>=
  12619. QVariant DeviceTreeModel::data(const QModelIndex &index, int role) const
  12620. {
  12621. if(!index.isValid())
  12622. {
  12623. return QVariant();
  12624. }
  12625. if(role != Qt::DisplayRole && role != Qt::UserRole && role != Qt::EditRole)
  12626. {
  12627. return QVariant();
  12628. }
  12629. DeviceTreeModelNode *item =
  12630. static_cast<DeviceTreeModelNode *>(index.internalPointer());
  12631. QDomNode node = item->node();
  12632. QDomElement element = node.toElement();
  12633. switch(role)
  12634. {
  12635. case Qt::DisplayRole:@/
  12636. case Qt::EditRole:@/
  12637. return QVariant(element.attribute("name"));
  12638. case Qt::UserRole:@/
  12639. return QVariant(element.attribute("reference"));
  12640. default:@/
  12641. return QVariant();
  12642. }
  12643. return QVariant();
  12644. }
  12645. @ The reference value is managed by the model and should never be changed. The
  12646. display value for a node is, however, editable. These changes must propagate
  12647. back to the XML document underlying the model.
  12648. @<DeviceTreeModel implementation@>=
  12649. bool DeviceTreeModel::setData(const QModelIndex &index,
  12650. const QVariant &value, int)@;@/
  12651. {@t\1@>@/
  12652. if(!index.isValid())@/
  12653. {@t\1@>@/
  12654. return false;@t\2@>@/
  12655. }@/
  12656. DeviceTreeModelNode *item =
  12657. static_cast<DeviceTreeModelNode *>(index.internalPointer());
  12658. QDomNode node = item->node();
  12659. QDomElement element = node.toElement();
  12660. element.setAttribute("name", value.toString());
  12661. emit dataChanged(index, index);@;
  12662. return true;@t\2@>@/
  12663. }
  12664. @ A custom method is provided for adding new nodes to the model. This generates
  12665. the two XML elements needed for the node. The |name| parameter is the display
  12666. name of the new node, the |driver| parameter is used as the value for the
  12667. {\tt driver} attribute in the {\tt reference} element which will be used to
  12668. determine what classes are used to work with that data.
  12669. @<DeviceTreeModel implementation@>=
  12670. void DeviceTreeModel::newNode(const QString &name, const QString &driver,
  12671. const QModelIndex &parent)
  12672. {
  12673. QString referenceID = QUuid::createUuid().toString();
  12674. @<Get parent item from index@>@;
  12675. QDomNode parentNode = parentItem->node();
  12676. int newRowNumber = rowCount(parent);
  12677. beginInsertRows(parent, newRowNumber, newRowNumber);
  12678. QDomElement deviceElement = document.createElement("node");
  12679. deviceElement.setAttribute("name", name);
  12680. deviceElement.setAttribute("reference", referenceID);
  12681. parentNode.appendChild(deviceElement);
  12682. QDomElement referenceElement = document.createElement("reference");
  12683. referenceElement.setAttribute("id", referenceID);
  12684. referenceElement.setAttribute("driver", driver);
  12685. referenceSection.appendChild(referenceElement);
  12686. endInsertRows();
  12687. }
  12688. @ We can also delete nodes. When deleting a node, both XML elements are
  12689. removed and our node cache is invalidated.
  12690. @<DeviceTreeModel implementation@>=
  12691. bool DeviceTreeModel::removeRows(int row, int count, const QModelIndex &parent)@t\2\2@>@/
  12692. {@t\1@>@/
  12693. @<Get parent item from index@>@;
  12694. QDomNode parentNode = parentItem->node();
  12695. QDomNodeList childNodes = parentNode.childNodes();@;
  12696. if(childNodes.size() < row + count)@/
  12697. {@t\1@>@/
  12698. return false;@t\2@>@/
  12699. }@/
  12700. beginRemoveRows(parent, row, row + count - 1);
  12701. QList<QDomElement> removalList;
  12702. for(int i = row; i < row + count; i++)
  12703. {
  12704. removalList.append(childNodes.at(i).toElement());
  12705. }
  12706. QDomElement element;
  12707. QDomElement reference;
  12708. for(int i = 0; i < count; i++)
  12709. {
  12710. element = removalList.at(i);
  12711. if(element.hasAttribute("reference"))
  12712. {
  12713. reference = referenceElement(element.attribute("reference"));
  12714. if(!reference.isNull())
  12715. {
  12716. referenceSection.removeChild(reference);
  12717. }
  12718. }
  12719. parentNode.removeChild(element);
  12720. }
  12721. endRemoveRows();
  12722. beginResetModel();
  12723. delete root;
  12724. root = new DeviceTreeModelNode(treeRoot, 0);
  12725. endResetModel();@;
  12726. return true;@t\2@>@/
  12727. }
  12728. @ Another custom method obtains the {\tt reference} element for a given
  12729. reference ID.
  12730. @<DeviceTreeModel implementation@>=
  12731. QDomElement DeviceTreeModel::referenceElement(const QString &id)
  12732. {
  12733. QDomNodeList childNodes = referenceSection.childNodes();
  12734. QDomElement element;
  12735. for(int i = 0; i < childNodes.size(); i++)
  12736. {
  12737. element = childNodes.at(i).toElement();
  12738. if(element.hasAttribute("id"))
  12739. {
  12740. if(element.attribute("id") == id)
  12741. {
  12742. return element;
  12743. }
  12744. }
  12745. }
  12746. return QDomElement();
  12747. }
  12748. @ We don't want any headers, so |headerData()| is very simple.
  12749. @<DeviceTreeModel implementation@>=
  12750. QVariant DeviceTreeModel::headerData(int, Qt::Orientation, int) const
  12751. {
  12752. return QVariant();
  12753. }
  12754. @ The destructor destroys the node cache. The destructor for the top level node
  12755. will recursively destroy all child nodes.
  12756. @<DeviceTreeModel implementation@>=
  12757. DeviceTreeModel::~DeviceTreeModel()
  12758. {
  12759. delete root;
  12760. }
  12761. @ Exposing this class to the host environment allows a number of interesting
  12762. possibilities. Setting the model to a combo box, for example, allows the
  12763. selection of top level nodes representing a particular coffee roaster. It is
  12764. also useful to have the ability to traverse a specified sub-tree of the model
  12765. to set up a logging view that matches the configuration for such a selected
  12766. roaster.
  12767. @<Function prototypes for scripting@>=
  12768. QScriptValue constructDeviceTreeModel(QScriptContext *context,
  12769. QScriptEngine *engine);
  12770. void setDeviceTreeModelProperties(QScriptValue value, QScriptEngine *engine);
  12771. void setQAbstractItemModelProperties(QScriptValue value, QScriptEngine *engine);
  12772. QScriptValue DeviceTreeModel_referenceElement(QScriptContext *context,
  12773. QScriptEngine *engine);
  12774. QScriptValue QAbstractItemModel_data(QScriptContext *context, QScriptEngine *engine);
  12775. QScriptValue QAbstractItemModel_index(QScriptContext *context, QScriptEngine *engine);
  12776. QScriptValue QAbstractItemModel_rowCount(QScriptContext *context, QScriptEngine *engine);
  12777. QScriptValue QAbstractItemModel_hasChildren(QScriptContext *context, QScriptEngine *engine);
  12778. @ The constructor is trivial.
  12779. @<Functions for scripting@>=
  12780. QScriptValue constructDeviceTreeModel(QScriptContext *, QScriptEngine *engine)
  12781. {
  12782. QScriptValue object = engine->newQObject(new DeviceTreeModel);
  12783. setDeviceTreeModelProperties(object, engine);
  12784. return object;
  12785. }
  12786. @ As usual the host environment is informed of this constructor.
  12787. @<Set up the scripting engine@>=
  12788. constructor = engine->newFunction(constructDeviceTreeModel);
  12789. value = engine->newQMetaObject(&DeviceTreeModel::staticMetaObject,
  12790. constructor);
  12791. engine->globalObject().setProperty("DeviceTreeModel", value);
  12792. @ A number of properties are set to allow script code to traverse the model.
  12793. Most of these properties are properly members of |QAbstractItemModel| and
  12794. the code is written to allow any models that may be exposed to the host
  12795. environment in the future to make use of these as well. Note that this is not
  12796. a full set of functionality but only what I needed to implement a particular
  12797. feature set.
  12798. @<Functions for scripting@>=
  12799. void setDeviceTreeModelProperties(QScriptValue value, QScriptEngine *engine)
  12800. {
  12801. setQAbstractItemModelProperties(value, engine);
  12802. value.setProperty("referenceElement",
  12803. engine->newFunction(DeviceTreeModel_referenceElement));
  12804. }
  12805. void setQAbstractItemModelProperties(QScriptValue value, QScriptEngine *engine)
  12806. {
  12807. setQObjectProperties(value, engine);
  12808. value.setProperty("data", engine->newFunction(QAbstractItemModel_data));
  12809. value.setProperty("index", engine->newFunction(QAbstractItemModel_index));
  12810. value.setProperty("rowCount", engine->newFunction(QAbstractItemModel_rowCount));
  12811. value.setProperty("hasChildren", engine->newFunction(QAbstractItemModel_hasChildren));
  12812. }
  12813. @ The wrapped call to |referenceElement| does a little more than might be
  12814. expected. Rather than returning a |QDomElement| and leaving it up to script
  12815. code to traverse the sub-tree, we create a |QVariantMap| which in script code
  12816. is translated as an object with the keys as properties of the object containing
  12817. the values of those keys. This is populated by first specifying a {\tt driver}
  12818. key with its value from the {\tt driver} attribute of the {\tt reference} node.
  12819. We then examine the {\tt <attribute>} sub-elements and use the {\tt name}
  12820. attribute as keys and the {\tt value} attribute as values to fill out the rest
  12821. of the map.
  12822. @<Functions for scripting@>=
  12823. QScriptValue DeviceTreeModel_referenceElement(QScriptContext *context,
  12824. QScriptEngine *engine)
  12825. {
  12826. DeviceTreeModel *model = getself<DeviceTreeModel *>(context);
  12827. QDomElement referenceElement = model->referenceElement(argument<QString>(0, context));
  12828. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  12829. QDomElement node;
  12830. QVariantMap retval;
  12831. retval.insert("driver", referenceElement.attribute("driver"));
  12832. for(int i = 0; i < configData.size(); i++)
  12833. {
  12834. node = configData.at(i).toElement();
  12835. retval.insert(node.attribute("name"), node.attribute("value"));
  12836. }
  12837. return engine->toScriptValue(retval);
  12838. }
  12839. QScriptValue QAbstractItemModel_data(QScriptContext *context, QScriptEngine *engine)
  12840. {
  12841. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  12842. QModelIndex index = argument<QModelIndex>(0, context);
  12843. int role = argument<int>(1, context);
  12844. return engine->toScriptValue(model->data(index, role));
  12845. }
  12846. QScriptValue QAbstractItemModel_index(QScriptContext *context, QScriptEngine *engine)
  12847. {
  12848. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  12849. int row = 0;
  12850. int column = 0;
  12851. QModelIndex index;
  12852. if(context->argumentCount() > 1)
  12853. {
  12854. row = argument<int>(0, context);
  12855. column = argument<int>(1, context);
  12856. }
  12857. if(context->argumentCount() > 2)
  12858. {
  12859. index = argument<QModelIndex>(2, context);
  12860. }
  12861. QModelIndex retval = model->index(row, column, index);
  12862. return engine->toScriptValue(retval);
  12863. }
  12864. QScriptValue QAbstractItemModel_rowCount(QScriptContext *context,
  12865. QScriptEngine *)
  12866. {
  12867. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  12868. QModelIndex index;
  12869. if(context->argumentCount() == 1)
  12870. {
  12871. index = argument<QModelIndex>(0, context);
  12872. }
  12873. return QScriptValue(model->rowCount(index));
  12874. }
  12875. QScriptValue QAbstractItemModel_hasChildren(QScriptContext *context,
  12876. QScriptEngine *engine)
  12877. {
  12878. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  12879. QModelIndex index;
  12880. if(context->argumentCount() == 1)
  12881. {
  12882. index = argument<QModelIndex>(0, context);
  12883. }
  12884. return QScriptValue(engine, model->hasChildren(index));
  12885. }
  12886. @ Some additional work is needed to handle |QModelIndex| appropriately. First
  12887. we declare |QModelIndex| as a metatype.
  12888. @<Class declarations@>=
  12889. Q_DECLARE_METATYPE(QModelIndex)
  12890. @ Next we need a pair of functions to convert |QModelIndex| to and from script
  12891. values.
  12892. @<Function prototypes for scripting@>=
  12893. QScriptValue QModelIndex_toScriptValue(QScriptEngine *engine, const QModelIndex &index);
  12894. void QModelIndex_fromScriptValue(const QScriptValue &value, QModelIndex &index);
  12895. @ These are implemented thusly.
  12896. @<Functions for scripting@>=
  12897. QScriptValue QModelIndex_toScriptValue(QScriptEngine *engine, const QModelIndex &index)
  12898. {
  12899. QVariant var;
  12900. var.setValue(index);
  12901. QScriptValue object = engine->newVariant(var);
  12902. return object;
  12903. }
  12904. void QModelIndex_fromScriptValue(const QScriptValue &value, QModelIndex &index)
  12905. {
  12906. index = value.toVariant().value<QModelIndex>();
  12907. }
  12908. @ Finally we register this with the engine.
  12909. @<Set up the scripting engine@>=
  12910. qScriptRegisterMetaType(engine, QModelIndex_toScriptValue, QModelIndex_fromScriptValue);
  12911. @* Device Configuration Widgets.
  12912. \noindent Each node in the {\tt devices} section of the |DeviceTreeModel| is
  12913. associated with a {\tt reference} element that provides a driver string which
  12914. can be used to identify the classes used to interact with the device
  12915. configuration data. An example of this is selecting which widget to use when
  12916. selecting a node in a configuration window. These widgets must be registered
  12917. to the appropriate driver string in advance. This is currently handled through
  12918. the |Application| instance, though it would probably be better to split this
  12919. into its own class at some point in the future.
  12920. @<Application private data members@>=
  12921. QHash<QString, QMetaObject> deviceConfigurationWidgets;
  12922. @ Two methods register widgets and retrieve an instance of the appropriate
  12923. widget for a given node in the device configuration model.
  12924. @<Device configuration members@>=
  12925. void registerDeviceConfigurationWidget(QString driver, QMetaObject widget);
  12926. QWidget* deviceConfigurationWidget(DeviceTreeModel *model,
  12927. const QModelIndex &index);
  12928. @ Registration is a simple wrapper around the underlying |QHash|.
  12929. @<Application Implementation@>=
  12930. void Application::registerDeviceConfigurationWidget(QString driver,
  12931. QMetaObject widget)
  12932. {
  12933. deviceConfigurationWidgets.insert(driver, widget);
  12934. }
  12935. @ Obtaining the configuration widget for a given node involves looking up the
  12936. reference element, extracting the driver string, looking up the associated
  12937. meta-object, and returning a new instance of that object.
  12938. As there is no concept of an invalid |QMetaObject| we default to the static
  12939. meta-object for a |QWidget| if a widget for the specified driver string is not
  12940. registered and check for this prior to creating a new instance of the
  12941. configuration widget.
  12942. @<Application Implementation@>=
  12943. QWidget* Application::deviceConfigurationWidget(DeviceTreeModel *model,
  12944. const QModelIndex &index)
  12945. {
  12946. QVariant nodeReference = index.data(Qt::UserRole);
  12947. QDomElement referenceElement = model->referenceElement(
  12948. model->data(index, Qt::UserRole).toString());
  12949. QMetaObject metaObject =
  12950. deviceConfigurationWidgets.value(referenceElement.attribute("driver"),
  12951. QWidget::staticMetaObject);
  12952. QWidget *editor;
  12953. if(metaObject.className() == QWidget::staticMetaObject.className())
  12954. {
  12955. editor = NULL;
  12956. }
  12957. else
  12958. {
  12959. editor = qobject_cast<QWidget *>(
  12960. metaObject.newInstance(Q_ARG(DeviceTreeModel *, model),
  12961. Q_ARG(QModelIndex, index)));
  12962. }
  12963. return editor;
  12964. }
  12965. @ Every node type should have an associated editor and the editors for nodes
  12966. which can have child nodes should be able to handle creating these child nodes.
  12967. This leaves the problem of creating the top level nodes. For this we must have
  12968. a way to register three key pieces of information: the text which should appear
  12969. for selecting a new top level node to add to the configuration, the default
  12970. name for a node of that type, and the registered driver string associated with
  12971. that node type. The most likely use for this information is in constructing a
  12972. menu. |QAction| seems like a good fit, but this cannot pass all of the
  12973. required information. Part of the chosen solution is a |QAction| subclass
  12974. which takes all three pieces of information and provides a new signal to
  12975. supply the information needed to add a new top level node.
  12976. @<Class declarations@>=
  12977. class NodeInserter : public QAction@/
  12978. {@/
  12979. @[Q_OBJECT@]@;
  12980. public:@/
  12981. NodeInserter(const QString &title, const QString &name,
  12982. const QString &driver, QObject *parent = NULL);
  12983. signals:@/
  12984. void triggered(QString name, QString driver);
  12985. @[private slots@]:@/
  12986. void onTriggered();
  12987. private:@/
  12988. QString defaultNodeName;
  12989. QString driverString;
  12990. };
  12991. @ The constructor saves the information that will later be emitted and connects
  12992. the |triggered()| signal from |QAction| to a private slot which emits our new
  12993. |triggered()| signal.
  12994. @<NodeInserter implementation@>=
  12995. NodeInserter::NodeInserter(const QString &title, const QString &name,
  12996. const QString &driver, QObject *parent) :
  12997. QAction(title, parent), defaultNodeName(name), driverString(driver)
  12998. {
  12999. connect(this, SIGNAL(triggered()), this, SLOT(onTriggered()));
  13000. }
  13001. void NodeInserter::onTriggered()
  13002. {
  13003. emit triggered(defaultNodeName, driverString);
  13004. }
  13005. @ An interface for adding top level nodes to the device configuration needs to
  13006. be able to access a list of these actions so we make this available through the
  13007. |Application| instance. Once again, it would be better to split device
  13008. configuration registration data to a separate class and there should be
  13009. accessors around this.
  13010. Note that this terminology was introduced when it was assumed that device
  13011. configuration and logging view configuration would be separate. It is likely
  13012. that a future code cleanup will remove this in favor of handling the top level
  13013. of the device configuration hierarchy (under roaster specification) in the same
  13014. way that sub-nodes are handled.
  13015. @<Device configuration members@>=
  13016. QList<NodeInserter *> topLevelNodeInserters;
  13017. @ With this done, we can now produce a window which allows someone to easily
  13018. edit the device configuration.
  13019. @<Class declarations@>=
  13020. class DeviceConfigurationWindow : public QMainWindow
  13021. {
  13022. @[Q_OBJECT@]@;
  13023. public:@/
  13024. DeviceConfigurationWindow();
  13025. @[public slots@]:@/
  13026. void addDevice();
  13027. void removeNode();
  13028. void newSelection(const QModelIndex &index);
  13029. @[private slots@]:@/
  13030. void resizeColumn();
  13031. private:@/
  13032. QDomDocument document;
  13033. DeviceTreeModel *model;
  13034. QTreeView *view;
  13035. QScrollArea *configArea;
  13036. };
  13037. @ This window consists of two main panels separated by a splitter. The left
  13038. panel presents a tree view of the current device configuration and a set of
  13039. controls that allows someone to either add a new top level node to the
  13040. configuration or delete any node in the configuration along with all of its
  13041. child nodes.
  13042. The right panel provides a |QScrollArea|. When a node is selected from the tree
  13043. view, the appropriate configuration widget will be inserted into that area.
  13044. When a configuration widget adds a new node to the device model, the parent
  13045. node (which should be the currently selected node but the code does not assume
  13046. this) is expanded to show the new child node if it has not already been
  13047. expanded.
  13048. @<DeviceConfigurationWindow implementation@>=
  13049. DeviceConfigurationWindow::DeviceConfigurationWindow() : QMainWindow(NULL),
  13050. view(new QTreeView), configArea(new QScrollArea)
  13051. {
  13052. QSplitter *splitter = new QSplitter;
  13053. QWidget *leftWidget = new QWidget;
  13054. leftWidget->setMinimumWidth(200);
  13055. QVBoxLayout *left = new QVBoxLayout;
  13056. view->setAnimated(true);
  13057. view->setSelectionMode(QAbstractItemView::SingleSelection);
  13058. document = AppInstance->deviceConfiguration();
  13059. model = new DeviceTreeModel;
  13060. view->setModel(model);
  13061. view->setTextElideMode(Qt::ElideNone);
  13062. view->expandAll();
  13063. view->resizeColumnToContents(0);
  13064. connect(model, SIGNAL(modelReset()), view, SLOT(expandAll()));
  13065. QHBoxLayout *treeButtons = new QHBoxLayout;
  13066. QToolButton *addDeviceButton = new QToolButton;
  13067. addDeviceButton->setIcon(QIcon::fromTheme("list-add"));
  13068. addDeviceButton->setToolTip(tr("New Roaster"));
  13069. connect(addDeviceButton, SIGNAL(clicked()),
  13070. this, SLOT(addDevice()));
  13071. QToolButton *removeNodeButton = new QToolButton;
  13072. removeNodeButton->setIcon(QIcon::fromTheme("list-remove"));
  13073. removeNodeButton->setToolTip(tr("Delete Selection"));
  13074. connect(removeNodeButton, SIGNAL(clicked()), this, SLOT(removeNode()));
  13075. treeButtons->addWidget(addDeviceButton);
  13076. treeButtons->addWidget(removeNodeButton);
  13077. left->addWidget(view);
  13078. left->addLayout(treeButtons);
  13079. leftWidget->setLayout(left);
  13080. splitter->addWidget(leftWidget);
  13081. configArea->setMinimumWidth(580);
  13082. configArea->setMinimumHeight(460);
  13083. splitter->addWidget(configArea);
  13084. setCentralWidget(splitter);
  13085. connect(view, SIGNAL(activated(QModelIndex)),
  13086. this, SLOT(newSelection(QModelIndex)));
  13087. connect(view, SIGNAL(clicked(QModelIndex)),
  13088. this, SLOT(newSelection(QModelIndex)));
  13089. connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)),
  13090. view, SLOT(expand(QModelIndex)));
  13091. connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)),
  13092. this, SLOT(resizeColumn()));
  13093. connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int)),
  13094. this, SLOT(resizeColumn()));
  13095. }
  13096. @ Adding a new top level node to the model is just a matter of extracting the
  13097. required information from the signal requesting that addition.
  13098. @<DeviceConfigurationWindow implementation@>=
  13099. void DeviceConfigurationWindow::addDevice()
  13100. {
  13101. model->newNode(tr("New Roaster"), "roaster", QModelIndex());
  13102. }
  13103. @ Removing the currently selected node is also simple.
  13104. @<DeviceConfigurationWindow implementation@>=
  13105. void DeviceConfigurationWindow::removeNode()
  13106. {
  13107. QModelIndex index = view->currentIndex();
  13108. if(index.isValid())
  13109. {
  13110. int row = index.row();
  13111. QModelIndex parent = index.parent();
  13112. model->removeRow(row, parent);
  13113. }
  13114. }
  13115. @ Due to most of the required logic being implemented in
  13116. |Application::deviceConfigurationWidget()|, inserting the proper editor in the
  13117. right area is also trivial.
  13118. @<DeviceConfigurationWindow implementation@>=
  13119. void DeviceConfigurationWindow::newSelection(const QModelIndex &index)
  13120. {
  13121. QWidget *editor = AppInstance->deviceConfigurationWidget(model, index);
  13122. if(editor)
  13123. {
  13124. configArea->setWidget(editor);
  13125. editor->show();
  13126. }
  13127. }
  13128. @ As nodes are added deeper in the device hierarchy or as nodes obtain longer
  13129. names, the nodes names may be elided by default rather than indicate that the
  13130. view can be scrolled horizontally. There has been feedback that this behavior
  13131. is not preferred so instead as the model data changes we expand the column
  13132. instead.
  13133. @<DeviceConfigurationWindow implementation@>=
  13134. void DeviceConfigurationWindow::resizeColumn()
  13135. {
  13136. view->resizeColumnToContents(0);
  13137. }
  13138. @ At least for the initial testing of this feature it will be useful if we can
  13139. instantiate this from the host environment. For this we at least require a
  13140. constructor.
  13141. @<Function prototypes for scripting@>=
  13142. QScriptValue constructDeviceConfigurationWindow(QScriptContext *context,
  13143. QScriptEngine *engine);
  13144. @ The constructor is trivial.
  13145. @<Functions for scripting@>=
  13146. QScriptValue constructDeviceConfigurationWindow(QScriptContext *,
  13147. QScriptEngine *engine)
  13148. {
  13149. QScriptValue object = engine->newQObject(new DeviceConfigurationWindow);
  13150. return object;
  13151. }
  13152. @ Finally we inform the host environment of this constructor.
  13153. @<Set up the scripting engine@>=
  13154. constructor = engine->newFunction(constructDeviceConfigurationWindow);
  13155. value = engine->newQMetaObject(&DeviceConfigurationWindow::staticMetaObject,
  13156. constructor);
  13157. engine->globalObject().setProperty("DeviceConfigurationWindow", value);
  13158. @* A Common Base Class for Device Configuration Widgets.
  13159. \noindent There are certain operations that are very commonly required
  13160. among device configuration widgets. These common elements have been implemented
  13161. in a base class.
  13162. @<Class declarations@>=
  13163. class BasicDeviceConfigurationWidget : public QWidget
  13164. {
  13165. @[Q_OBJECT@]@;
  13166. public:@/
  13167. BasicDeviceConfigurationWidget(DeviceTreeModel *model,
  13168. const QModelIndex &index);
  13169. @[public slots@]:@/
  13170. void insertChildNode(const QString &name, const QString &driver);
  13171. void updateAttribute(const QString &name, const QString &value);
  13172. protected:@/
  13173. DeviceTreeModel *deviceModel;
  13174. QModelIndex currentNode;
  13175. };
  13176. @ The constructor just passes its arguments to a pair of protected data
  13177. members. These are commonly required in subclasses but need not be exposed
  13178. outside of this branch of the object hierarchy.
  13179. @<BasicDeviceConfigurationWidget implementation@>=
  13180. BasicDeviceConfigurationWidget::BasicDeviceConfigurationWidget(
  13181. DeviceTreeModel *model, const QModelIndex &index)
  13182. : QWidget(NULL), deviceModel(model), currentNode(index)
  13183. {
  13184. /* Nothing needs to be done here. */
  13185. }
  13186. @ The |updateAttribute()| method sets the value property of an attribute
  13187. element of a given name that is a child of the current node, creating the
  13188. element if it does not exist.
  13189. @<BasicDeviceConfigurationWidget implementation@>=
  13190. void BasicDeviceConfigurationWidget::updateAttribute(const QString &name,
  13191. const QString &value)
  13192. {
  13193. QDomElement referenceElement = deviceModel->referenceElement(
  13194. deviceModel->data(currentNode, Qt::UserRole).toString());
  13195. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  13196. QDomElement node;
  13197. bool found = false;
  13198. for(int i = 0; i < configData.size(); i++)
  13199. {
  13200. node = configData.at(i).toElement();
  13201. if(node.attribute("name") == name)
  13202. {
  13203. node.setAttribute("value", value);
  13204. found = true;
  13205. break;
  13206. }
  13207. }
  13208. if(!found)
  13209. {
  13210. node = AppInstance->deviceConfiguration().createElement("attribute");
  13211. node.setAttribute("name", name);
  13212. node.setAttribute("value", value);
  13213. referenceElement.appendChild(node);
  13214. }
  13215. AppInstance->saveDeviceConfiguration();
  13216. }
  13217. @ The |insertChildNode()| method constructs a new node with the specified name
  13218. and driver as a child of the current node. Node insertion is a generic
  13219. operation that does not require any knowledge of the configuration options that
  13220. will be presented in that node.
  13221. @<BasicDeviceConfigurationWidget implementation@>=
  13222. void BasicDeviceConfigurationWidget::insertChildNode(const QString &name,
  13223. const QString &driver)
  13224. {
  13225. deviceModel->newNode(name, driver, currentNode);
  13226. }
  13227. @** Configuration of Top Level Roaster Nodes.
  13228. \noindent The first configuration widget required is one for defining a coffee
  13229. roaster. This stores the identification number that will be used for machine
  13230. references in the database and also provides controls for adding all of the
  13231. required child nodes for hardware and configurable elements of the logging
  13232. window that may vary from one machine to the next.
  13233. All of the configuration widgets follow a similar pattern. One important detail
  13234. to note is that these configuration widgets are instantiated through Qt's
  13235. meta-object system. All of these constructors take a |DeviceTreeModel *| and a
  13236. |QModelIndex &| as arguments and they are marked as |Q_INVOKABLE|.
  13237. @<Class declarations@>=
  13238. class RoasterConfWidget : public BasicDeviceConfigurationWidget
  13239. {
  13240. @[Q_OBJECT@]@;
  13241. public:@/
  13242. @[Q_INVOKABLE@]@, RoasterConfWidget(DeviceTreeModel *model,
  13243. const QModelIndex &index);
  13244. @[private slots@]:@/
  13245. void updateRoasterId(int id);
  13246. };
  13247. @ Aside from the ID number used to identify the roaster in the database we also
  13248. need controls to add child nodes. In order to limit the number of options in
  13249. menus for adding child nodes, these are organized into groups that are
  13250. available through different controls.
  13251. @<RoasterConfWidget implementation@>=
  13252. RoasterConfWidget::RoasterConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  13253. : BasicDeviceConfigurationWidget(model, index)
  13254. {
  13255. QVBoxLayout *layout = new QVBoxLayout;
  13256. QPushButton *addDeviceButton = new QPushButton(tr("Add Device"));
  13257. QMenu *deviceMenu = new QMenu;
  13258. NodeInserter *insertAction;
  13259. foreach(insertAction, AppInstance->topLevelNodeInserters)
  13260. {
  13261. connect(insertAction, SIGNAL(triggered(QString, QString)),
  13262. this, SLOT(insertChildNode(QString, QString)));
  13263. deviceMenu->addAction(insertAction);
  13264. }
  13265. addDeviceButton->setMenu(deviceMenu);
  13266. layout->addWidget(addDeviceButton);
  13267. QPushButton *addAnnotationControlButton = new QPushButton(tr("Add Annotation Control"));
  13268. QMenu *annotationMenu = new QMenu;
  13269. NodeInserter *basicButtonInserter = new NodeInserter(tr("Annotation Button"), tr("Annotation Button"), "annotationbutton");
  13270. NodeInserter *countingButtonInserter = new NodeInserter(tr("Counting Button"), tr("Counting Button"), "reconfigurablebutton");
  13271. NodeInserter *spinBoxInserter = new NodeInserter(tr("Numeric Entry"), tr("Numeric Entry"), "annotationspinbox");
  13272. NodeInserter *freeAnnotationInserter = new NodeInserter(tr("Free Text"),
  13273. tr("Free Text"),
  13274. "freeannotation");
  13275. annotationMenu->addAction(basicButtonInserter);
  13276. annotationMenu->addAction(countingButtonInserter);
  13277. annotationMenu->addAction(spinBoxInserter);
  13278. annotationMenu->addAction(freeAnnotationInserter);
  13279. connect(basicButtonInserter, SIGNAL(triggered(QString, QString)),
  13280. this, SLOT(insertChildNode(QString, QString)));
  13281. connect(countingButtonInserter, SIGNAL(triggered(QString, QString)),
  13282. this, SLOT(insertChildNode(QString, QString)));
  13283. connect(spinBoxInserter, SIGNAL(triggered(QString, QString)),
  13284. this, SLOT(insertChildNode(QString, QString)));
  13285. connect(freeAnnotationInserter, SIGNAL(triggered(QString, QString)),
  13286. this, SLOT(insertChildNode(QString, QString)));
  13287. addAnnotationControlButton->setMenu(annotationMenu);
  13288. layout->addWidget(addAnnotationControlButton);
  13289. QPushButton *advancedButton = new QPushButton(tr("Advanced Features"));
  13290. QMenu *advancedMenu = new QMenu;
  13291. NodeInserter *linearsplineinserter = new NodeInserter(tr("Linear Spline Interpolated Series"), tr("Linear Spline Interpolated Series"), "linearspline");
  13292. advancedMenu->addAction(linearsplineinserter);
  13293. NodeInserter *translationinserter = new NodeInserter(tr("Profile Translation"), tr("Profile Translation"), "translation");
  13294. advancedMenu->addAction(translationinserter);
  13295. connect(linearsplineinserter, SIGNAL(triggered(QString, QString)), this, SLOT(insertChildNode(QString, QString)));
  13296. connect(translationinserter, SIGNAL(triggered(QString, QString)), this, SLOT(insertChildNode(QString, QString)));
  13297. advancedButton->setMenu(advancedMenu);
  13298. layout->addWidget(advancedButton);
  13299. QHBoxLayout *idLayout = new QHBoxLayout;
  13300. QLabel *idLabel = new QLabel(tr("Machine ID for database:"));
  13301. idLayout->addWidget(idLabel);
  13302. QSpinBox *id = new QSpinBox;
  13303. idLayout->addWidget(id);
  13304. layout->addLayout(idLayout);
  13305. @<Get device configuration data for current node@>@;
  13306. for(int i = 0; i < configData.size(); i++)
  13307. {
  13308. node = configData.at(i).toElement();
  13309. if(node.attribute("name") == "databaseid")
  13310. {
  13311. id->setValue(node.attribute("value").toInt());
  13312. break;
  13313. }
  13314. }
  13315. updateRoasterId(id->value());
  13316. connect(id, SIGNAL(valueChanged(int)), this, SLOT(updateRoasterId(int)));
  13317. setLayout(layout);
  13318. }
  13319. @ Iterating over the configuration data associated with the current node is
  13320. required in nearly every configuration widget. The specifics of the loop
  13321. vary, but there is likely a better way to generalize that. Until then,
  13322. obtaining a |QDomNodeList| with the required data to iterate over has been
  13323. split off as its own chunk to reduce the risk of errors associated with typing
  13324. the same code many times.
  13325. @<Get device configuration data for current node@>=
  13326. QDomElement referenceElement =
  13327. model->referenceElement(model->data(index, Qt::UserRole).toString());
  13328. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  13329. QDomElement node;
  13330. @ We need to propagate changes to the ID number field to the device
  13331. configuration document. The |updateAttribute()| method in the base class
  13332. makes this trivial.
  13333. @<RoasterConfWidget implementation@>=
  13334. void RoasterConfWidget::updateRoasterId(int id)
  13335. {
  13336. updateAttribute("databaseid", QString("%1").arg(id));
  13337. }
  13338. @ Finally we must register the configuration widget so that it can be
  13339. instantiated at the appropriate time.
  13340. @<Register device configuration widgets@>=
  13341. app.registerDeviceConfigurationWidget("roaster", RoasterConfWidget::staticMetaObject);
  13342. @** Configuration for NI-DAQmx Base devices.
  13343. \noindent The primary concern in supporting hardware that communicates through
  13344. NI-DAQmx Base is in configurations using a single NI USB 9211 (for NI-DAQmx
  13345. Base 2.x) or NI USB 9211A (for NI-DAQmx Base 3.x), but if it is reasonable to
  13346. do so I'd like to later add support for multiple device configurations and
  13347. limited support for other devices including the ability to use devices with
  13348. voltage inputs for non-temperature measurement data. The top priority, however,
  13349. is in continuing to support hardware that people are already using with Typica.
  13350. In order to more easily implement these future plans, device configuration is
  13351. handled with three configuration tiers. The top level configuration node
  13352. indicates that we are using NI-DAQmx Base. Here we can add a child node
  13353. representing either a NI USB 9211 or NI USB 9211A. From a configuration
  13354. perspective these are identical with the default node name as the only
  13355. difference. From the device configuration we can specify the device identifier
  13356. and add channels to the device. In the channel nodes we specify the
  13357. thermocouple type.
  13358. @<Class declarations@>=
  13359. class NiDaqMxBaseDriverConfWidget : public BasicDeviceConfigurationWidget
  13360. {
  13361. @[Q_OBJECT@]@;
  13362. public:@/
  13363. @[Q_INVOKABLE@]@, NiDaqMxBaseDriverConfWidget(DeviceTreeModel *model,@|
  13364. const QModelIndex &index);
  13365. };
  13366. @ There is very little to configure here so there isn't much for the
  13367. constructor to do. We do need to keep a reference to the node we are
  13368. configuring so that child nodes can later be added. At present, no real
  13369. configuration data other than the existence of the node is required so
  13370. there is no need to read any configuration data here.
  13371. @<NiDaqMxBaseDriverConfWidget implementation@>=
  13372. NiDaqMxBaseDriverConfWidget::NiDaqMxBaseDriverConfWidget(
  13373. DeviceTreeModel *model, const QModelIndex &index) :
  13374. BasicDeviceConfigurationWidget(model, index)
  13375. {
  13376. QHBoxLayout *layout = new QHBoxLayout;
  13377. QToolButton *addDeviceButton = new QToolButton;
  13378. addDeviceButton->setText(tr("Add Device"));
  13379. NodeInserter *add9211 = new NodeInserter("NI USB 9211", "NI USB 9211",
  13380. "nidaqmxbase9211series");
  13381. NodeInserter *add9211a = new NodeInserter("NI USB 9211A", "NI USB 9211A",
  13382. "nidaqmxbase9211series");
  13383. connect(add9211, SIGNAL(triggered(QString, QString)),
  13384. this, SLOT(insertChildNode(QString, QString)));
  13385. connect(add9211a, SIGNAL(triggered(QString, QString)),
  13386. this, SLOT(insertChildNode(QString, QString)));
  13387. QMenu *deviceMenu = new QMenu;
  13388. deviceMenu->addAction(add9211);
  13389. deviceMenu->addAction(add9211a);
  13390. addDeviceButton->setMenu(deviceMenu);
  13391. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  13392. layout->addWidget(addDeviceButton);
  13393. setLayout(layout);
  13394. }
  13395. @ Both the NI USB 9211 and NI USB 9211A are identical from a configuration
  13396. perspective. The only difference is the version of NI-DAQmx Base required for
  13397. use. As the API does not provide a way of determining which version is
  13398. installed, ensuring that the appropriate software is installed without
  13399. conflicts is left as an exercise for the person attempting to use \pn{}.
  13400. @<Class declarations@>=
  13401. class NiDaqMxBase9211ConfWidget : public BasicDeviceConfigurationWidget
  13402. {
  13403. Q_OBJECT
  13404. public:
  13405. Q_INVOKABLE NiDaqMxBase9211ConfWidget(DeviceTreeModel *device,
  13406. const QModelIndex &index);
  13407. private slots:
  13408. void addChannel();
  13409. void updateDeviceId(const QString &newId);
  13410. };
  13411. @ There are two controls required in a configuration widget for this device.
  13412. The first is the device identifier (for example, "Dev1"), the second is a
  13413. button for adding channels to the device. On a generic device we would also
  13414. need to set the clock rate, but with this hardware it is possible to determine
  13415. the maximum clock rate from the channels defined.
  13416. @<NiDaqMxBase9211ConfWidget implementation@>=
  13417. NiDaqMxBase9211ConfWidget::NiDaqMxBase9211ConfWidget(DeviceTreeModel *model,
  13418. const QModelIndex &index)
  13419. : BasicDeviceConfigurationWidget(model, index)
  13420. {
  13421. QVBoxLayout *layout = new QVBoxLayout;
  13422. QHBoxLayout *deviceIdLayout = new QHBoxLayout;
  13423. QLabel *label = new QLabel(tr("Device ID:"));
  13424. QLineEdit *deviceId = new QLineEdit;
  13425. deviceIdLayout->addWidget(label);
  13426. deviceIdLayout->addWidget(deviceId);
  13427. QPushButton *addChannelButton = new QPushButton(tr("Add Channel"));
  13428. layout->addLayout(deviceIdLayout);
  13429. layout->addWidget(addChannelButton);
  13430. @<Get device configuration data for current node@>@;
  13431. for(int i = 0; i < configData.size(); i++)
  13432. {
  13433. node = configData.at(i).toElement();
  13434. if(node.attribute("name") == "deviceID")
  13435. {
  13436. deviceId->setText(node.attribute("value", "Dev1"));
  13437. break;
  13438. }
  13439. }
  13440. updateDeviceId(deviceId->text());
  13441. connect(addChannelButton, SIGNAL(clicked()),
  13442. this, SLOT(addChannel()));
  13443. connect(deviceId, SIGNAL(textEdited(QString)),
  13444. this, SLOT(updateDeviceId(QString)));
  13445. setLayout(layout);
  13446. }
  13447. @ Updating the attribute tag under the reference element associated with the
  13448. current node is handled in the base class so we just need to pass in the
  13449. appropriate name value pair.
  13450. @<NiDaqMxBase9211ConfWidget implementation@>=
  13451. void NiDaqMxBase9211ConfWidget::updateDeviceId(const QString &newId)
  13452. {
  13453. updateAttribute("deviceID", newId);
  13454. }
  13455. @ Adding channels is just like adding any other sort of node.
  13456. @<NiDaqMxBase9211ConfWidget implementation@>=
  13457. void NiDaqMxBase9211ConfWidget::addChannel()
  13458. {
  13459. insertChildNode(tr("Thermocouple channel"), "ni9211seriestc");
  13460. }
  13461. @ Finally, we need a configuration widget to handle our thermocouple channels.
  13462. Ordinarily we would need three pieces of information for each channel. First
  13463. there is the thermocouple channel. Previously this was left implied by the
  13464. order of requests for a new channel, but more flexible configuration options
  13465. become possible with a more explicit specification. Since this widget is device
  13466. specific, all of the options can be easily enumerated to match markings on the
  13467. device. Next is the thermocouple type. Many options are supported, but I would
  13468. like to ensure that the most commonly used choices are listed first. The other
  13469. piece of information that DAQmx or DAQmx Base require is the measurement unit.
  13470. As all of Typica's internal operations are in Fahrenheit there is no need to
  13471. make this configurable so long as everything else that can display temperature
  13472. measurements can perform the appropriate conversions.
  13473. Note that as there are no configuration differences between the various
  13474. device combinations using an NI 9211 module with regard to thermocouple channel
  13475. configuration, we can use this widget with all device combinations that make
  13476. use of such a module.
  13477. @<Class declarations@>=
  13478. class Ni9211TcConfWidget : public BasicDeviceConfigurationWidget
  13479. {
  13480. @[Q_OBJECT@]@/
  13481. public:@/
  13482. Q_INVOKABLE Ni9211TcConfWidget(DeviceTreeModel *device,
  13483. const QModelIndex &index);
  13484. @[private slots@]:@/
  13485. void updateThermocoupleType(const QString &type);
  13486. void updateColumnName(const QString &name);
  13487. };
  13488. @ This follows the same pattern of previous device configuration widgets. The
  13489. constructor provides the required configuration controls and slot methods
  13490. catch configuration changes and update the underlying XML document
  13491. appropriately.
  13492. @<Ni9211TcConfWidget implementation@>=
  13493. Ni9211TcConfWidget::Ni9211TcConfWidget(DeviceTreeModel *model,
  13494. const QModelIndex &index) :
  13495. BasicDeviceConfigurationWidget(model, index)
  13496. {
  13497. QFormLayout *layout = new QFormLayout;
  13498. QLineEdit *columnName = new QLineEdit;
  13499. layout->addRow(tr("Column Name:"), columnName);
  13500. QComboBox *typeSelector = new QComboBox;
  13501. typeSelector->addItem("J");
  13502. typeSelector->addItem("K");
  13503. typeSelector->addItem("T");
  13504. typeSelector->addItem("B");
  13505. typeSelector->addItem("E");
  13506. typeSelector->addItem("N");
  13507. typeSelector->addItem("R");
  13508. typeSelector->addItem("S");
  13509. layout->addRow(tr("Thermocouple Type:"), typeSelector);
  13510. setLayout(layout);
  13511. @<Get device configuration data for current node@>@;
  13512. for(int i = 0; i < configData.size(); i++)
  13513. {
  13514. node = configData.at(i).toElement();
  13515. if(node.attribute("name") == "type")
  13516. {
  13517. typeSelector->setCurrentIndex(
  13518. typeSelector->findText(node.attribute("value")));
  13519. }
  13520. else if(node.attribute("name") == "columnname")
  13521. {
  13522. columnName->setText(node.attribute("value"));
  13523. }
  13524. }
  13525. updateThermocoupleType(typeSelector->currentText());
  13526. updateColumnName(columnName->text());
  13527. connect(typeSelector, SIGNAL(currentIndexChanged(QString)),
  13528. this, SLOT(updateThermocoupleType(QString)));
  13529. connect(columnName, SIGNAL(textEdited(QString)), this, SLOT(updateColumnName(QString)));
  13530. }
  13531. @ Two slots are used to pass configuration changes back to the underlying XML
  13532. representation.
  13533. @<Ni9211TcConfWidget implementation@>=
  13534. void Ni9211TcConfWidget::updateThermocoupleType(const QString &type)
  13535. {
  13536. updateAttribute("type", type);
  13537. }
  13538. void Ni9211TcConfWidget::updateColumnName(const QString &name)
  13539. {
  13540. updateAttribute("columnname", name);
  13541. }
  13542. @ These three widgets need to be registered so the configuration widget can
  13543. instantiate them when the nodes are selected.
  13544. @<Register device configuration widgets@>=
  13545. app.registerDeviceConfigurationWidget("nidaqmxbase",
  13546. NiDaqMxBaseDriverConfWidget::staticMetaObject);
  13547. app.registerDeviceConfigurationWidget("nidaqmxbase9211series",
  13548. NiDaqMxBase9211ConfWidget::staticMetaObject);
  13549. app.registerDeviceConfigurationWidget("ni9211seriestc",
  13550. Ni9211TcConfWidget::staticMetaObject);
  13551. @ Furthermore, we should create the NodeInserter objects for adding top level
  13552. nodes to the configuration. Preferably we would only allow top level nodes to
  13553. be inserted when all prerequisite software is available.
  13554. @<Register top level device configuration nodes@>=
  13555. NodeInserter *inserter = new NodeInserter(tr("NI DAQmx Base Device"),
  13556. tr("NI DAQmx Base"),
  13557. "nidaqmxbase", NULL);
  13558. topLevelNodeInserters.append(inserter);
  13559. @** Configuration of NI-DAQmx devices.
  13560. \noindent The other main class of hardware currently supported in Typica is a
  13561. small set of devices that require NI-DAQmx. This includes a few combinations of
  13562. the NI 9211 in different carriers and the NI USB TC01. Additional hardware may
  13563. be added to this set in the future.
  13564. The approach here is very similar to the approach used to configure NI-DAQmx
  13565. Base devices, starting with a widget for adding child device nodes.
  13566. @<Class declarations@>=
  13567. class NiDaqMxDriverConfWidget : public BasicDeviceConfigurationWidget
  13568. {
  13569. @[Q_OBJECT@]@;
  13570. public:
  13571. @[Q_INVOKABLE@]@, NiDaqMxDriverConfWidget(DeviceTreeModel *model,
  13572. const QModelIndex &index);
  13573. };
  13574. @ Under our driver node we want to have the ability to insert device specific
  13575. child nodes.
  13576. @<NiDaqMxDriverConfWidget implementation@>=
  13577. NiDaqMxDriverConfWidget::NiDaqMxDriverConfWidget(DeviceTreeModel *model,
  13578. const QModelIndex &index)
  13579. : BasicDeviceConfigurationWidget(model, index)
  13580. {
  13581. QHBoxLayout *layout = new QHBoxLayout;
  13582. QToolButton *addDeviceButton = new QToolButton;
  13583. addDeviceButton->setText(tr("Add Device"));
  13584. NodeInserter *add9211a = new NodeInserter("NI USB 9211A", "NI USB 9211A",
  13585. "nidaqmx9211series");
  13586. NodeInserter *addtc01 = new NodeInserter("NI USB TC01", "NI USB TC01",
  13587. "nidaqmxtc01");
  13588. connect(add9211a, SIGNAL(triggered(QString, QString)),
  13589. this, SLOT(insertChildNode(QString, QString)));
  13590. connect(addtc01, SIGNAL(triggered(QString, QString)),
  13591. this, SLOT(insertChildNode(QString, QString)));
  13592. QMenu *deviceMenu = new QMenu;
  13593. deviceMenu->addAction(add9211a);
  13594. deviceMenu->addAction(addtc01);
  13595. addDeviceButton->setMenu(deviceMenu);
  13596. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  13597. layout->addWidget(addDeviceButton);
  13598. setLayout(layout);
  13599. }
  13600. @ Devices based on the 9211 module are essentially the same aside from device
  13601. naming convention. Configuring these is very similar to configuring similar
  13602. devices when using NI-DAQmx Base.
  13603. @<Class declarations@>=
  13604. class NiDaqMx9211ConfWidget : public BasicDeviceConfigurationWidget
  13605. {
  13606. @[Q_OBJECT@]@;
  13607. public:@/
  13608. @[Q_INVOKABLE@]@, NiDaqMx9211ConfWidget(DeviceTreeModel *model,
  13609. const QModelIndex &index);
  13610. @[private slots@]:@/
  13611. void addChannel();
  13612. void updateDeviceId(const QString &newId);
  13613. };
  13614. @ Implementation is essentially identical to the NI-DAQmx Base class. It is
  13615. likely that there will be differences if this is ever extended to support
  13616. automatic detection of connected hardware. While NI-DAQmx Base does not
  13617. provide a way to query device identifiers, it uses a consistent naming scheme
  13618. by which device identifiers can be discovered. While NI-DAQmx lacks the same
  13619. consistency in device identifiers, it does provide a way to query that
  13620. information.
  13621. @<NiDaqMx9211ConfWidget implementation@>=
  13622. NiDaqMx9211ConfWidget::NiDaqMx9211ConfWidget(DeviceTreeModel *model,
  13623. const QModelIndex &index)
  13624. : BasicDeviceConfigurationWidget(model, index)
  13625. {
  13626. QVBoxLayout *layout = new QVBoxLayout;
  13627. QHBoxLayout *deviceIdLayout = new QHBoxLayout;
  13628. QLabel *label = new QLabel(tr("Device ID:"));
  13629. QLineEdit *deviceId = new QLineEdit;
  13630. deviceIdLayout->addWidget(label);
  13631. deviceIdLayout->addWidget(deviceId);
  13632. QPushButton *addChannelButton = new QPushButton(tr("Add Channel"));
  13633. layout->addLayout(deviceIdLayout);
  13634. layout->addWidget(addChannelButton);
  13635. @<Get device configuration data for current node@>@;
  13636. for(int i = 0; i < configData.size(); i++)
  13637. {
  13638. node = configData.at(i).toElement();
  13639. if(node.attribute("name") == "deviceID")
  13640. {
  13641. deviceId->setText(node.attribute("value","Dev1"));
  13642. break;
  13643. }
  13644. }
  13645. updateDeviceId(deviceId->text());
  13646. connect(addChannelButton, SIGNAL(clicked()), this, SLOT(addChannel()));
  13647. connect(deviceId, SIGNAL(textEdited(QString)),
  13648. this, SLOT(updateDeviceId(QString)));
  13649. setLayout(layout);
  13650. }
  13651. void NiDaqMx9211ConfWidget::updateDeviceId(const QString &newId)
  13652. {
  13653. updateAttribute("deviceID", newId);
  13654. }
  13655. void NiDaqMx9211ConfWidget::addChannel()
  13656. {
  13657. insertChildNode(tr("Thermocouple channel"), "ni9211seriestc");
  13658. }
  13659. @ There is no need to create a configuration widget specific to the 9211 module
  13660. used in NI-DAQmx. The widget already used for NI-DAQmx Base can be used without
  13661. modification.
  13662. Configuring Typica for use with the NI USB-TC01 can be slightly simplified as
  13663. the device only has a single thermocouple channel. We can configure this without
  13664. requiring another node.
  13665. @<Class declarations@>=
  13666. class NiDaqMxTc01ConfWidget : public BasicDeviceConfigurationWidget
  13667. {
  13668. @[Q_OBJECT@]@;
  13669. public:@/
  13670. @[Q_INVOKABLE@]@, NiDaqMxTc01ConfWidget(DeviceTreeModel *model,
  13671. const QModelIndex &index);
  13672. @[private slots@]:@/
  13673. void updateDeviceId(const QString &newId);
  13674. void updateThermocoupleType(const QString &type);
  13675. void updateColumnName(const QString &name);
  13676. };
  13677. @ The implementation is similar to the other configuration widgets.
  13678. @<NiDaqMxTc01ConfWidget implementation@>=
  13679. NiDaqMxTc01ConfWidget::NiDaqMxTc01ConfWidget(DeviceTreeModel *model,
  13680. const QModelIndex &index)
  13681. : BasicDeviceConfigurationWidget(model, index)
  13682. {
  13683. QFormLayout *layout = new QFormLayout;
  13684. QLineEdit *deviceId = new QLineEdit;
  13685. layout->addRow(tr("Device ID:"), deviceId);
  13686. QLineEdit *columnName = new QLineEdit;
  13687. layout->addRow(tr("Column Name:"), columnName);
  13688. QComboBox *typeSelector = new QComboBox;
  13689. typeSelector->addItem("J");
  13690. typeSelector->addItem("K");
  13691. typeSelector->addItem("T");
  13692. typeSelector->addItem("B");
  13693. typeSelector->addItem("E");
  13694. typeSelector->addItem("N");
  13695. typeSelector->addItem("R");
  13696. typeSelector->addItem("S");
  13697. layout->addRow(tr("Thermocouple Type:"), typeSelector);
  13698. @<Get device configuration data for current node@>@;
  13699. for(int i = 0; i < configData.size(); i++)
  13700. {
  13701. node = configData.at(i).toElement();
  13702. if(node.attribute("name") == "deviceID")
  13703. {
  13704. deviceId->setText(node.attribute("value"));
  13705. }
  13706. else if(node.attribute("name") == "type")
  13707. {
  13708. typeSelector->setCurrentIndex(typeSelector->findText(node.attribute("value")));
  13709. }
  13710. else if(node.attribute("name") == "columnname")
  13711. {
  13712. columnName->setText(node.attribute("value"));
  13713. }
  13714. }
  13715. updateDeviceId(deviceId->text());
  13716. updateThermocoupleType(typeSelector->currentText());
  13717. updateColumnName(columnName->text());
  13718. connect(deviceId, SIGNAL(textEdited(QString)), this, SLOT(updateDeviceId(QString)));
  13719. connect(typeSelector, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateThermocoupleType(QString)));
  13720. connect(columnName, SIGNAL(textEdited(QString)), this, SLOT(updateColumnName(QString)));
  13721. setLayout(layout);
  13722. }
  13723. void NiDaqMxTc01ConfWidget::updateDeviceId(const QString &newId)
  13724. {
  13725. updateAttribute("deviceID", newId);
  13726. }
  13727. void NiDaqMxTc01ConfWidget::updateThermocoupleType(const QString &type)
  13728. {
  13729. updateAttribute("type", type);
  13730. }
  13731. void NiDaqMxTc01ConfWidget::updateColumnName(const QString &name)
  13732. {
  13733. updateAttribute("columnname", name);
  13734. }
  13735. @ These configuration widgets need to be registered so they can be instantiated
  13736. in response to node selections.
  13737. @<Register device configuration widgets@>=
  13738. app.registerDeviceConfigurationWidget("nidaqmx", NiDaqMxDriverConfWidget::staticMetaObject);
  13739. app.registerDeviceConfigurationWidget("nidaqmx9211series", NiDaqMx9211ConfWidget::staticMetaObject);
  13740. app.registerDeviceConfigurationWidget("nidaqmxtc01", NiDaqMxTc01ConfWidget::staticMetaObject);
  13741. @ A |NodeInserter| for the driver configuration widget is also needed. Note that
  13742. at present NI DAQmx is only available on Windows so we do not bother to show
  13743. the option on other platforms. It would be generally preferable to replace this
  13744. with a check at runtime to determine if the required library exists. That could
  13745. be done with anything that requires third party installed code, leaving by
  13746. default only those options which have no external dependencies.
  13747. @<Register top level device configuration nodes@>=
  13748. #ifdef Q_OS_WIN32
  13749. inserter = new NodeInserter(tr("NI DAQmx Device"), tr("NI DAQmx"), "nidaqmx", NULL);
  13750. topLevelNodeInserters.append(inserter);
  13751. #endif
  13752. @** Configuration of Serial Port Devices.
  13753. \noindent It is possible to communicate with a number of devices through a
  13754. serial port. To do this, the appropriate settings for opening the port are
  13755. required and the communications protocol understood by the device must be
  13756. known. Serial port communications are provided by QextSerialPort. That
  13757. project was released under the MIT license.\nfnote{See the license text for
  13758. more information.} Additional headers are required.
  13759. @<Header files to include@>=
  13760. #include "qextserialport.h"
  13761. #include "qextserialenumerator.h"
  13762. @ Some custom widgets are provided which allow selecting the relevant
  13763. connection options from combo boxes. First there is a widget for selecting
  13764. the desired serial port. The drop down is pre-populated with any serial ports
  13765. that could be automatically detected, but the field can also be edited to
  13766. other values as may be required if the hardware is not connected during
  13767. configuration.
  13768. @<Class declarations@>=
  13769. class PortSelector : public QComboBox
  13770. {
  13771. Q_OBJECT
  13772. public:
  13773. PortSelector(QWidget *parent = NULL);
  13774. private slots:
  13775. void addDevice(QextPortInfo port);
  13776. private:
  13777. QextSerialEnumerator *lister;
  13778. };
  13779. @ The implementation is trivial.
  13780. @<PortSelector implementation@>=
  13781. PortSelector::PortSelector(QWidget *parent) : QComboBox(parent),
  13782. lister(new QextSerialEnumerator)
  13783. {
  13784. QList<QextPortInfo> ports = QextSerialEnumerator::getPorts();
  13785. QextPortInfo port;
  13786. foreach(port, ports)
  13787. {
  13788. addItem(port.portName);
  13789. }
  13790. lister->setUpNotifications();
  13791. connect(lister, SIGNAL(deviceDiscovered(QextPortInfo)),
  13792. this, SLOT(addDevice(QextPortInfo)));
  13793. setEditable(true);
  13794. }
  13795. void PortSelector::addDevice(QextPortInfo port)
  13796. {
  13797. addItem(port.portName);
  13798. }
  13799. @ Next is a widget which allows selecting the baud rate. Only rates supported
  13800. by the current operating system are available to select.
  13801. A later version of QextSerialPort than is used by \pn{} provides a helper
  13802. class which can be used more conveniently to create this sort of control. As
  13803. this is not yet available to \pn{}, we instead copy the |enum| specifying
  13804. the appropriate values into the class and use Qt's meta-object system to
  13805. populate the combo box based on the values in that |enum|.
  13806. @<Class declarations@>=
  13807. class BaudSelector : public QComboBox
  13808. {
  13809. Q_OBJECT
  13810. Q_ENUMS(BaudRateType)
  13811. public:
  13812. BaudSelector(QWidget *parent = NULL);
  13813. enum BaudRateType
  13814. {
  13815. #if defined(Q_OS_UNIX) || defined(qdoc)
  13816. BAUD50 = 50, //POSIX ONLY
  13817. BAUD75 = 75, //POSIX ONLY
  13818. BAUD134 = 134, //POSIX ONLY
  13819. BAUD150 = 150, //POSIX ONLY
  13820. BAUD200 = 200, //POSIX ONLY
  13821. BAUD1800 = 1800, //POSIX ONLY
  13822. #if defined(B76800) || defined(qdoc)
  13823. BAUD76800 = 76800, //POSIX ONLY
  13824. #endif
  13825. #if (defined(B230400) && defined(B4000000)) || defined(qdoc)
  13826. BAUD230400 = 230400, //POSIX ONLY
  13827. BAUD460800 = 460800, //POSIX ONLY
  13828. BAUD500000 = 500000, //POSIX ONLY
  13829. BAUD576000 = 576000, //POSIX ONLY
  13830. BAUD921600 = 921600, //POSIX ONLY
  13831. BAUD1000000 = 1000000, //POSIX ONLY
  13832. BAUD1152000 = 1152000, //POSIX ONLY
  13833. BAUD1500000 = 1500000, //POSIX ONLY
  13834. BAUD2000000 = 2000000, //POSIX ONLY
  13835. BAUD2500000 = 2500000, //POSIX ONLY
  13836. BAUD3000000 = 3000000, //POSIX ONLY
  13837. BAUD3500000 = 3500000, //POSIX ONLY
  13838. BAUD4000000 = 4000000, //POSIX ONLY
  13839. #endif
  13840. #endif
  13841. #if defined(Q_OS_WIN) || defined(qdoc)
  13842. BAUD14400 = 14400, //WINDOWS ONLY
  13843. BAUD56000 = 56000, //WINDOWS ONLY
  13844. BAUD128000 = 128000, //WINDOWS ONLY
  13845. BAUD256000 = 256000, //WINDOWS ONLY
  13846. #endif
  13847. BAUD110 = 110,
  13848. BAUD300 = 300,
  13849. BAUD600 = 600,
  13850. BAUD1200 = 1200,
  13851. BAUD2400 = 2400,
  13852. BAUD4800 = 4800,
  13853. BAUD9600 = 9600,
  13854. BAUD19200 = 19200,
  13855. BAUD38400 = 38400,
  13856. BAUD57600 = 57600,
  13857. BAUD115200 = 115200
  13858. };
  13859. };
  13860. @ As the |enum| values are identical to the baud rates represented, we only
  13861. the numeric values, ignoring the names which are rather ugly.
  13862. @<BaudSelector implementation@>=
  13863. BaudSelector::BaudSelector(QWidget *parent) : QComboBox(parent)
  13864. {
  13865. QMetaObject meta = BaudSelector::staticMetaObject;
  13866. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("BaudRateType"));
  13867. for(int i = 0; i < type.keyCount(); i++)
  13868. {
  13869. addItem(QString("%1").arg(type.value(i)));
  13870. }
  13871. }
  13872. @ This same technique is used in a widget for selecting parity.
  13873. @<Class declarations@>=
  13874. class ParitySelector : public QComboBox
  13875. {
  13876. Q_OBJECT
  13877. Q_ENUMS(ParityType)
  13878. public:
  13879. ParitySelector(QWidget *parent = NULL);
  13880. enum ParityType
  13881. {
  13882. PAR_NONE,
  13883. PAR_ODD,
  13884. PAR_EVEN,
  13885. #if defined(Q_OS_WIN) || defined(qdoc)
  13886. PAR_MARK, //WINDOWS ONLY
  13887. #endif
  13888. PAR_SPACE
  13889. };
  13890. };
  13891. @ Implementation is similar to |BaudSelector| but as the values have no
  13892. apparent relation to what is represented we present the value names, placing
  13893. the corresponding value in the user data space associated with each entry.
  13894. The names here are ugly and not amenable to localization so this approach
  13895. should be reconsidered later.
  13896. @<ParitySelector implementation@>=
  13897. ParitySelector::ParitySelector(QWidget *parent) : QComboBox(parent)
  13898. {
  13899. QMetaObject meta = ParitySelector::staticMetaObject;
  13900. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("ParityType"));
  13901. for(int i = 0; i < type.keyCount(); i++)
  13902. {
  13903. addItem(QString(type.key(i)), QVariant(type.value(i)));
  13904. }
  13905. }
  13906. @ Similarly, we have a widget for selecting a method for flow control.
  13907. @<Class declarations@>=
  13908. class FlowSelector : public QComboBox
  13909. {
  13910. Q_OBJECT
  13911. Q_ENUMS(FlowType)
  13912. public:
  13913. FlowSelector(QWidget *parent = NULL);
  13914. enum FlowType
  13915. {
  13916. FLOW_OFF,
  13917. FLOW_HARDWARE,
  13918. FLOW_XONXOFF
  13919. };
  13920. };
  13921. @ Implementation follows the same pattern as in |ParitySelector|.
  13922. @<FlowSelector implementation@>=
  13923. FlowSelector::FlowSelector(QWidget *parent) : QComboBox(parent)
  13924. {
  13925. QMetaObject meta = FlowSelector::staticMetaObject;
  13926. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("FlowType"));
  13927. for(int i = 0; i < type.keyCount(); i++)
  13928. {
  13929. addItem(QString(type.key(i)), QVariant(type.value(i)));
  13930. }
  13931. }
  13932. @ We assume that the number of data bits will always be 8, though it may be
  13933. useful to later provide a control for selecting this for use with other devices
  13934. where this may not be assumed or for the sake of completion. This only leaves
  13935. specifying the number of stop bits.
  13936. @<Class declarations@>=
  13937. class StopSelector : public QComboBox
  13938. {
  13939. Q_OBJECT
  13940. Q_ENUMS(StopBitsType)
  13941. public:
  13942. StopSelector(QWidget *parent = NULL);
  13943. enum StopBitsType
  13944. {
  13945. STOP_1,
  13946. #if defined(Q_OS_WIN) || defined(qdoc)
  13947. STOP_1_5, //WINDOWS ONLY
  13948. #endif
  13949. STOP_2
  13950. };
  13951. };
  13952. @ Implementation should be familiar by now.
  13953. @<StopSelector implementation@>=
  13954. StopSelector::StopSelector(QWidget *parent) : QComboBox(parent)
  13955. {
  13956. QMetaObject meta = StopSelector::staticMetaObject;
  13957. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("StopBitsType"));
  13958. for(int i = 0; i < type.keyCount(); i++)
  13959. {
  13960. addItem(QString(type.key(i)), QVariant(type.value(i)));
  13961. }
  13962. }
  13963. @** Configuration of Serial Devices Using Modbus RTU.
  13964. \noindent One protocol that is used across a broad class of devices is called
  13965. Modbus RTU. This protocol allows multiple devices to be chained together on a
  13966. two wire bus which can be connected to a single serial port. The communication
  13967. protocol involves a single message which is sent from a master device (in this
  13968. case the computer running Typica) to a slave device (the device we would like
  13969. to obtain information from) which is followed by a response message from the
  13970. slave to the master. After a brief wait the master can then send another
  13971. message to any slave on the bus and this process repeats. Every outgoing
  13972. message provides a station address to identify which slave on the bus should
  13973. respond, a function code to identify which of a broad class of operations has
  13974. been requested, the required data for the function specified, and a cyclic
  13975. redundancy check to validate the message.
  13976. @** A Spin Box with Hexadecimal Representation.
  13977. \noindent Common convention for communications documentation for devices that
  13978. use Modbus RTU is that relative addresses are specified in hexadecimal
  13979. representation. In order to simplify initial device configuration, it would be
  13980. best that input widgets both accept input in base 16 and display values as a
  13981. four digit hexadecimal value.
  13982. @<Class declarations@>=
  13983. class ShortHexSpinBox : public QSpinBox
  13984. {
  13985. Q_OBJECT
  13986. public:
  13987. ShortHexSpinBox(QWidget *parent = NULL);
  13988. virtual QValidator::State validate(QString &input, int &pos) const;
  13989. protected:
  13990. virtual int valueFromText(const QString &text) const;
  13991. virtual QString textFromValue(int value) const;
  13992. };
  13993. @ For this we can set some new defaults in the constructor and must override
  13994. three methods.
  13995. @<ShortHexSpinBox implementation@>=
  13996. ShortHexSpinBox::ShortHexSpinBox(QWidget *parent) : QSpinBox(parent)
  13997. {
  13998. setMinimum(0);
  13999. setMaximum(0xFFFF);
  14000. setPrefix("0x");
  14001. setMinimumWidth(65);
  14002. }
  14003. QValidator::State ShortHexSpinBox::validate(QString &input, int &) const
  14004. {
  14005. if(input.size() == 2)
  14006. {
  14007. return QValidator::Intermediate;
  14008. }
  14009. bool okay;
  14010. input.toInt(&okay, 16);
  14011. if(okay)
  14012. {
  14013. return QValidator::Acceptable;
  14014. }
  14015. return QValidator::Invalid;
  14016. }
  14017. int ShortHexSpinBox::valueFromText(const QString &text) const
  14018. {
  14019. return text.toInt(NULL, 16);
  14020. }
  14021. QString ShortHexSpinBox::textFromValue(int value) const
  14022. {
  14023. QString retval;
  14024. retval.setNum(value, 16);
  14025. while(retval.size() < 4)
  14026. {
  14027. retval.prepend("0");
  14028. }
  14029. return retval.toUpper();
  14030. }
  14031. @** Configuration Widgets for Modbus RTU Devices.
  14032. \noindent While the top level configuration widgets seen so far have not had
  14033. any configuration details beyond the ability to add devices under the driver,
  14034. in the case of a serial port with Modbus RTU devices it is reasonable to
  14035. provide the connection details which will be shared by all devices on the bus.
  14036. @<Class declarations@>=
  14037. class ModbusRtuPortConfWidget : public BasicDeviceConfigurationWidget
  14038. {
  14039. @[Q_OBJECT@]@;
  14040. public:
  14041. @[Q_INVOKABLE@]@, ModbusRtuPortConfWidget(DeviceTreeModel *model,
  14042. const QModelIndex &index);
  14043. @[private slots@]:@/
  14044. void updatePort(const QString &newPort);
  14045. void updateBaudRate(const QString &newRate);
  14046. void updateParity(const QString &newParity);
  14047. void updateFlowControl(const QString &newFlow);
  14048. void updateStopBits(const QString &newStopBits);
  14049. };
  14050. @ Aside from the extra information compared with other configuration widgets
  14051. previously described, there is nothing surprising about the implementation.
  14052. @<ModbusRtuPortConfWidget implementation@>=
  14053. ModbusRtuPortConfWidget::ModbusRtuPortConfWidget(DeviceTreeModel *model,
  14054. const QModelIndex &index)
  14055. : BasicDeviceConfigurationWidget(model, index)
  14056. {
  14057. QFormLayout *layout = new QFormLayout;
  14058. QToolButton *addDeviceButton = new QToolButton;
  14059. addDeviceButton->setText(tr("Add Device"));
  14060. NodeInserter *addModbusRtuDevice = new NodeInserter("Modbus RTU Device",
  14061. "Modbus RTU Device",
  14062. "modbusrtudevice");
  14063. connect(addModbusRtuDevice, SIGNAL(triggered(QString, QString)),
  14064. this, SLOT(insertChildNode(QString, QString)));
  14065. QMenu *deviceMenu = new QMenu;
  14066. deviceMenu->addAction(addModbusRtuDevice);
  14067. addDeviceButton->setMenu(deviceMenu);
  14068. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  14069. layout->addRow(QString(), addDeviceButton);
  14070. PortSelector *port = new PortSelector;
  14071. layout->addRow(tr("Port:"), port);
  14072. connect(port, SIGNAL(currentIndexChanged(QString)),
  14073. this, SLOT(updatePort(QString)));
  14074. connect(port, SIGNAL(editTextChanged(QString)),
  14075. this, SLOT(updatePort(QString)));
  14076. BaudSelector *rate = new BaudSelector;
  14077. layout->addRow(tr("Baud:"), rate);
  14078. connect(rate, SIGNAL(currentIndexChanged(QString)),
  14079. this, SLOT(updateBaudRate(QString)));
  14080. ParitySelector *parity = new ParitySelector;
  14081. layout->addRow(tr("Parity:"), parity);
  14082. connect(parity, SIGNAL(currentIndexChanged(QString)),
  14083. this, SLOT(updateParity(QString)));
  14084. FlowSelector *flow = new FlowSelector;
  14085. layout->addRow(tr("Flow Control:"), flow);
  14086. connect(flow, SIGNAL(currentIndexChanged(QString)),
  14087. this, SLOT(updateFlowControl(QString)));
  14088. StopSelector *stop = new StopSelector;
  14089. layout->addRow(tr("Stop Bits:"), stop);
  14090. connect(stop, SIGNAL(currentIndexChanged(QString)),
  14091. this, SLOT(updateStopBits(QString)));
  14092. @<Get device configuration data for current node@>@;
  14093. for(int i = 0; i < configData.size(); i++)
  14094. {
  14095. node = configData.at(i).toElement();
  14096. if(node.attribute("name") == "port")
  14097. {
  14098. int j = port->findText(node.attribute("value"));
  14099. if(j >= 0)
  14100. {
  14101. port->setCurrentIndex(j);
  14102. }
  14103. else
  14104. {
  14105. port->insertItem(0, node.attribute("value"));
  14106. port->setCurrentIndex(0);
  14107. }
  14108. }
  14109. else if(node.attribute("name") == "baudrate")
  14110. {
  14111. rate->setCurrentIndex(rate->findText(node.attribute("value")));
  14112. }
  14113. else if(node.attribute("name") == "parity")
  14114. {
  14115. parity->setCurrentIndex(parity->findText(node.attribute("value")));
  14116. }
  14117. else if(node.attribute("name") == "flowcontrol")
  14118. {
  14119. flow->setCurrentIndex(flow->findText(node.attribute("value")));
  14120. }
  14121. else if(node.attribute("name") == "stopbits")
  14122. {
  14123. stop->setCurrentIndex(stop->findText(node.attribute("value")));
  14124. }
  14125. }
  14126. updatePort(port->currentText());
  14127. updateBaudRate(rate->currentText());
  14128. updateParity(parity->currentText());
  14129. updateFlowControl(flow->currentText());
  14130. updateStopBits(stop->currentText());
  14131. setLayout(layout);
  14132. }
  14133. void ModbusRtuPortConfWidget::updatePort(const QString &newPort)
  14134. {
  14135. updateAttribute("port", newPort);
  14136. }
  14137. void ModbusRtuPortConfWidget::updateBaudRate(const QString &newRate)
  14138. {
  14139. updateAttribute("baudrate", newRate);
  14140. }
  14141. void ModbusRtuPortConfWidget::updateParity(const QString &newParity)
  14142. {
  14143. updateAttribute("parity", newParity);
  14144. }
  14145. void ModbusRtuPortConfWidget::updateFlowControl(const QString &newFlow)
  14146. {
  14147. updateAttribute("flowcontrol", newFlow);
  14148. }
  14149. void ModbusRtuPortConfWidget::updateStopBits(const QString &newStopBits)
  14150. {
  14151. updateAttribute("stopbits", newStopBits);
  14152. }
  14153. @ From here we need to provide a widget for configuring a particular device.
  14154. At a minimum this would require setting the station number to a value between
  14155. 0 and 255. Zero is typically the broadcast address which reaches all devices
  14156. on the bus and is not generally recommended for use except in particular
  14157. circumstances. There are, however, a number of settings that influence all of
  14158. the currently supported child nodes and these settings are in the device
  14159. configuration widget instead of requiring that information to be duplicated
  14160. across multiple child nodes.
  14161. The Modbus RTU protocol is very general in scope and leaves many of the
  14162. details of how to do certain things up to the manufacturer. For rudimentary
  14163. support of devices using this protocol, the documentation for several devices
  14164. was consulted and a test rig with one device was set up. There are a number of
  14165. assumptions made for this initial support and to better support additional
  14166. device classes it may become necessary to expand on what is provided initially.
  14167. The primary focus presently is on the use of PID controllers as temperature
  14168. indicators with the ability to modify a set value in the case where this is
  14169. used as a controller rather than just a display.
  14170. All of the devices studied prior to adding this support made use of scaled
  14171. integer representation. In order to correctly determine the measured process
  14172. value it is necessary to know the unit of the measurement and the position of
  14173. the decimal point. It is generally possible to query this information, however
  14174. it may be useful to provide a way to specify fixed values in the event that a
  14175. device exposes these details in a way that is incompatible with my assumptions.
  14176. @<Class declarations@>=
  14177. class ModbusRtuDeviceConfWidget : public BasicDeviceConfigurationWidget
  14178. {
  14179. @[Q_OBJECT@]@;
  14180. public:@/
  14181. @[Q_INVOKABLE@]@, ModbusRtuDeviceConfWidget(DeviceTreeModel *model,
  14182. const QModelIndex &index);
  14183. @[private slots@]:@/
  14184. void updateStationNumber(int newStation);
  14185. void updateFixedUnit(bool newFixed);
  14186. void updateFixedDecimal(bool newFixed);
  14187. void updateUnit(const QString &newUnit);
  14188. void updateUnitAddress(int newAddress);
  14189. void updateValueF(int newValue);
  14190. void updateValueC(int newValue);
  14191. void updatePrecisionAddress(int newAddress);
  14192. void updatePrecisionValue(int newValue);
  14193. private:@/
  14194. QStackedLayout *unitSpecificationLayout;
  14195. QStackedLayout *decimalSpecificationLayout;
  14196. };
  14197. @ This widget has a number of differences from previous configuration widgets.
  14198. Perhaps most significantly there are controls which do not provide a text based
  14199. signal on state change. We also set certain controls as disabled when the
  14200. provided values are not relevant to operations such as when switching between
  14201. fixed decimal position and looking up decimal position from the device. Aside
  14202. from these details the widget operates according to the same principles as the
  14203. other widgets already seen.
  14204. @<ModbusRtuDeviceConfWidget implementation@>=
  14205. ModbusRtuDeviceConfWidget::ModbusRtuDeviceConfWidget(DeviceTreeModel *model,
  14206. const QModelIndex &index)
  14207. : BasicDeviceConfigurationWidget(model, index),
  14208. unitSpecificationLayout(new QStackedLayout),
  14209. decimalSpecificationLayout(new QStackedLayout)
  14210. {
  14211. QVBoxLayout *layout = new QVBoxLayout;
  14212. QToolButton *addChannelButton = new QToolButton;
  14213. addChannelButton->setText(tr("Add Channel"));
  14214. NodeInserter *addTemperaturePV = new NodeInserter("Temperature Process Value",
  14215. "Temperature Process Value",
  14216. "modbustemperaturepv");
  14217. NodeInserter *addTemperatureSV = new NodeInserter("Temperature Set Value",
  14218. "Temperature Set Value",
  14219. "modbustemperaturesv");
  14220. connect(addTemperaturePV, SIGNAL(triggered(QString, QString)),
  14221. this, SLOT(insertChildNode(QString, QString)));
  14222. connect(addTemperatureSV, SIGNAL(triggered(QString, QString)),
  14223. this, SLOT(insertChildNode(QString, QString)));
  14224. QMenu *channelMenu = new QMenu;
  14225. channelMenu->addAction(addTemperaturePV);
  14226. channelMenu->addAction(addTemperatureSV);
  14227. addChannelButton->setMenu(channelMenu);
  14228. addChannelButton->setPopupMode(QToolButton::InstantPopup);
  14229. layout->addWidget(addChannelButton);
  14230. QHBoxLayout *stationLayout = new QHBoxLayout;
  14231. QLabel *stationLabel = new QLabel(tr("Station:"));
  14232. QSpinBox *stationNumber = new QSpinBox;
  14233. stationNumber->setMinimum(0);
  14234. stationNumber->setMaximum(255);
  14235. stationLayout->addWidget(stationLabel);
  14236. stationLayout->addWidget(stationNumber);
  14237. layout->addLayout(stationLayout);
  14238. QCheckBox *fixedUnit = new QCheckBox(tr("Fixed Temperature Unit"));
  14239. layout->addWidget(fixedUnit);
  14240. QWidget *fixedUnitPlaceholder = new QWidget(this);
  14241. QHBoxLayout *fixedUnitLayout = new QHBoxLayout;
  14242. QLabel *fixedUnitLabel = new QLabel(tr("Temperature Unit:"));
  14243. QComboBox *fixedUnitSelector = new QComboBox;
  14244. fixedUnitSelector->addItem("Fahrenheit");
  14245. fixedUnitSelector->addItem("Celsius");
  14246. fixedUnitLayout->addWidget(fixedUnitLabel);
  14247. fixedUnitLayout->addWidget(fixedUnitSelector);
  14248. fixedUnitPlaceholder->setLayout(fixedUnitLayout);
  14249. unitSpecificationLayout->addWidget(fixedUnitPlaceholder);
  14250. QWidget *queriedUnitPlaceholder = new QWidget(this);
  14251. QFormLayout *queriedUnitLayout = new QFormLayout;
  14252. ShortHexSpinBox *unitAddress = new ShortHexSpinBox;
  14253. queriedUnitLayout->addRow(tr("Function 0x03 Unit Address:"), unitAddress);
  14254. QSpinBox *valueF = new QSpinBox;
  14255. valueF->setMinimum(0);
  14256. valueF->setMaximum(65535);
  14257. queriedUnitLayout->addRow(tr("Value for Fahrenheit"), valueF);
  14258. QSpinBox *valueC = new QSpinBox;
  14259. valueC->setMinimum(0);
  14260. valueC->setMaximum(65535);
  14261. queriedUnitLayout->addRow(tr("Value for Celsius"), valueC);
  14262. queriedUnitPlaceholder->setLayout(queriedUnitLayout);
  14263. unitSpecificationLayout->addWidget(queriedUnitPlaceholder);
  14264. layout->addLayout(unitSpecificationLayout);
  14265. QCheckBox *fixedPrecision = new QCheckBox(tr("Fixed Precision"));
  14266. layout->addWidget(fixedPrecision);
  14267. QWidget *fixedPrecisionPlaceholder = new QWidget(this);
  14268. QFormLayout *fixedPrecisionLayout = new QFormLayout;
  14269. QSpinBox *fixedPrecisionValue = new QSpinBox;
  14270. fixedPrecisionValue->setMinimum(0);
  14271. fixedPrecisionValue->setMaximum(9);
  14272. fixedPrecisionLayout->addRow("Places after the decimal point:",
  14273. fixedPrecisionValue);
  14274. fixedPrecisionPlaceholder->setLayout(fixedPrecisionLayout);
  14275. decimalSpecificationLayout->addWidget(fixedPrecisionPlaceholder);
  14276. QWidget *queriedPrecisionPlaceholder = new QWidget(this);
  14277. QFormLayout *queriedPrecisionLayout = new QFormLayout;
  14278. ShortHexSpinBox *precisionAddress = new ShortHexSpinBox;
  14279. queriedPrecisionLayout->addRow("Function 0x03 Decimal Position Address:",
  14280. precisionAddress);
  14281. queriedPrecisionPlaceholder->setLayout(queriedPrecisionLayout);
  14282. decimalSpecificationLayout->addWidget(queriedPrecisionPlaceholder);
  14283. layout->addLayout(decimalSpecificationLayout);
  14284. @<Get device configuration data for current node@>@;
  14285. for(int i = 0; i < configData.size(); i++)
  14286. {
  14287. node = configData.at(i).toElement();
  14288. if(node.attribute("name") == "station")
  14289. {
  14290. stationNumber->setValue(node.attribute("value").toInt());
  14291. }
  14292. else if(node.attribute("name") == "fixedunit")
  14293. {
  14294. if(node.attribute("value") == "true")
  14295. {
  14296. fixedUnit->setCheckState(Qt::Checked);
  14297. }
  14298. else if(node.attribute("value") == "false")
  14299. {
  14300. fixedUnit->setCheckState(Qt::Unchecked);
  14301. }
  14302. }
  14303. else if(node.attribute("name") == "fixedprecision")
  14304. {
  14305. fixedPrecisionValue->setValue(node.attribute("value").toInt());
  14306. }
  14307. else if(node.attribute("name") == "unit")
  14308. {
  14309. fixedUnitSelector->setCurrentIndex(fixedUnitSelector->findText(node.attribute("value")));
  14310. }
  14311. else if(node.attribute("name") == "unitaddress")
  14312. {
  14313. unitAddress->setValue(node.attribute("value").toInt());
  14314. }
  14315. else if(node.attribute("name") == "fvalue")
  14316. {
  14317. valueF->setValue(node.attribute("value").toInt());
  14318. }
  14319. else if(node.attribute("name") == "cvalue")
  14320. {
  14321. valueC->setValue(node.attribute("value").toInt());
  14322. }
  14323. else if(node.attribute("name") == "precisionaddress")
  14324. {
  14325. precisionAddress->setValue(node.attribute("value").toInt());
  14326. }
  14327. else if(node.attribute("name") == "precision")
  14328. {
  14329. fixedPrecisionValue->setValue(node.attribute("value").toInt());
  14330. }
  14331. }
  14332. updateStationNumber(stationNumber->value());
  14333. updateFixedUnit(fixedUnit->isChecked());
  14334. updateFixedDecimal(fixedPrecision->isChecked());
  14335. updateUnit(fixedUnitSelector->currentText());
  14336. updateUnitAddress(unitAddress->value());
  14337. updateValueF(valueF->value());
  14338. updateValueC(valueC->value());
  14339. updatePrecisionAddress(precisionAddress->value());
  14340. updatePrecisionValue(fixedPrecisionValue->value());
  14341. connect(stationNumber, SIGNAL(valueChanged(int)),
  14342. this, SLOT(updateStationNumber(int)));
  14343. connect(fixedUnitSelector, SIGNAL(currentIndexChanged(QString)),
  14344. this, SLOT(updateUnit(QString)));
  14345. connect(unitAddress, SIGNAL(valueChanged(int)),
  14346. this, SLOT(updateUnitAddress(int)));
  14347. connect(valueF, SIGNAL(valueChanged(int)),
  14348. this, SLOT(updateValueF(int)));
  14349. connect(valueC, SIGNAL(valueChanged(int)),
  14350. this, SLOT(updateValueC(int)));
  14351. connect(fixedUnit, SIGNAL(toggled(bool)),
  14352. this, SLOT(updateFixedUnit(bool)));
  14353. connect(fixedPrecision, SIGNAL(toggled(bool)),
  14354. this, SLOT(updateFixedDecimal(bool)));
  14355. connect(fixedPrecisionValue, SIGNAL(valueChanged(int)),
  14356. this, SLOT(updatePrecisionValue(int)));
  14357. connect(precisionAddress, SIGNAL(valueChanged(int)),
  14358. this, SLOT(updatePrecisionAddress(int)));
  14359. setLayout(layout);
  14360. }
  14361. void ModbusRtuDeviceConfWidget::updateStationNumber(int newStation)
  14362. {
  14363. updateAttribute("station", QString("%1").arg(newStation));
  14364. }
  14365. void ModbusRtuDeviceConfWidget::updateFixedUnit(bool newFixed)
  14366. {
  14367. if(newFixed)
  14368. {
  14369. unitSpecificationLayout->setCurrentIndex(0);
  14370. updateAttribute("fixedunit", "true");
  14371. }
  14372. else
  14373. {
  14374. unitSpecificationLayout->setCurrentIndex(1);
  14375. updateAttribute("fixedunit", "false");
  14376. }
  14377. }
  14378. void ModbusRtuDeviceConfWidget::updateFixedDecimal(bool newFixed)
  14379. {
  14380. if(newFixed)
  14381. {
  14382. decimalSpecificationLayout->setCurrentIndex(0);
  14383. updateAttribute("fixedprecision", "true");
  14384. }
  14385. else
  14386. {
  14387. decimalSpecificationLayout->setCurrentIndex(1);
  14388. updateAttribute("fixedprecision", "false");
  14389. }
  14390. }
  14391. void ModbusRtuDeviceConfWidget::updateUnit(const QString &newUnit)
  14392. {
  14393. updateAttribute("unit", newUnit);
  14394. }
  14395. void ModbusRtuDeviceConfWidget::updateUnitAddress(int newAddress)
  14396. {
  14397. updateAttribute("unitaddress", QString("%1").arg(newAddress));
  14398. }
  14399. void ModbusRtuDeviceConfWidget::updateValueF(int newValue)
  14400. {
  14401. updateAttribute("fvalue", QString("%1").arg(newValue));
  14402. }
  14403. void ModbusRtuDeviceConfWidget::updateValueC(int newValue)
  14404. {
  14405. updateAttribute("cvalue", QString("%1").arg(newValue));
  14406. }
  14407. void ModbusRtuDeviceConfWidget::updatePrecisionAddress(int newAddress)
  14408. {
  14409. updateAttribute("precisionaddress", QString("%1").arg(newAddress));
  14410. }
  14411. void ModbusRtuDeviceConfWidget::updatePrecisionValue(int newValue)
  14412. {
  14413. updateAttribute("precision", QString("%1").arg(newValue));
  14414. }
  14415. @ Initial Modbus RTU support is very limited and only considers temperature
  14416. process and set values. While in some cases it would be possible to cleverly
  14417. adapt this support to broader categories this is an area that must be extended
  14418. later to cover at least unitless control values and on/off status values. It
  14419. would be ideal to cover a broad range of useful properties. To read process
  14420. values we need to know the address that the current process value can be read
  14421. from.
  14422. @<Class declarations@>=
  14423. class ModbusRtuDeviceTPvConfWidget : public BasicDeviceConfigurationWidget
  14424. {
  14425. @[Q_OBJECT@]@/
  14426. public:@/
  14427. @[Q_INVOKABLE@]@, ModbusRtuDeviceTPvConfWidget(DeviceTreeModel *model,
  14428. const QModelIndex &index);
  14429. @[private slots@]:@/
  14430. void updateAddress(int newAddress);
  14431. };
  14432. @ This requires only a single field to store the address to query the current
  14433. process value.
  14434. @<ModbusRtuDeviceTPvConfWidget implementation@>=
  14435. ModbusRtuDeviceTPvConfWidget::ModbusRtuDeviceTPvConfWidget(DeviceTreeModel *model,
  14436. const QModelIndex &index)
  14437. : BasicDeviceConfigurationWidget(model, index)
  14438. {
  14439. QFormLayout *layout = new QFormLayout;
  14440. ShortHexSpinBox *address = new ShortHexSpinBox;
  14441. layout->addRow(tr("Function 0x04 Process Value Address"), address);
  14442. @<Get device configuration data for current node@>@;
  14443. for(int i = 0; i < configData.size(); i++)
  14444. {
  14445. node = configData.at(i).toElement();
  14446. if(node.attribute("name") == "address")
  14447. {
  14448. address->setValue(node.attribute("value").toInt());
  14449. break;
  14450. }
  14451. }
  14452. updateAddress(address->value());
  14453. connect(address, SIGNAL(valueChanged(int)), this, SLOT(updateAddress(int)));
  14454. setLayout(layout);
  14455. }
  14456. void ModbusRtuDeviceTPvConfWidget::updateAddress(int newAddress)
  14457. {
  14458. updateAttribute("address", QString("%1").arg(newAddress));
  14459. }
  14460. @ Set values are slightly more complicated as we may want either a fixed range
  14461. or the ability to query the device for its current allowed range, but nothing
  14462. is here that hasn't been seen elsewhere.
  14463. @<Class declarations@>=
  14464. class ModbusRtuDeviceTSvConfWidget : public BasicDeviceConfigurationWidget
  14465. {
  14466. @[Q_OBJECT@]@;
  14467. public:@/
  14468. @[Q_INVOKABLE@]@, ModbusRtuDeviceTSvConfWidget(DeviceTreeModel *model,
  14469. const QModelIndex &index);
  14470. @[private slots@]:@/
  14471. void updateReadAddress(int newAddress);
  14472. void updateWriteAddress(int newAddress);
  14473. void updateFixedRange(bool fixed);
  14474. void updateLower(const QString &lower);
  14475. void updateUpper(const QString &upper);
  14476. void updateLowerAddress(int newAddress);
  14477. void updateUpperAddress(int newAddress);
  14478. private:
  14479. QStackedLayout *boundsLayout;
  14480. };
  14481. @ Upper and lower bounds when operating on a fixed range are still subject to
  14482. decimal position rules in the parent node. It may be a good idea to enforce
  14483. this, however at present the person configuring the system is trusted to know
  14484. what they are doing.
  14485. @<ModbusRtuDeviceTSvConfWidget implementation@>=
  14486. ModbusRtuDeviceTSvConfWidget::ModbusRtuDeviceTSvConfWidget(DeviceTreeModel *model,
  14487. const QModelIndex &index)
  14488. : BasicDeviceConfigurationWidget(model, index), boundsLayout(new QStackedLayout)
  14489. {
  14490. QVBoxLayout *layout = new QVBoxLayout;
  14491. QFormLayout *addressLayout = new QFormLayout;
  14492. ShortHexSpinBox *readAddress = new ShortHexSpinBox;
  14493. ShortHexSpinBox *writeAddress = new ShortHexSpinBox;
  14494. addressLayout->addRow(tr("Function 0x04 Read Set Value Address:"), readAddress);
  14495. addressLayout->addRow(tr("Function 0x06 Write Set Value Address:"), writeAddress);
  14496. layout->addLayout(addressLayout);
  14497. QCheckBox *fixedRange = new QCheckBox(tr("Fixed Set Value Range"));
  14498. layout->addWidget(fixedRange);
  14499. QWidget *queriedRangePlaceholder = new QWidget(this);
  14500. QFormLayout *queriedRangeLayout = new QFormLayout;
  14501. ShortHexSpinBox *lowerAddress = new ShortHexSpinBox;
  14502. ShortHexSpinBox *upperAddress = new ShortHexSpinBox;
  14503. queriedRangeLayout->addRow(tr("Function 0x03 Minimum Set Value Address"),
  14504. lowerAddress);
  14505. queriedRangeLayout->addRow(tr("Function 0x03 Maximum Set Value Address"),
  14506. upperAddress);
  14507. queriedRangePlaceholder->setLayout(queriedRangeLayout);
  14508. boundsLayout->addWidget(queriedRangePlaceholder);
  14509. QWidget *fixedRangePlaceholder = new QWidget(this);
  14510. QFormLayout *fixedRangeLayout = new QFormLayout;
  14511. QLineEdit *fixedLower = new QLineEdit;
  14512. QLineEdit *fixedUpper = new QLineEdit;
  14513. fixedRangeLayout->addRow(tr("Minimum Set Value:"), fixedLower);
  14514. fixedRangeLayout->addRow(tr("Maximum Set Value:"), fixedUpper);
  14515. fixedRangePlaceholder->setLayout(fixedRangeLayout);
  14516. boundsLayout->addWidget(fixedRangePlaceholder);
  14517. layout->addLayout(boundsLayout);
  14518. @<Get device configuration data for current node@>@;
  14519. for(int i = 0; i < configData.size(); i++)
  14520. {
  14521. node = configData.at(i).toElement();
  14522. if(node.attribute("name") == "readaddress")
  14523. {
  14524. readAddress->setValue(node.attribute("value").toInt());
  14525. }
  14526. else if(node.attribute("name") == "writeaddress")
  14527. {
  14528. writeAddress->setValue(node.attribute("value").toInt());
  14529. }
  14530. else if(node.attribute("name") == "fixedrange")
  14531. {
  14532. if(node.attribute("value") == "true")
  14533. {
  14534. fixedRange->setCheckState(Qt::Checked);
  14535. }
  14536. else if(node.attribute("value") == "false")
  14537. {
  14538. fixedRange->setCheckState(Qt::Unchecked);
  14539. }
  14540. }
  14541. else if(node.attribute("name") == "fixedlower")
  14542. {
  14543. fixedLower->setText(node.attribute("value"));
  14544. }
  14545. else if(node.attribute("name") == "fixedupper")
  14546. {
  14547. fixedUpper->setText(node.attribute("value"));
  14548. }
  14549. else if(node.attribute("name") == "loweraddress")
  14550. {
  14551. lowerAddress->setValue(node.attribute("value").toInt());
  14552. }
  14553. else if(node.attribute("name") == "upperaddress")
  14554. {
  14555. upperAddress->setValue(node.attribute("value").toInt());
  14556. }
  14557. }
  14558. updateReadAddress(readAddress->value());
  14559. updateWriteAddress(writeAddress->value());
  14560. updateFixedRange(fixedRange->isChecked());
  14561. updateLower(fixedLower->text());
  14562. updateUpper(fixedUpper->text());
  14563. updateLowerAddress(lowerAddress->value());
  14564. updateUpperAddress(upperAddress->value());
  14565. connect(readAddress, SIGNAL(valueChanged(int)),
  14566. this, SLOT(updateReadAddress(int)));
  14567. connect(writeAddress, SIGNAL(valueChanged(int)),
  14568. this, SLOT(updateWriteAddress(int)));
  14569. connect(fixedRange, SIGNAL(toggled(bool)), this, SLOT(updateFixedRange(bool)));
  14570. connect(fixedLower, SIGNAL(textChanged(QString)),
  14571. this, SLOT(updateLower(QString)));
  14572. connect(fixedUpper, SIGNAL(textChanged(QString)),
  14573. this, SLOT(updateUpper(QString)));
  14574. connect(lowerAddress, SIGNAL(valueChanged(int)),
  14575. this, SLOT(updateLowerAddress(int)));
  14576. connect(upperAddress, SIGNAL(valueChanged(int)),
  14577. this, SLOT(updateUpperAddress(int)));
  14578. setLayout(layout);
  14579. }
  14580. void ModbusRtuDeviceTSvConfWidget::updateReadAddress(int newAddress)
  14581. {
  14582. updateAttribute("readaddress", QString("%1").arg(newAddress));
  14583. }
  14584. void ModbusRtuDeviceTSvConfWidget::updateWriteAddress(int newAddress)
  14585. {
  14586. updateAttribute("writeaddress", QString("%1").arg(newAddress));
  14587. }
  14588. void ModbusRtuDeviceTSvConfWidget::updateFixedRange(bool fixed)
  14589. {
  14590. if(fixed)
  14591. {
  14592. updateAttribute("fixedrange", "true");
  14593. boundsLayout->setCurrentIndex(1);
  14594. }
  14595. else
  14596. {
  14597. updateAttribute("fixedrange", "false");
  14598. boundsLayout->setCurrentIndex(0);
  14599. }
  14600. }
  14601. void ModbusRtuDeviceTSvConfWidget::updateLower(const QString &lower)
  14602. {
  14603. updateAttribute("fixedlower", lower);
  14604. }
  14605. void ModbusRtuDeviceTSvConfWidget::updateUpper(const QString &upper)
  14606. {
  14607. updateAttribute("fixedupper", upper);
  14608. }
  14609. void ModbusRtuDeviceTSvConfWidget::updateLowerAddress(int newAddress)
  14610. {
  14611. updateAttribute("loweraddress", QString("%1").arg(newAddress));
  14612. }
  14613. void ModbusRtuDeviceTSvConfWidget::updateUpperAddress(int newAddress)
  14614. {
  14615. updateAttribute("upperaddress", QString("%1").arg(newAddress));
  14616. }
  14617. @ The configuration widgets need to be registered.
  14618. @<Register device configuration widgets@>=
  14619. app.registerDeviceConfigurationWidget("modbusrtuport", ModbusRtuPortConfWidget::staticMetaObject);
  14620. app.registerDeviceConfigurationWidget("modbusrtudevice", ModbusRtuDeviceConfWidget::staticMetaObject);
  14621. app.registerDeviceConfigurationWidget("modbustemperaturepv", ModbusRtuDeviceTPvConfWidget::staticMetaObject);
  14622. app.registerDeviceConfigurationWidget("modbustemperaturesv", ModbusRtuDeviceTSvConfWidget::staticMetaObject);
  14623. @ A |NodeInserter| for the driver configuration widget is also needed. Note
  14624. that this is temporarily disabled. These configuration widgets will become
  14625. useful when I rearchitect the Modbus RTU support in a future release.
  14626. @<Register top level device configuration nodes@>=
  14627. #if 0
  14628. inserter = new NodeInserter(tr("Modbus RTU Port"), tr("Modbus RTU Port"), "modbusrtuport", NULL);
  14629. topLevelNodeInserters.append(inserter);
  14630. #endif
  14631. @** Configuration of Annotation Controls.
  14632. \noindent Aside from the details of hardware devices, the logging view must
  14633. also be able to set up log annotation controls. A few different control types
  14634. are offered. These include simple push buttons which insert a fixed annotation
  14635. when activated, push buttons which insert a value that includes a number which
  14636. is incremented every time the button is pressed, free text entry fields, and
  14637. numeric entry fields.
  14638. The basic push button control should allow configuration of both the button
  14639. text and the annotation text.
  14640. @<Class declarations@>=
  14641. class AnnotationButtonConfWidget : public BasicDeviceConfigurationWidget
  14642. {
  14643. @[Q_OBJECT@]@;
  14644. public:@/
  14645. @[Q_INVOKABLE@]@, AnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  14646. @[private slots@]:@/
  14647. void updateButtonText(const QString &text);
  14648. void updateAnnotationText(const QString &text);
  14649. };
  14650. @ The constructor sets up the controls for editing this data.
  14651. @<AnnotationButtonConfWidget implementation@>=
  14652. AnnotationButtonConfWidget::AnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  14653. : BasicDeviceConfigurationWidget(model, index)
  14654. {
  14655. QFormLayout *layout = new QFormLayout;
  14656. QLineEdit *buttonTextEdit = new QLineEdit;
  14657. QLineEdit *annotationTextEdit = new QLineEdit;
  14658. layout->addRow(tr("Button Text:"), buttonTextEdit);
  14659. layout->addRow(tr("Annotation Text:"), annotationTextEdit);
  14660. @<Get device configuration data for current node@>@;
  14661. for(int i = 0; i < configData.size(); i++)
  14662. {
  14663. node = configData.at(i).toElement();
  14664. if(node.attribute("name") == "buttontext")
  14665. {
  14666. buttonTextEdit->setText(node.attribute("value"));
  14667. }
  14668. else if(node.attribute("name") == "annotationtext")
  14669. {
  14670. annotationTextEdit->setText(node.attribute("value"));
  14671. }
  14672. }
  14673. updateButtonText(buttonTextEdit->text());
  14674. updateAnnotationText(annotationTextEdit->text());
  14675. connect(buttonTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateButtonText(QString)));
  14676. connect(annotationTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateAnnotationText(QString)));
  14677. setLayout(layout);
  14678. }
  14679. @ The slots are implemented trivially.
  14680. @<AnnotationButtonConfWidget implementation@>=
  14681. void AnnotationButtonConfWidget::updateButtonText(const QString &text)
  14682. {
  14683. updateAttribute("buttontext", text);
  14684. }
  14685. void AnnotationButtonConfWidget::updateAnnotationText(const QString &text)
  14686. {
  14687. updateAttribute("annotationtext", text);
  14688. }
  14689. @ The control must be registered.
  14690. @<Register device configuration widgets@>=
  14691. app.registerDeviceConfigurationWidget("annotationbutton", AnnotationButtonConfWidget::staticMetaObject);
  14692. @ Closely related to the previous control is one which provides parameterized
  14693. text. Technically this is not needed as both this and the previous
  14694. configuration control map to the same widget in the logging view and
  14695. parameterized annotation text can be used with either. The reason for
  14696. separating these is to indicate that it should be possible to change the text
  14697. and reset the number without altering the default configuration or requiring a
  14698. reinitialization of the logging view.
  14699. @<Class declarations@>=
  14700. class ReconfigurableAnnotationButtonConfWidget : public BasicDeviceConfigurationWidget
  14701. {
  14702. @[Q_OBJECT@]@/
  14703. public:@/
  14704. @[Q_INVOKABLE@] ReconfigurableAnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  14705. @[private slots@]:@/
  14706. void updateButtonText(const QString &text);
  14707. void updateAnnotationText(const QString &text);
  14708. };
  14709. @ The key difference in implementation is the addition of some documentation on
  14710. how to specify a numeric placeholder in the annotation text.
  14711. @<AnnotationButtonConfWidget implementation@>=
  14712. ReconfigurableAnnotationButtonConfWidget::ReconfigurableAnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  14713. : BasicDeviceConfigurationWidget(model, index)
  14714. {
  14715. QFormLayout *layout = new QFormLayout;
  14716. QLineEdit *buttonTextEdit = new QLineEdit;
  14717. QLineEdit *annotationTextEdit = new QLineEdit;
  14718. layout->addRow(tr("Button Text:"), buttonTextEdit);
  14719. layout->addRow(tr("Annotation Text:"), annotationTextEdit);
  14720. @<Get device configuration data for current node@>@;
  14721. for(int i = 0; i < configData.size(); i++)
  14722. {
  14723. node = configData.at(i).toElement();
  14724. if(node.attribute("name") == "buttontext")
  14725. {
  14726. buttonTextEdit->setText(node.attribute("value"));
  14727. }
  14728. else if(node.attribute("name") == "annotationtext")
  14729. {
  14730. annotationTextEdit->setText(node.attribute("value"));
  14731. }
  14732. }
  14733. updateButtonText(buttonTextEdit->text());
  14734. updateAnnotationText(annotationTextEdit->text());
  14735. connect(buttonTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateButtonText(QString)));
  14736. connect(annotationTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateAnnotationText(QString)));
  14737. QTextEdit *documentation = new QTextEdit;
  14738. 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."));
  14739. documentation->setReadOnly(true);
  14740. layout->addRow("", documentation);
  14741. setLayout(layout);
  14742. }
  14743. void ReconfigurableAnnotationButtonConfWidget::updateButtonText(const QString &text)
  14744. {
  14745. updateAttribute("buttontext", text);
  14746. }
  14747. void ReconfigurableAnnotationButtonConfWidget::updateAnnotationText(const QString &text)
  14748. {
  14749. updateAttribute("annotationtext", text);
  14750. }
  14751. @ The control must be registered as usual.
  14752. @<Register device configuration widgets@>=
  14753. app.registerDeviceConfigurationWidget("reconfigurablebutton", ReconfigurableAnnotationButtonConfWidget::staticMetaObject);
  14754. @ While it is generally better to have all measurements logged automatically,
  14755. many roasters would like to keep track of infrequently altered control
  14756. variables which have not been set up for automated logging. A reading from the
  14757. manometer after a fuel adjustment, for example, is frequently not available by
  14758. automated means. In cases such as this, providing for numeric annotation entry
  14759. may be desired. The |AnnotationSpinBox| provides for this. There are a few
  14760. details that are important in this. First is a label to better indicate to the
  14761. operator what values in this control represent. The range of allowed values and
  14762. the number of decimal places is important. This control also allows the
  14763. specification of text to precede and/or follow the numeric value and this must
  14764. be configurable.
  14765. @<Class declarations@>=
  14766. class NoteSpinConfWidget : public BasicDeviceConfigurationWidget
  14767. {
  14768. @[Q_OBJECT@]@;
  14769. public:@/
  14770. @[Q_INVOKABLE@]@, NoteSpinConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  14771. @[private slots@]:@/
  14772. void updateLabel(const QString &text);
  14773. void updateMinimum(const QString &minimum);
  14774. void updateMaximum(const QString &maximum);
  14775. void updatePrecision(int precision);
  14776. void updatePretext(const QString &text);
  14777. void updatePosttext(const QString &text);
  14778. };
  14779. @ There is nothing new in the implementation of note.
  14780. @<NoteSpinConfWidget implementation@>=
  14781. NoteSpinConfWidget::NoteSpinConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  14782. : BasicDeviceConfigurationWidget(model, index)
  14783. {
  14784. QFormLayout *layout = new QFormLayout;
  14785. QLineEdit *labelEdit = new QLineEdit;
  14786. layout->addRow(tr("Control Label: "), labelEdit);
  14787. QLineEdit *minimumEdit = new QLineEdit;
  14788. layout->addRow(tr("Minimum Value: "), minimumEdit);
  14789. QLineEdit *maximumEdit = new QLineEdit;
  14790. layout->addRow(tr("Maximum Value: "), maximumEdit);
  14791. QSpinBox *precisionEdit = new QSpinBox;
  14792. precisionEdit->setMinimum(0);
  14793. precisionEdit->setMaximum(9);
  14794. layout->addRow(tr("Precision"), precisionEdit);
  14795. QLineEdit *pretext = new QLineEdit;
  14796. layout->addRow(tr("Prefix text"), pretext);
  14797. QLineEdit *posttext = new QLineEdit;
  14798. layout->addRow(tr("Suffix text"), posttext);
  14799. @<Get device configuration data for current node@>@;
  14800. for(int i = 0; i < configData.size(); i++)
  14801. {
  14802. node = configData.at(i).toElement();
  14803. if(node.attribute("name") == "label")
  14804. {
  14805. labelEdit->setText(node.attribute("value"));
  14806. }
  14807. else if(node.attribute("name") == "minimum")
  14808. {
  14809. minimumEdit->setText(node.attribute("value"));
  14810. }
  14811. else if(node.attribute("name") == "maximum")
  14812. {
  14813. maximumEdit->setText(node.attribute("value"));
  14814. }
  14815. else if(node.attribute("name") == "precision")
  14816. {
  14817. precisionEdit->setValue(node.attribute("value").toInt());
  14818. }
  14819. else if(node.attribute("name") == "pretext")
  14820. {
  14821. pretext->setText(node.attribute("value"));
  14822. }
  14823. else if(node.attribute("name") == "posttext")
  14824. {
  14825. posttext->setText(node.attribute("value"));
  14826. }
  14827. }
  14828. updateLabel(labelEdit->text());
  14829. updateMinimum(minimumEdit->text());
  14830. updateMaximum(maximumEdit->text());
  14831. updatePrecision(precisionEdit->value());
  14832. updatePretext(pretext->text());
  14833. updatePosttext(posttext->text());
  14834. connect(labelEdit, SIGNAL(textEdited(QString)), this, SLOT(updateLabel(QString)));
  14835. connect(minimumEdit, SIGNAL(textEdited(QString)), this, SLOT(updateMinimum(QString)));
  14836. connect(maximumEdit, SIGNAL(textEdited(QString)), this, SLOT(updateMaximum(QString)));
  14837. connect(precisionEdit, SIGNAL(valueChanged(int)), this, SLOT(updatePrecision(int)));
  14838. connect(pretext, SIGNAL(textEdited(QString)), this, SLOT(updatePretext(QString)));
  14839. connect(posttext, SIGNAL(textEdited(QString)), this, SLOT(updatePosttext(QString)));
  14840. setLayout(layout);
  14841. }
  14842. void NoteSpinConfWidget::updateLabel(const QString &text)
  14843. {
  14844. updateAttribute("label", text);
  14845. }
  14846. void NoteSpinConfWidget::updateMinimum(const QString &minimum)
  14847. {
  14848. updateAttribute("minimum", minimum);
  14849. }
  14850. void NoteSpinConfWidget::updateMaximum(const QString &maximum)
  14851. {
  14852. updateAttribute("maximum", maximum);
  14853. }
  14854. void NoteSpinConfWidget::updatePrecision(int precision)
  14855. {
  14856. updateAttribute("precision", QString("%1").arg(precision));
  14857. }
  14858. void NoteSpinConfWidget::updatePretext(const QString &text)
  14859. {
  14860. updateAttribute("pretext", text);
  14861. }
  14862. void NoteSpinConfWidget::updatePosttext(const QString &text)
  14863. {
  14864. updateAttribute("posttext", text);
  14865. }
  14866. @ Configuration widget registration is as usual.
  14867. @<Register device configuration widgets@>=
  14868. app.registerDeviceConfigurationWidget("annotationspinbox", NoteSpinConfWidget::staticMetaObject);
  14869. @i freeannotation.w
  14870. @** Communicating with a Device through Modbus RTU.
  14871. \noindent The classes described here need to be further generalized to support
  14872. communications with multiple devices on the same port. The interface is based
  14873. on the |DAQ| class but extended to support additional functionality.
  14874. @<Class declarations@>=
  14875. class ModbusRTUDevice : public QObject
  14876. {
  14877. @[Q_OBJECT@]@;
  14878. public:@/
  14879. ModbusRTUDevice(DeviceTreeModel *model, const QModelIndex &index);
  14880. ~ModbusRTUDevice();
  14881. void queueMessage(QByteArray request, QObject *object, const char *callback);
  14882. @[Q_INVOKABLE@]@, double SVLower();
  14883. @[Q_INVOKABLE@]@, double SVUpper();
  14884. @[Q_INVOKABLE@]@, int decimals();
  14885. QList<Channel*> channels;
  14886. @[public slots@]:@/
  14887. void outputSV(double sv);
  14888. @[signals@]:@/
  14889. void SVLowerChanged(double);
  14890. void SVUpperChanged(double);
  14891. void SVDecimalChanged(int);
  14892. void queueEmpty();
  14893. @[private slots@]:@/
  14894. void dataAvailable();
  14895. void sendNextMessage();
  14896. void decimalResponse(QByteArray response);
  14897. void unitResponse(QByteArray response);
  14898. void svlResponse(QByteArray response);
  14899. void svuResponse(QByteArray response);
  14900. void requestMeasurement();
  14901. void mResponse(QByteArray response);
  14902. void ignore(QByteArray response);
  14903. private:@/
  14904. QextSerialPort *port;
  14905. QByteArray responseBuffer;
  14906. QList<QByteArray> messageQueue;
  14907. QList<QObject *> retObjQueue;
  14908. QList<char *> callbackQueue;
  14909. quint16 calculateCRC(QByteArray data);
  14910. QTimer *messageDelayTimer;
  14911. int delayTime;
  14912. char station;
  14913. int decimalPosition;
  14914. int valueF;
  14915. int valueC;
  14916. bool unitIsF;
  14917. double outputSVLower;
  14918. double outputSVUpper;
  14919. QByteArray outputSVStub;
  14920. QByteArray pvStub;
  14921. QByteArray svStub;
  14922. QByteArray mStub;
  14923. quint16 pvaddress;
  14924. quint16 svaddress;
  14925. bool svenabled;
  14926. bool readingsv;
  14927. double savedpv;
  14928. bool waiting;
  14929. };
  14930. @ The constructor reads its configuration from the configuration sub-tree of the
  14931. port node. This was adapted from a prototype implementation which used
  14932. |QSettings| to store this data. Note that this will only process the first
  14933. device specified on the port, the first process value on that device, and the
  14934. first set value on that device. A much more versatile architecture has been
  14935. planned for a future release which allows multiple devices per bus and
  14936. arbitrarily many monitored addresses per device. Communications are initiated
  14937. immediately upon construction.
  14938. @<ModbusRTUDevice implementation@>=
  14939. ModbusRTUDevice::ModbusRTUDevice(DeviceTreeModel *model, const QModelIndex &index)
  14940. : QObject(NULL), messageDelayTimer(new QTimer), unitIsF(true), readingsv(false),
  14941. waiting(false)
  14942. {
  14943. QDomElement portReferenceElement = model->referenceElement(model->data(index,
  14944. Qt::UserRole).toString());
  14945. QDomNodeList portConfigData = portReferenceElement.elementsByTagName("attribute");
  14946. QDomElement node;
  14947. QVariantMap attributes;
  14948. for(int i = 0; i < portConfigData.size(); i++)
  14949. {
  14950. node = portConfigData.at(i).toElement();
  14951. attributes.insert(node.attribute("name"), node.attribute("value"));
  14952. }
  14953. port = new QextSerialPort(attributes.value("port").toString(),
  14954. QextSerialPort::EventDriven);
  14955. int baudRate = attributes.value("baud").toInt();
  14956. port->setBaudRate((BaudRateType)baudRate);
  14957. double temp = ((double)(1) / (double)(baudRate)) * 48;
  14958. delayTime = (int)(temp * 3000);
  14959. messageDelayTimer->setSingleShot(true);
  14960. connect(messageDelayTimer, SIGNAL(timeout()), this, SLOT(sendNextMessage()));
  14961. port->setDataBits(DATA_8);
  14962. port->setParity((ParityType)attributes.value("parity").toInt());
  14963. port->setStopBits((StopBitsType)attributes.value("stop").toInt());
  14964. port->setFlowControl((FlowType)attributes.value("flow").toInt());
  14965. connect(port, SIGNAL(readyRead()), this, SLOT(dataAvailable()));
  14966. port->open(QIODevice::ReadWrite);
  14967. station = (char)attributes.value("station").toInt();
  14968. if(attributes.value("decimalQuery") == "true")
  14969. {
  14970. decimalPosition = 0;
  14971. QByteArray message;
  14972. message.append(station);
  14973. message.append((char)0x03);
  14974. quint16 address = (quint16)attributes.value("decimalAddress").toInt();
  14975. char *addressBytes = (char*)&address;
  14976. message.append(addressBytes[1]);
  14977. message.append(addressBytes[0]);
  14978. message.append((char)0x00);
  14979. message.append((char)0x01);
  14980. queueMessage(message, this, "decimalResponse(QByteArray)");
  14981. }
  14982. else
  14983. {
  14984. decimalPosition = attributes.value("decimalPosition").toInt();
  14985. }
  14986. valueF = attributes.value("valueF").toInt();
  14987. valueC = attributes.value("valueC").toInt();
  14988. if(attributes.value("unitQuery") == "true")
  14989. {
  14990. QByteArray message;
  14991. message.append(station);
  14992. message.append((char)0x03);
  14993. quint16 address = (quint16)attributes.value("unitAddress").toInt();
  14994. char *addressBytes = (char*)&address;
  14995. message.append(addressBytes[1]);
  14996. message.append(addressBytes[0]);
  14997. message.append((char)0x00);
  14998. message.append((char)0x01);
  14999. queueMessage(message, this, "unitResponse(QByteArray)");
  15000. }
  15001. else
  15002. {
  15003. if(attributes.value("fixedUnit") == "Celsius")
  15004. {
  15005. unitIsF = false;
  15006. }
  15007. }
  15008. if(attributes.value("sVWritable") == "true")
  15009. {
  15010. if(attributes.value("deviceLimit") == "true")
  15011. {
  15012. QByteArray lmessage;
  15013. lmessage.append(station);
  15014. lmessage.append((char)0x03);
  15015. quint16 laddress = (quint16)attributes.value("sVLowerAddr").toInt();
  15016. char *addressBytes = (char*)&laddress;
  15017. lmessage.append(addressBytes[1]);
  15018. lmessage.append(addressBytes[0]);
  15019. lmessage.append((char)0x00);
  15020. lmessage.append((char)0x01);
  15021. queueMessage(lmessage, this, "svlResponse(QByteArray)");
  15022. QByteArray umessage;
  15023. umessage.append(station);
  15024. umessage.append((char)0x03);
  15025. quint16 uaddress = (quint16)attributes.value("sVUpperAddr").toInt();
  15026. addressBytes = (char*)&uaddress;
  15027. umessage.append(addressBytes[1]);
  15028. umessage.append(addressBytes[0]);
  15029. umessage.append((char)0x00);
  15030. umessage.append((char)0x01);
  15031. queueMessage(umessage, this, "svuResponse(QByteArray)");
  15032. }
  15033. else
  15034. {
  15035. outputSVLower = attributes.value("sVLower").toDouble();
  15036. outputSVUpper = attributes.value("sVUpper").toDouble();
  15037. }
  15038. outputSVStub.append(station);
  15039. outputSVStub.append((char)0x06);
  15040. quint16 address = (quint16)attributes.value("sVOutputAddr").toInt();
  15041. char *addressBytes = (char*)&address;
  15042. outputSVStub.append(addressBytes[1]);
  15043. outputSVStub.append(addressBytes[0]);
  15044. }
  15045. Channel *pv = new Channel;
  15046. channels.append(pv);
  15047. pvStub.append(station);
  15048. pvStub.append((char)0x04);
  15049. pvaddress = (quint16)attributes.value("pVAddress").toInt();
  15050. char *pvac = (char*)&pvaddress;
  15051. pvStub.append(pvac[1]);
  15052. pvStub.append(pvac[0]);
  15053. pvStub.append((char)0x00);
  15054. pvStub.append((char)0x01);
  15055. svenabled = attributes.value("sVEnabled").toBool();
  15056. if(svenabled)
  15057. {
  15058. Channel *sv = new Channel;
  15059. channels.append(sv);
  15060. svStub.append(station);
  15061. svStub.append((char)0x04);
  15062. svaddress = (quint16)attributes.value("sVReadAddress").toInt();
  15063. char *svac = (char*)&svaddress;
  15064. svStub.append(svac[1]);
  15065. svStub.append(svac[0]);
  15066. svStub.append((char)0x00);
  15067. svStub.append((char)0x01);
  15068. if(svaddress - pvaddress == 1)
  15069. {
  15070. mStub.append(station);
  15071. mStub.append((char)0x04);
  15072. mStub.append(pvac[1]);
  15073. mStub.append(pvac[0]);
  15074. mStub.append((char)0x00);
  15075. mStub.append((char)0x02);
  15076. }
  15077. }
  15078. connect(this, SIGNAL(queueEmpty()), this, SLOT(requestMeasurement()));
  15079. requestMeasurement();
  15080. }
  15081. double ModbusRTUDevice::SVLower()
  15082. {
  15083. return outputSVLower;
  15084. }
  15085. double ModbusRTUDevice::SVUpper()
  15086. {
  15087. return outputSVUpper;
  15088. }
  15089. int ModbusRTUDevice::decimals()
  15090. {
  15091. return decimalPosition;
  15092. }
  15093. void ModbusRTUDevice::decimalResponse(QByteArray response)
  15094. {
  15095. quint16 temp;
  15096. char *tchar = (char*)&temp;
  15097. tchar[1] = response.at(3);
  15098. tchar[0] = response.at(4);
  15099. decimalPosition = temp;
  15100. emit SVDecimalChanged(decimalPosition);
  15101. qDebug() << "Received decimal response";
  15102. }
  15103. void ModbusRTUDevice::unitResponse(QByteArray response)
  15104. {
  15105. quint16 temp;
  15106. char *tchar = (char*)&temp;
  15107. tchar[1] = response.at(3);
  15108. tchar[0] = response.at(4);
  15109. int value = temp;
  15110. if(value == valueF)
  15111. {
  15112. unitIsF = true;
  15113. }
  15114. else
  15115. {
  15116. unitIsF = false;
  15117. }
  15118. }
  15119. void ModbusRTUDevice::svlResponse(QByteArray response)
  15120. {
  15121. quint16 temp;
  15122. char *tchar = (char*)&temp;
  15123. tchar[1] = response.at(3);
  15124. tchar[0] = response.at(4);
  15125. outputSVLower = (double)temp;
  15126. for(int i = 0; i < decimalPosition; i++)
  15127. {
  15128. outputSVLower /= 10;
  15129. }
  15130. emit SVLowerChanged(outputSVLower);
  15131. }
  15132. void ModbusRTUDevice::svuResponse(QByteArray response)
  15133. {
  15134. quint16 temp;
  15135. char *tchar = (char*)&temp;
  15136. tchar[1] = response.at(3);
  15137. tchar[0] = response.at(4);
  15138. outputSVUpper = (double)temp;
  15139. for(int i = 0; i < decimalPosition; i++)
  15140. {
  15141. outputSVUpper /= 10;
  15142. }
  15143. emit SVUpperChanged(outputSVUpper);
  15144. }
  15145. void ModbusRTUDevice::requestMeasurement()
  15146. {
  15147. if(mStub.length() > 0)
  15148. {
  15149. queueMessage(mStub, this, "mResponse(QByteArray)");
  15150. }
  15151. else
  15152. {
  15153. queueMessage(pvStub, this, "mResponse(QByteArray)");
  15154. if(svenabled)
  15155. {
  15156. queueMessage(svStub, this, "mResponse(QByteArray)");
  15157. }
  15158. }
  15159. }
  15160. void ModbusRTUDevice::mResponse(QByteArray response)
  15161. {
  15162. QTime time = QTime::currentTime();
  15163. if(response.at(2) == 0x04)
  15164. {
  15165. @<Process PV and SV@>@;
  15166. }
  15167. else
  15168. {
  15169. @<Process PV or SV@>@;
  15170. }
  15171. }
  15172. @ There are two ways that we might request measurement data. All of the
  15173. devices I've seen documented provide function 0x4 addresses for PV and SV
  15174. such that SV can be obtained from the address immediately after the address
  15175. from which we obtain PV. In this case we request both values at the same time.
  15176. @<Process PV and SV@>=
  15177. quint16 pv;
  15178. quint16 sv;
  15179. char *pvBytes = (char*)&pv;
  15180. char *svBytes = (char*)&sv;
  15181. pvBytes[1] = response.at(3);
  15182. pvBytes[0] = response.at(4);
  15183. svBytes[1] = response.at(5);
  15184. svBytes[0] = response.at(6);
  15185. double pvOut = (double)pv;
  15186. double svOut = (double)sv;
  15187. for(int i = 0; i < decimalPosition; i++)
  15188. {
  15189. pvOut /= 10;
  15190. svOut /= 10;
  15191. }
  15192. if(!unitIsF)
  15193. {
  15194. pvOut = pvOut * 9 / 5 + 32;
  15195. svOut = svOut * 9 / 5 + 32;
  15196. }
  15197. Measurement pvm(pvOut, time, Measurement::Fahrenheit);
  15198. Measurement svm(svOut, time, Measurement::Fahrenheit);
  15199. channels.at(0)->input(pvm);
  15200. channels.at(1)->input(svm);
  15201. @ When not measuring PV and SV at the same time, there are two possibilities.
  15202. One possibility is that SV is not enabled and we will only be reading from PV.
  15203. The other possibility is that we are alternating between reading PV and SV.
  15204. @<Process PV or SV@>=
  15205. quint16 value;
  15206. char *valueBytes = (char*)&value;
  15207. valueBytes[1] = response.at(3);
  15208. valueBytes[0] = response.at(4);
  15209. double valueOut = (double)value;
  15210. for(int i = 0; i < decimalPosition; i++)
  15211. {
  15212. valueOut /= 10;
  15213. }
  15214. if(!unitIsF)
  15215. {
  15216. valueOut = valueOut * 9 / 5 + 32;
  15217. }
  15218. if(!svenabled)
  15219. {
  15220. Measurement vm(valueOut, time, Measurement::Fahrenheit);
  15221. channels.at(0)->input(vm);
  15222. }
  15223. else
  15224. {
  15225. if(readingsv)
  15226. {
  15227. Measurement pvm(savedpv, time, Measurement::Fahrenheit);
  15228. Measurement svm(valueOut, time, Measurement::Fahrenheit);
  15229. channels.at(0)->input(pvm);
  15230. channels.at(1)->input(svm);
  15231. readingsv = false;
  15232. }
  15233. else
  15234. {
  15235. savedpv = valueOut;
  15236. readingsv = true;
  15237. }
  15238. }
  15239. @ The destructor should close the port.
  15240. @<ModbusRTUDevice implementation@>=
  15241. ModbusRTUDevice::~ModbusRTUDevice()
  15242. {
  15243. messageDelayTimer->stop();
  15244. port->close();
  15245. }
  15246. @ When data is available it should be read into a buffer. The start of the
  15247. buffer should always be the start of a response and there should never be
  15248. more than one response in the buffer at a time. It is, however, likely that
  15249. this buffer will have incomplete data. This means that we must determine when
  15250. the full response is available before passing the complete response along to
  15251. the appropriate method. If the response has not been received in full, nothing
  15252. is done. We'll be notified of more data shortly.
  15253. When the message we see the response for was queued, a callback was also
  15254. registered to handle the response. Once we have the complete message, we pass
  15255. the response along to the callback that was registered for that message,
  15256. remove the message and callback information from the message queue, and start
  15257. a timer which will trigger sending the next message after a safe amount of
  15258. time has passed.
  15259. @<ModbusRTUDevice implementation@>=
  15260. void ModbusRTUDevice::dataAvailable()
  15261. {
  15262. if(messageDelayTimer->isActive())
  15263. {
  15264. messageDelayTimer->stop();
  15265. }
  15266. responseBuffer.append(port->readAll());
  15267. @<Check Modbus RTU message size@>@;
  15268. if(calculateCRC(responseBuffer) == 0)
  15269. {
  15270. QObject *object = retObjQueue.at(0);
  15271. char *method = callbackQueue.at(0);
  15272. QMetaMethod metamethod = object->metaObject()->
  15273. method(object->metaObject()->
  15274. indexOfMethod(QMetaObject::normalizedSignature(method)));
  15275. metamethod.invoke(object, Qt::QueuedConnection,
  15276. Q_ARG(QByteArray, responseBuffer));
  15277. messageQueue.removeAt(0);
  15278. retObjQueue.removeAt(0);
  15279. callbackQueue.removeAt(0);
  15280. messageDelayTimer->start(delayTime);
  15281. }
  15282. else
  15283. {
  15284. qDebug() << "CRC failed";
  15285. }
  15286. waiting = false;
  15287. responseBuffer.clear();
  15288. }
  15289. @ In Modbus RTU, a response message starts with one byte identifying the device
  15290. the message was sent from, one byte indicating the function, a variable number
  15291. of bytes with the response data, and two bytes used to verify that the response
  15292. was correctly received. In the event of a normal response, messages will be at
  15293. least six bytes long, but in the event of an error it is possible for a message
  15294. to be five bytes long.
  15295. Messages with a function number of 0x01 or 0x02 will be 6 bytes in length.
  15296. Messages with a function number of 0x03 or 0x04 will be at least 7 bytes in
  15297. length with the total length determined by the sum of 5 and the value in the
  15298. fifth byte. Messages with a function number of 0x05, 0x06, or 0x10 will be 8
  15299. bytes in length. Messages with a function number greater than 0x80 will be five
  15300. bytes in length.
  15301. @<Check Modbus RTU message size@>=
  15302. if(responseBuffer.size() < 5)
  15303. {
  15304. return;
  15305. }
  15306. switch(responseBuffer.at(1))
  15307. {
  15308. case 0x01:
  15309. case 0x02:
  15310. if(responseBuffer.size() < 6)
  15311. {
  15312. return;
  15313. }
  15314. responseBuffer = responseBuffer.left(6);
  15315. break;
  15316. case 0x03:
  15317. case 0x04:
  15318. if(responseBuffer.size() < 5 + responseBuffer.at(2))
  15319. {
  15320. return;
  15321. }
  15322. responseBuffer = responseBuffer.left(5 + responseBuffer.at(2));
  15323. break;
  15324. case 0x05:
  15325. case 0x06:
  15326. case 0x10:
  15327. if(responseBuffer.size() < 8)
  15328. {
  15329. return;
  15330. }
  15331. responseBuffer = responseBuffer.left(8);
  15332. break;
  15333. }
  15334. @ When sending and receiving messages, it is necessary to calculate a 16 bit
  15335. cyclic redundancy check code. The algorithm used to calculate this is specified
  15336. by the Modbus RTU protocol documentation. When sending a message, |data| should
  15337. be the message to send except for the CRC bytes which will be appended once
  15338. this method calculates them. When receiving a message, passing the complete
  15339. message back through this method should result in a return value of |0|. Any
  15340. other value indicates an error.
  15341. @<ModbusRTUDevice implementation@>=
  15342. quint16 ModbusRTUDevice::calculateCRC(QByteArray data)
  15343. {
  15344. quint16 retval = 0xFFFF;
  15345. int i = 0;
  15346. while(i < data.size())
  15347. {
  15348. retval ^= 0x00FF & (quint16)data.at(i);
  15349. for(int j = 0; j < 8; j++)
  15350. {
  15351. if(retval & 1)
  15352. {
  15353. retval = (retval >> 1) ^ 0xA001;
  15354. }
  15355. else
  15356. {
  15357. retval >>= 1;
  15358. }
  15359. }
  15360. i++;
  15361. }
  15362. return retval;
  15363. }
  15364. @ When preparing an instance of ModbusRTUDevice, several messages may need to
  15365. be sent to the device in order to determine important details such as how
  15366. measurement data should be interpreted. During normal operation, messages
  15367. might be sent interactively between regular messages to acquire data. When
  15368. queueing a message, we also specify an object and method the response should be
  15369. sent to.
  15370. @<ModbusRTUDevice implementation@>=
  15371. void ModbusRTUDevice::queueMessage(QByteArray request, QObject *object,
  15372. const char *callback)
  15373. {
  15374. messageQueue.append(request);
  15375. retObjQueue.append(object);
  15376. callbackQueue.append(const_cast<char*>(callback));
  15377. if(messageQueue.size() == 1 && !(messageDelayTimer->isActive()))
  15378. {
  15379. sendNextMessage();
  15380. }
  15381. }
  15382. void ModbusRTUDevice::sendNextMessage()
  15383. {
  15384. if(messageQueue.size() > 0 && !waiting)
  15385. {
  15386. QByteArray message = messageQueue.at(0);
  15387. quint16 crc = calculateCRC(message);
  15388. char *check = (char*)&crc;
  15389. message.append(check[0]);
  15390. message.append(check[1]);
  15391. port->write(message);
  15392. messageDelayTimer->start(delayTime);
  15393. waiting = true;
  15394. }
  15395. else
  15396. {
  15397. emit queueEmpty();
  15398. }
  15399. }
  15400. void ModbusRTUDevice::outputSV(double value)
  15401. {
  15402. for(int i = 0; i < decimalPosition; i++)
  15403. {
  15404. value *= 10;
  15405. }
  15406. quint16 outval = (quint16)value;
  15407. QByteArray message(outputSVStub);
  15408. char *valBytes = (char*)&outval;
  15409. message.append(valBytes[1]);
  15410. message.append(valBytes[0]);
  15411. queueMessage(message, this, "ignore(QByteArray)");
  15412. }
  15413. @ We don't care about the response when sending a new SV.
  15414. @<ModbusRTUDevice implementation@>=
  15415. void ModbusRTUDevice::ignore(QByteArray)
  15416. {
  15417. return;
  15418. }
  15419. @ This class must be exposed to the host environment.
  15420. @<Function prototypes for scripting@>=
  15421. QScriptValue constructModbusRTUDevice(QScriptContext *context, QScriptEngine *engine);
  15422. QScriptValue ModbusRTUDevice_pVChannel(QScriptContext *context, QScriptEngine *engine);
  15423. QScriptValue ModbusRTUDevice_sVChannel(QScriptContext *context, QScriptEngine *engine);
  15424. void setModbusRTUDeviceProperties(QScriptValue value, QScriptEngine *engine);
  15425. @ The host environment is informed of the constructor.
  15426. @<Set up the scripting engine@>=
  15427. constructor = engine->newFunction(constructModbusRTUDevice);
  15428. value = engine->newQMetaObject(&ModbusRTUDevice::staticMetaObject, constructor);
  15429. engine->globalObject().setProperty("ModbusRTUDevice", value);
  15430. @ The constructor takes the configuration model and the index to the device of
  15431. interest as arguments rather than provide a large number of property setters to
  15432. handle initialization.
  15433. @<Functions for scripting@>=
  15434. QScriptValue constructModbusRTUDevice(QScriptContext *context, QScriptEngine *engine)
  15435. {
  15436. QScriptValue object;
  15437. if(context->argumentCount() == 2)
  15438. {
  15439. object = engine->newQObject(new ModbusRTUDevice(argument<DeviceTreeModel *>(0, context),
  15440. argument<QModelIndex>(1, context)),
  15441. QScriptEngine::ScriptOwnership);
  15442. setModbusRTUDeviceProperties(object, engine);
  15443. }
  15444. else
  15445. {
  15446. context->throwError("Incorrect number of arguments passed to "@|
  15447. "ModbusRTUDevice constructor. This takes the configuration model "@|
  15448. "and an index.");
  15449. }
  15450. return object;
  15451. }
  15452. @ The host environment needs a way to gain access to the channel objects.
  15453. @<Functions for scripting@>=
  15454. QScriptValue ModbusRTUDevice_pVChannel(QScriptContext *context, QScriptEngine *engine)
  15455. {
  15456. ModbusRTUDevice *self = getself<ModbusRTUDevice *>(context);
  15457. QScriptValue object;
  15458. if(self)
  15459. {
  15460. if(self->channels.size() > 0)
  15461. {
  15462. object = engine->newQObject(self->channels.at(0));
  15463. setChannelProperties(object, engine);
  15464. }
  15465. }
  15466. return object;
  15467. }
  15468. QScriptValue ModbusRTUDevice_sVChannel(QScriptContext *context, QScriptEngine *engine)
  15469. {
  15470. ModbusRTUDevice *self = getself<ModbusRTUDevice *>(context);
  15471. QScriptValue object;
  15472. if(self)
  15473. {
  15474. if(self->channels.size() > 1)
  15475. {
  15476. object = engine->newQObject(self->channels.at(1));
  15477. setChannelProperties(object, engine);
  15478. }
  15479. }
  15480. return object;
  15481. }
  15482. @ These methods are set as properties when the object is created.
  15483. @<Functions for scripting@>=
  15484. void setModbusRTUDeviceProperties(QScriptValue value, QScriptEngine *engine)
  15485. {
  15486. setQObjectProperties(value, engine);
  15487. value.setProperty("pVChannel", engine->newFunction(ModbusRTUDevice_pVChannel));
  15488. value.setProperty("sVChannel", engine->newFunction(ModbusRTUDevice_sVChannel));
  15489. }
  15490. @* Modbus RTU device configuration widget.
  15491. \noindent This class was minimally adapted from a prototype implementation to
  15492. use the new configuration system introduced in \pn{} 1.4.
  15493. With all of the custom widgets for specifying a device configuration in place,
  15494. we can proceed to combine these in a form. As all of the options might use more
  15495. screen space than is available we make this scrollable. Some reorganization of
  15496. this will be done prior to release to enable the use of multiple devices on the
  15497. port which may obviate the need for this, but as there are those who prefer to
  15498. have a small screen it may be better to leave the scroll area in place even
  15499. after such a change.
  15500. @<Class declarations@>=
  15501. class ModbusConfigurator : public BasicDeviceConfigurationWidget
  15502. {
  15503. @[Q_OBJECT@]
  15504. public:@/
  15505. Q_INVOKABLE ModbusConfigurator(DeviceTreeModel *model, const QModelIndex &index);
  15506. @[private slots@]:@/
  15507. void updatePort(const QString &newPort);
  15508. void updateBaudRate(const QString &newRate);
  15509. void updateParity(const QString &newParity);
  15510. void updateFlowControl(const QString &newFlow);
  15511. void updateStopBits(const QString &newStopBits);
  15512. void updateStation(int station);
  15513. void updateFixedDecimal(bool fixed);
  15514. void updateDecimalAddress(int address);
  15515. void updateDecimalPosition(int position);
  15516. void updateFixedUnit(bool fixed);
  15517. void updateUnitAddress(int address);
  15518. void updateValueForF(int value);
  15519. void updateValueForC(int value);
  15520. void updateUnit(const QString &newUnit);
  15521. void updatePVAddress(int address);
  15522. void updateSVEnabled(bool enabled);
  15523. void updateSVReadAddress(int address);
  15524. void updateDeviceLimit(bool query);
  15525. void updateSVLowerAddress(int address);
  15526. void updateSVUpperAddress(int address);
  15527. void updateSVLower(double value);
  15528. void updateSVUpper(double value);
  15529. void updateSVWritable(bool canWriteSV);
  15530. void updateSVWriteAddress(int address);
  15531. void updatePVColumnName(const QString &name);
  15532. void updateSVColumnName(const QString &name);
  15533. private:@/
  15534. PortSelector *port;
  15535. BaudSelector *baud;
  15536. ParitySelector *parity;
  15537. FlowSelector *flow;
  15538. StopSelector *stop;
  15539. QSpinBox *station;
  15540. QCheckBox *decimalQuery;
  15541. ShortHexSpinBox *decimalAddress;
  15542. QSpinBox *decimalPosition;
  15543. QCheckBox *unitQuery;
  15544. ShortHexSpinBox *unitAddress;
  15545. QSpinBox *valueF;
  15546. QSpinBox *valueC;
  15547. QComboBox *fixedUnit;
  15548. ShortHexSpinBox *pVAddress;
  15549. QCheckBox *sVEnabled;
  15550. ShortHexSpinBox *sVReadAddress;
  15551. QCheckBox *deviceLimit;
  15552. ShortHexSpinBox *sVLowerAddr;
  15553. ShortHexSpinBox *sVUpperAddr;
  15554. QDoubleSpinBox *sVLower;
  15555. QDoubleSpinBox *sVUpper;
  15556. QCheckBox *sVWritable;
  15557. ShortHexSpinBox *sVOutputAddr;
  15558. QLineEdit *pVColumnName;
  15559. QLineEdit *sVColumnName;
  15560. };
  15561. @ Implementation.
  15562. @<ModbusConfigurator implementation@>=
  15563. ModbusConfigurator::ModbusConfigurator(DeviceTreeModel *model, const QModelIndex &index)
  15564. : BasicDeviceConfigurationWidget(model, index),
  15565. port(new PortSelector), baud(new BaudSelector), parity(new ParitySelector),
  15566. flow(new FlowSelector), stop(new StopSelector), station(new QSpinBox),
  15567. decimalQuery(new QCheckBox(tr("Enable"))),
  15568. decimalAddress(new ShortHexSpinBox), decimalPosition(new QSpinBox),
  15569. unitQuery(new QCheckBox(tr("Enable"))),
  15570. unitAddress(new ShortHexSpinBox), valueF(new QSpinBox),
  15571. valueC(new QSpinBox), fixedUnit(new QComboBox),
  15572. pVAddress(new ShortHexSpinBox),
  15573. sVEnabled(new QCheckBox(tr("Enable"))),
  15574. sVReadAddress(new ShortHexSpinBox),
  15575. deviceLimit(new QCheckBox(tr("Enable"))),
  15576. sVLowerAddr(new ShortHexSpinBox), sVUpperAddr(new ShortHexSpinBox),
  15577. sVLower(new QDoubleSpinBox), sVUpper(new QDoubleSpinBox),
  15578. sVWritable(new QCheckBox(tr("Enable"))),
  15579. sVOutputAddr(new ShortHexSpinBox),
  15580. pVColumnName(new QLineEdit), sVColumnName(new QLineEdit)
  15581. {
  15582. QHBoxLayout *layout = new QHBoxLayout;
  15583. QWidget *form = new QWidget;
  15584. QHBoxLayout *masterLayout = new QHBoxLayout;
  15585. QVBoxLayout *portAndDeviceLayout = new QVBoxLayout;
  15586. QVBoxLayout *seriesLayout = new QVBoxLayout;
  15587. QFormLayout *serialSection = new QFormLayout;
  15588. serialSection->addRow(QString(tr("Port:")), port);
  15589. serialSection->addRow(QString(tr("Baud rate:")), baud);
  15590. serialSection->addRow(QString(tr("Parity:")), parity);
  15591. serialSection->addRow(QString(tr("Flow control:")), flow);
  15592. serialSection->addRow(QString(tr("Stop bits:")), stop);
  15593. QGroupBox *serialSectionBox = new QGroupBox(tr("Serial Port Configuration"));
  15594. serialSectionBox->setLayout(serialSection);
  15595. portAndDeviceLayout->addWidget(serialSectionBox);
  15596. QFormLayout *deviceSection = new QFormLayout;
  15597. station->setMinimum(1);
  15598. station->setMaximum(255);
  15599. decimalPosition->setMinimum(0);
  15600. decimalPosition->setMaximum(9);
  15601. valueF->setMinimum(0);
  15602. valueF->setMaximum(0xFFFF);
  15603. valueC->setMinimum(0);
  15604. valueC->setMaximum(0xFFFF);
  15605. fixedUnit->addItem(tr("Fahrenheit"), QVariant(QString("F")));
  15606. fixedUnit->addItem(tr("Celsius"), QVariant(QString("C")));
  15607. deviceSection->addRow(tr("Station:"), station);
  15608. deviceSection->addRow(tr("Decimal position from device:"), decimalQuery);
  15609. deviceSection->addRow(tr("Decimal position relative address:"), decimalAddress);
  15610. deviceSection->addRow(tr("Fixed decimal position:"), decimalPosition);
  15611. deviceSection->addRow(tr("Measurement unit from device:"), unitQuery);
  15612. deviceSection->addRow(tr("Current unit relative address:"), unitAddress);
  15613. deviceSection->addRow(tr("Value for Fahrenheit:"), valueF);
  15614. deviceSection->addRow(tr("Value for Celsius:"), valueC);
  15615. deviceSection->addRow(tr("Fixed unit:"), fixedUnit);
  15616. QGroupBox *deviceSectionBox = new QGroupBox(tr("Device Configuration"));
  15617. deviceSectionBox->setLayout(deviceSection);
  15618. portAndDeviceLayout->addWidget(deviceSectionBox);
  15619. QFormLayout *pVSection = new QFormLayout;
  15620. pVSection->addRow(tr("Value relative address:"), pVAddress);
  15621. pVSection->addRow(tr("PV column name:"), pVColumnName);
  15622. QGroupBox *processValueBox = new QGroupBox(tr("Process Value"));
  15623. processValueBox->setLayout(pVSection);
  15624. seriesLayout->addWidget(processValueBox);
  15625. QFormLayout *sVSection = new QFormLayout;
  15626. sVLower->setDecimals(1);
  15627. sVLower->setMinimum(0.0);
  15628. sVLower->setMaximum(999.9);
  15629. sVUpper->setDecimals(1);
  15630. sVUpper->setMinimum(0.0);
  15631. sVUpper->setMaximum(999.9);
  15632. sVSection->addRow(tr("Set value:"), sVEnabled);
  15633. sVSection->addRow(tr("Read relative address:"), sVReadAddress);
  15634. sVSection->addRow(tr("SV column name:"), sVColumnName);
  15635. sVSection->addRow(tr("Limits from device:"), deviceLimit);
  15636. sVSection->addRow(tr("Lower limit relative address:"), sVLowerAddr);
  15637. sVSection->addRow(tr("Upper limit relative address:"), sVUpperAddr);
  15638. sVSection->addRow(tr("Lower limit:"), sVLower);
  15639. sVSection->addRow(tr("Upper limit:"), sVUpper);
  15640. sVSection->addRow(tr("Output set value:"), sVWritable);
  15641. sVSection->addRow(tr("Output relative address:"), sVOutputAddr);
  15642. QGroupBox *setValueBox = new QGroupBox(tr("Set Value"));
  15643. setValueBox->setLayout(sVSection);
  15644. seriesLayout->addWidget(setValueBox);
  15645. masterLayout->addLayout(portAndDeviceLayout);
  15646. masterLayout->addLayout(seriesLayout);
  15647. form->setLayout(masterLayout);
  15648. @<Get device configuration data for current node@>@;
  15649. for(int i = 0; i < configData.size(); i++)
  15650. {
  15651. node = configData.at(i).toElement();
  15652. if(node.attribute("name") == "port")
  15653. {
  15654. QString portname = node.attribute("value");
  15655. int idx = port->findText(portname);
  15656. if(idx >= 0)
  15657. {
  15658. port->setCurrentIndex(idx);
  15659. }
  15660. else
  15661. {
  15662. port->addItem(portname);
  15663. }
  15664. }
  15665. else if(node.attribute("name") == "baud")
  15666. {
  15667. baud->setCurrentIndex(baud->findText(node.attribute("value")));
  15668. }
  15669. else if(node.attribute("name") == "parity")
  15670. {
  15671. parity->setCurrentIndex(parity->findData(node.attribute("value")));
  15672. }
  15673. else if(node.attribute("name") == "flow")
  15674. {
  15675. flow->setCurrentIndex(flow->findData(node.attribute("value")));
  15676. }
  15677. else if(node.attribute("name") == "stop")
  15678. {
  15679. stop->setCurrentIndex(stop->findData(node.attribute("value")));
  15680. }
  15681. else if(node.attribute("name") == "station")
  15682. {
  15683. station->setValue(node.attribute("value").toInt());
  15684. }
  15685. else if(node.attribute("name") == "decimalQuery")
  15686. {
  15687. if(node.attribute("value") == "true")
  15688. {
  15689. decimalQuery->setChecked(true);
  15690. }
  15691. else
  15692. {
  15693. decimalQuery->setChecked(false);
  15694. }
  15695. }
  15696. else if(node.attribute("name") == "decimalAddress")
  15697. {
  15698. decimalAddress->setValue(node.attribute("value").toInt());
  15699. }
  15700. else if(node.attribute("name") == "decimalPosition")
  15701. {
  15702. decimalPosition->setValue(node.attribute("value").toInt());
  15703. }
  15704. else if(node.attribute("name") == "unitQuery")
  15705. {
  15706. if(node.attribute("value") == "true")
  15707. {
  15708. unitQuery->setChecked(true);
  15709. }
  15710. else
  15711. {
  15712. unitQuery->setChecked(false);
  15713. }
  15714. }
  15715. else if(node.attribute("name") == "unitAddress")
  15716. {
  15717. unitAddress->setValue(node.attribute("value").toInt());
  15718. }
  15719. else if(node.attribute("name") == "valueF")
  15720. {
  15721. valueF->setValue(node.attribute("value").toInt());
  15722. }
  15723. else if(node.attribute("name") == "valueC")
  15724. {
  15725. valueC->setValue(node.attribute("value").toInt());
  15726. }
  15727. else if(node.attribute("name") == "fixedUnit")
  15728. {
  15729. fixedUnit->setCurrentIndex(fixedUnit->findText(node.attribute("value")));
  15730. }
  15731. else if(node.attribute("name") == "pVAddress")
  15732. {
  15733. pVAddress->setValue(node.attribute("value").toInt());
  15734. }
  15735. else if(node.attribute("name") == "sVEnabled")
  15736. {
  15737. if(node.attribute("value") == "true")
  15738. {
  15739. sVEnabled->setChecked(true);
  15740. }
  15741. else
  15742. {
  15743. sVEnabled->setChecked(false);
  15744. }
  15745. }
  15746. else if(node.attribute("name") == "sVReadAddress")
  15747. {
  15748. sVReadAddress->setValue(node.attribute("value").toInt());
  15749. }
  15750. else if(node.attribute("name") == "deviceLimit")
  15751. {
  15752. if(node.attribute("value") == "true")
  15753. {
  15754. deviceLimit->setChecked(true);
  15755. }
  15756. else
  15757. {
  15758. deviceLimit->setChecked(false);
  15759. }
  15760. }
  15761. else if(node.attribute("name") == "sVLowerAddr")
  15762. {
  15763. sVLowerAddr->setValue(node.attribute("value").toInt());
  15764. }
  15765. else if(node.attribute("name") == "sVUpperAddr")
  15766. {
  15767. sVUpperAddr->setValue(node.attribute("value").toInt());
  15768. }
  15769. else if(node.attribute("name") == "sVLower")
  15770. {
  15771. sVLower->setValue(node.attribute("value").toDouble());
  15772. }
  15773. else if(node.attribute("name") == "sVUpper")
  15774. {
  15775. sVUpper->setValue(node.attribute("value").toDouble());
  15776. }
  15777. else if(node.attribute("name") == "sVWritable")
  15778. {
  15779. if(node.attribute("value") == "true")
  15780. {
  15781. sVWritable->setChecked(true);
  15782. }
  15783. else
  15784. {
  15785. sVWritable->setChecked(false);
  15786. }
  15787. }
  15788. else if(node.attribute("name") == "sVOutputAddr")
  15789. {
  15790. sVOutputAddr->setValue(node.attribute("value").toInt());
  15791. }
  15792. else if(node.attribute("name") == "pvcolname")
  15793. {
  15794. pVColumnName->setText(node.attribute("value"));
  15795. }
  15796. else if(node.attribute("name") == "svcolname")
  15797. {
  15798. sVColumnName->setText(node.attribute("value"));
  15799. }
  15800. }
  15801. updatePort(port->currentText());
  15802. updateBaudRate(baud->currentText());
  15803. updateParity(parity->itemData(parity->currentIndex()).toString());
  15804. updateFlowControl(flow->itemData(flow->currentIndex()).toString());
  15805. updateStopBits(stop->itemData(stop->currentIndex()).toString());
  15806. updateStation(station->value());
  15807. updateFixedDecimal(decimalQuery->isChecked());
  15808. updateDecimalAddress(decimalAddress->value());
  15809. updateDecimalPosition(decimalPosition->value());
  15810. updateFixedUnit(unitQuery->isChecked());
  15811. updateUnitAddress(unitAddress->value());
  15812. updateValueForF(valueF->value());
  15813. updateValueForC(valueC->value());
  15814. updateUnit(fixedUnit->currentText());
  15815. updatePVAddress(pVAddress->value());
  15816. updateSVEnabled(sVEnabled->isChecked());
  15817. updateSVReadAddress(sVReadAddress->value());
  15818. updateDeviceLimit(deviceLimit->isChecked());
  15819. updateSVLowerAddress(sVLowerAddr->value());
  15820. updateSVUpperAddress(sVUpperAddr->value());
  15821. updateSVLower(sVLower->value());
  15822. updateSVUpper(sVUpper->value());
  15823. updateSVWritable(sVWritable->isChecked());
  15824. updateSVWriteAddress(sVOutputAddr->value());
  15825. updatePVColumnName(pVColumnName->text());
  15826. updateSVColumnName(sVColumnName->text());
  15827. connect(port, SIGNAL(currentIndexChanged(QString)), this, SLOT(updatePort(QString)));
  15828. connect(port, SIGNAL(editTextChanged(QString)), this, SLOT(updatePort(QString)));
  15829. connect(baud, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateBaudRate(QString)));
  15830. connect(parity, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateParity(QString)));
  15831. connect(flow, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateFlowControl(QString)));
  15832. connect(stop, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateStopBits(QString)));
  15833. connect(station, SIGNAL(valueChanged(int)), this, SLOT(updateStation(int)));
  15834. connect(decimalQuery, SIGNAL(toggled(bool)), this, SLOT(updateFixedDecimal(bool)));
  15835. connect(decimalAddress, SIGNAL(valueChanged(int)), this, SLOT(updateDecimalAddress(int)));
  15836. connect(decimalPosition, SIGNAL(valueChanged(int)), this, SLOT(updateDecimalPosition(int)));
  15837. connect(unitQuery, SIGNAL(toggled(bool)), this, SLOT(updateFixedUnit(bool)));
  15838. connect(unitAddress, SIGNAL(valueChanged(int)), this, SLOT(updateUnitAddress(int)));
  15839. connect(valueF, SIGNAL(valueChanged(int)), this, SLOT(updateValueForF(int)));
  15840. connect(valueC, SIGNAL(valueChanged(int)), this, SLOT(updateValueForC(int)));
  15841. connect(fixedUnit, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateUnit(QString)));
  15842. connect(pVAddress, SIGNAL(valueChanged(int)), this, SLOT(updatePVAddress(int)));
  15843. connect(sVEnabled, SIGNAL(toggled(bool)), this, SLOT(updateSVEnabled(bool)));
  15844. connect(sVReadAddress, SIGNAL(valueChanged(int)), this, SLOT(updateSVReadAddress(int)));
  15845. connect(deviceLimit, SIGNAL(toggled(bool)), this, SLOT(updateDeviceLimit(bool)));
  15846. connect(sVLowerAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVLowerAddress(int)));
  15847. connect(sVUpperAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVUpperAddress(int)));
  15848. connect(sVLower, SIGNAL(valueChanged(double)), this, SLOT(updateSVLower(double)));
  15849. connect(sVUpper, SIGNAL(valueChanged(double)), this, SLOT(updateSVUpper(double)));
  15850. connect(sVWritable, SIGNAL(toggled(bool)), this, SLOT(updateSVWritable(bool)));
  15851. connect(sVOutputAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVWriteAddress(int)));
  15852. connect(pVColumnName, SIGNAL(textEdited(QString)), this, SLOT(updatePVColumnName(QString)));
  15853. connect(sVColumnName, SIGNAL(textEdited(QString)), this, SLOT(updateSVColumnName(QString)));
  15854. layout->addWidget(form);
  15855. setLayout(layout);
  15856. }
  15857. void ModbusConfigurator::updatePort(const QString &newPort)
  15858. {
  15859. updateAttribute("port", newPort);
  15860. }
  15861. void ModbusConfigurator::updateBaudRate(const QString &newRate)
  15862. {
  15863. updateAttribute("baud", newRate);
  15864. }
  15865. void ModbusConfigurator::updateParity(const QString &)
  15866. {
  15867. updateAttribute("parity", parity->itemData(parity->currentIndex()).toString());
  15868. }
  15869. void ModbusConfigurator::updateFlowControl(const QString &)
  15870. {
  15871. updateAttribute("flow", flow->itemData(flow->currentIndex()).toString());
  15872. }
  15873. void ModbusConfigurator::updateStopBits(const QString &)
  15874. {
  15875. updateAttribute("stop", stop->itemData(stop->currentIndex()).toString());
  15876. }
  15877. void ModbusConfigurator::updateStation(int station)
  15878. {
  15879. updateAttribute("station", QString("%1").arg(station));
  15880. }
  15881. void ModbusConfigurator::updateFixedDecimal(bool fixed)
  15882. {
  15883. updateAttribute("decimalQuery", fixed ? "true" : "false");
  15884. }
  15885. void ModbusConfigurator::updateDecimalAddress(int address)
  15886. {
  15887. updateAttribute("decimalAddress", QString("%1").arg(address));
  15888. }
  15889. void ModbusConfigurator::updateDecimalPosition(int position)
  15890. {
  15891. updateAttribute("decimalPosition", QString("%1").arg(position));
  15892. }
  15893. void ModbusConfigurator::updateFixedUnit(bool fixed)
  15894. {
  15895. updateAttribute("unitQuery", fixed ? "true" : "false");
  15896. }
  15897. void ModbusConfigurator::updateUnitAddress(int address)
  15898. {
  15899. updateAttribute("unitAddress", QString("%1").arg(address));
  15900. }
  15901. void ModbusConfigurator::updateValueForF(int value)
  15902. {
  15903. updateAttribute("valueF", QString("%1").arg(value));
  15904. }
  15905. void ModbusConfigurator::updateValueForC(int value)
  15906. {
  15907. updateAttribute("valueC", QString("%1").arg(value));
  15908. }
  15909. void ModbusConfigurator::updateUnit(const QString &newUnit)
  15910. {
  15911. updateAttribute("fixedUnit", newUnit);
  15912. }
  15913. void ModbusConfigurator::updatePVAddress(int address)
  15914. {
  15915. updateAttribute("pVAddress", QString("%1").arg(address));
  15916. }
  15917. void ModbusConfigurator::updateSVEnabled(bool enabled)
  15918. {
  15919. updateAttribute("sVEnabled", enabled ? "true" : "false");
  15920. }
  15921. void ModbusConfigurator::updateSVReadAddress(int address)
  15922. {
  15923. updateAttribute("sVReadAddress", QString("%1").arg(address));
  15924. }
  15925. void ModbusConfigurator::updateDeviceLimit(bool query)
  15926. {
  15927. updateAttribute("deviceLimit", query ? "true" : "false");
  15928. }
  15929. void ModbusConfigurator::updateSVLowerAddress(int address)
  15930. {
  15931. updateAttribute("sVLowerAddr", QString("%1").arg(address));
  15932. }
  15933. void ModbusConfigurator::updateSVUpperAddress(int address)
  15934. {
  15935. updateAttribute("sVUpperAddr", QString("%1").arg(address));
  15936. }
  15937. void ModbusConfigurator::updateSVLower(double value)
  15938. {
  15939. updateAttribute("sVLower", QString("%1").arg(value));
  15940. }
  15941. void ModbusConfigurator::updateSVUpper(double value)
  15942. {
  15943. updateAttribute("sVUpper", QString("%1").arg(value));
  15944. }
  15945. void ModbusConfigurator::updateSVWritable(bool canWriteSV)
  15946. {
  15947. updateAttribute("sVWritable", canWriteSV ? "true" : "false");
  15948. }
  15949. void ModbusConfigurator::updateSVWriteAddress(int address)
  15950. {
  15951. updateAttribute("sVOutputAddr", QString("%1").arg(address));
  15952. }
  15953. void ModbusConfigurator::updatePVColumnName(const QString &name)
  15954. {
  15955. updateAttribute("pvcolname", name);
  15956. }
  15957. void ModbusConfigurator::updateSVColumnName(const QString &name)
  15958. {
  15959. updateAttribute("svcolname", name);
  15960. }
  15961. @ This is registered with the configuration system.
  15962. @<Register device configuration widgets@>=
  15963. app.registerDeviceConfigurationWidget("modbusrtu", ModbusConfigurator::staticMetaObject);
  15964. @ A |NodeInserter| for the driver configuration widget is also needed.
  15965. @<Register top level device configuration nodes@>=
  15966. inserter = new NodeInserter(tr("Modbus RTU Device"), tr("Modbus RTU Device"), "modbusrtu", NULL);
  15967. topLevelNodeInserters.append(inserter);
  15968. @* Configuration widget for a calibrated data series.
  15969. \noindent This control is used for adding a |LinearSplineInterpolator| to the
  15970. logging view.
  15971. @<Class declarations@>=
  15972. class LinearSplineInterpolationConfWidget : public BasicDeviceConfigurationWidget
  15973. {
  15974. @[Q_OBJECT@]@/
  15975. public:@/
  15976. @[Q_INVOKABLE@]@, LinearSplineInterpolationConfWidget(DeviceTreeModel *model,
  15977. const QModelIndex &index);
  15978. @[private slots@]:@/
  15979. void updateSourceColumn(const QString &source);
  15980. void updateDestinationColumn(const QString &dest);
  15981. void updateKnots();
  15982. private:@/
  15983. SaltModel *knotmodel;
  15984. };
  15985. @ This is configured by specifying a source column name, a destination column
  15986. name, and a two column table. Note that while we only have one widget handling
  15987. the mapping data, we store each column of the table in its own attribute.
  15988. @<LinearSplineInterpolationConfWidget implementation@>=
  15989. LinearSplineInterpolationConfWidget::LinearSplineInterpolationConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  15990. : BasicDeviceConfigurationWidget(model, index), knotmodel(new SaltModel(2))
  15991. {
  15992. QFormLayout *layout = new QFormLayout;
  15993. QLineEdit *source = new QLineEdit;
  15994. layout->addRow(tr("Source column name:"), source);
  15995. QLineEdit *destination = new QLineEdit;
  15996. layout->addRow(tr("Destination column name:"), destination);
  15997. knotmodel->setHeaderData(0, Qt::Horizontal, "Input");
  15998. knotmodel->setHeaderData(1, Qt::Horizontal, "Output");
  15999. QTableView *mappingTable = new QTableView;
  16000. mappingTable->setModel(knotmodel);
  16001. NumericDelegate *delegate = new NumericDelegate;
  16002. mappingTable->setItemDelegate(delegate);
  16003. layout->addRow(tr("Mapping data:"), mappingTable);
  16004. @<Get device configuration data for current node@>@;
  16005. for(int i = 0; i < configData.size(); i++)
  16006. {
  16007. node = configData.at(i).toElement();
  16008. if(node.attribute("name") == "source")
  16009. {
  16010. source->setText(node.attribute("value"));
  16011. }
  16012. else if(node.attribute("name") == "destination")
  16013. {
  16014. destination->setText(node.attribute("value"));
  16015. }
  16016. else if(node.attribute("name") == "sourcevalues")
  16017. {
  16018. @<Convert numeric array literal to list@>@;
  16019. int column = 0;
  16020. @<Populate model column from list@>@;
  16021. }
  16022. else if(node.attribute("name") == "destinationvalues")
  16023. {
  16024. @<Convert numeric array literal to list@>@;
  16025. int column = 1;
  16026. @<Populate model column from list@>@;
  16027. }
  16028. }
  16029. updateSourceColumn(source->text());
  16030. updateDestinationColumn(destination->text());
  16031. updateKnots();
  16032. connect(source, SIGNAL(textEdited(QString)), this, SLOT(updateSourceColumn(QString)));
  16033. connect(destination, SIGNAL(textEdited(QString)), this, SLOT(updateDestinationColumn(QString)));
  16034. connect(knotmodel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(updateKnots()));
  16035. setLayout(layout);
  16036. }
  16037. @ The saved data will have come from a previous call to
  16038. |SaltModel::arrayLiteral()| to repopulate the model we need to strip off the
  16039. the start and end of the strings and split them back into separate elements.
  16040. @<Convert numeric array literal to list@>=
  16041. QString data = node.attribute("value");
  16042. if(data.length() > 3)
  16043. {
  16044. data.chop(2);
  16045. data = data.remove(0, 2);
  16046. }
  16047. QStringList itemList = data.split(",");
  16048. @ Once the saved string has been split, the values can be inserted into the
  16049. model.
  16050. @<Populate model column from list@>=
  16051. for(int i = 0; i < itemList.size(); i++)
  16052. {
  16053. knotmodel->setData(knotmodel->index(i, column),
  16054. QVariant(itemList.at(i).toDouble()),
  16055. Qt::DisplayRole);
  16056. }
  16057. @ When data in the table is changed we simply overwrite any previously saved
  16058. data with the current data.
  16059. @<LinearSplineInterpolationConfWidget implementation@>=
  16060. void LinearSplineInterpolationConfWidget::updateKnots()
  16061. {
  16062. updateAttribute("sourcevalues", knotmodel->arrayLiteral(0, Qt::DisplayRole));
  16063. updateAttribute("destinationvalues", knotmodel->arrayLiteral(1, Qt::DisplayRole));
  16064. }
  16065. void LinearSplineInterpolationConfWidget::updateSourceColumn(const QString &source)
  16066. {
  16067. updateAttribute("source", source);
  16068. }
  16069. void LinearSplineInterpolationConfWidget::updateDestinationColumn(const QString &dest)
  16070. {
  16071. updateAttribute("destination", dest);
  16072. }
  16073. @ The widget is registered with the configuration system.
  16074. @<Register device configuration widgets@>=
  16075. app.registerDeviceConfigurationWidget("linearspline", LinearSplineInterpolationConfWidget::staticMetaObject);
  16076. @* Profile Translation Configuration Widget.
  16077. \noindent Configuring profile translation requires knowing which column to use
  16078. for matching purposes and the value to match.
  16079. @<Class declarations@>=
  16080. class TranslationConfWidget : public BasicDeviceConfigurationWidget
  16081. {
  16082. @[Q_OBJECT@]@;
  16083. public:@/
  16084. @[Q_INVOKABLE@]@, TranslationConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  16085. @[private slots@]:@/
  16086. void updateMatchingColumn(const QString &column);
  16087. void updateTemperature();
  16088. private:@/
  16089. QDoubleSpinBox *temperatureValue;
  16090. QComboBox *unitSelector;
  16091. };
  16092. @ The constructor sets up our user interface.
  16093. @<TranslationConfWidget implementation@>=
  16094. TranslationConfWidget::TranslationConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  16095. : BasicDeviceConfigurationWidget(model, index),
  16096. temperatureValue(new QDoubleSpinBox), unitSelector(new QComboBox)
  16097. {
  16098. unitSelector->addItem("Fahrenheit");
  16099. unitSelector->addItem("Celsius");
  16100. temperatureValue->setMinimum(0);
  16101. temperatureValue->setMaximum(1000);
  16102. QFormLayout *layout = new QFormLayout;
  16103. QLineEdit *column = new QLineEdit;
  16104. layout->addRow(tr("Column to match:"), column);
  16105. layout->addRow(tr("Unit:"), unitSelector);
  16106. layout->addRow(tr("Value:"), temperatureValue);
  16107. @<Get device configuration data for current node@>@;
  16108. for(int i = 0; i < configData.size(); i++)
  16109. {
  16110. node = configData.at(i).toElement();
  16111. if(node.attribute("name") == "column")
  16112. {
  16113. column->setText(node.attribute("value"));
  16114. }
  16115. else if(node.attribute("name") == "unit")
  16116. {
  16117. unitSelector->setCurrentIndex(unitSelector->findText(node.attribute("value")));
  16118. }
  16119. else if(node.attribute("name") == "value")
  16120. {
  16121. temperatureValue->setValue(node.attribute("value").toDouble());
  16122. }
  16123. }
  16124. updateMatchingColumn(column->text());
  16125. updateTemperature();
  16126. connect(column, SIGNAL(textEdited(QString)), this, SLOT(updateMatchingColumn(QString)));
  16127. connect(unitSelector, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateTemperature()));
  16128. connect(temperatureValue, SIGNAL(valueChanged(double)), this, SLOT(updateTemperature()));
  16129. setLayout(layout);
  16130. }
  16131. @ To update the temperature at which to match we save both the values of the
  16132. two widgets which control this and the value in Fahrenheit so we don't need to
  16133. run unit conversions during view initialization.
  16134. @<TranslationConfWidget implementation@>=
  16135. void TranslationConfWidget::updateTemperature()
  16136. {
  16137. updateAttribute("unit", unitSelector->currentText());
  16138. updateAttribute("value", QString("%1").arg(temperatureValue->value()));
  16139. if(unitSelector->currentText() == "Fahrenheit")
  16140. {
  16141. updateAttribute("FValue", QString("%1").arg(temperatureValue->value()));
  16142. }
  16143. else
  16144. {
  16145. updateAttribute("FValue", QString("%1").arg(temperatureValue->value() * 9 / 5 + 32));
  16146. }
  16147. }
  16148. void TranslationConfWidget::updateMatchingColumn(const QString &column)
  16149. {
  16150. updateAttribute("column", column);
  16151. }
  16152. @ This is registered with the configuration system.
  16153. @<Register device configuration widgets@>=
  16154. app.registerDeviceConfigurationWidget("translation", TranslationConfWidget::staticMetaObject);
  16155. @** Local changes.
  16156. \noindent This is the end of \pn{} as distributed by its author. It is expected
  16157. that some might have need of a program like \pn, but require some modification.
  16158. The patching capabilities of \cweb{} can be used to produce these local
  16159. modifications. This section is provided for those whose change requirements are
  16160. sufficiently extensive to require the introduction of new sections to the
  16161. program.
  16162. @** Index.
  16163. \noindent Following is a list of identifiers used in \pn, with underlined
  16164. entries pointing to where \cweb{} has guessed that the identifier was defined.
  16165. All references are to section numbers instead of page numbers.
  16166. \def\nullsec{--}