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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491
  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.9.0 \number\year-\number\month-\number\day}
  25. \def\years{2007--2017}
  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}}@q'@> (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. @** Introduction.
  415. \noindent A common tool in the craft of coffee roasting is the data logger.
  416. Perhaps the most commonly used of these fall into the category of manual data
  417. loggers which require the roaster to use paper and a writing utensil,
  418. periodically recording measurements and noting control changes and observations
  419. of interest as needed.
  420. While there are many benefits to recording roast data\nfnote{Torrey Lee, Stephan
  421. Diedrich, Carl Staub, and Jack Newall, ``How to Obtain Excellence with Drum
  422. Roasters'' (2002) {\it Specialty Coffee Association of America 14$^{th}$ Annual
  423. Conference and Exhibition}}, there are a number of limitations to the manual
  424. approach; maintaining the records in a useful order is time consuming and error
  425. prone, it is difficult to work with aggregates of such records, and the
  426. attention required to log the data by hand can distract from the roasting. Using
  427. a computer with automatic data logging software designed with coffee roasting in
  428. mind can reduce or eliminate these deficiencies. \pn{} is one such program.
  429. The file {\tt \filebase.w} contains both \CPLUSPLUS/source code and the
  430. documentation for that code. This file is intended to be processed by
  431. \cweb\nfnote{Donald E. Knuth and Silvio Levy, ``The \cweb{} System of Structured
  432. Documentation'' (1994)}~to produce source code for your compiler and plain
  433. \TeX{}\nfnote{\TeX{} (pronounced $\tau\epsilon\chi$) is a trademark of the
  434. American Mathematical Society.} documentation that can be used to generate a PDF
  435. document for gorgeous printable documentation. These generated files may have
  436. been distributed with your copy of {\tt \filebase.w} for convenience.
  437. Changes to the program can be made in three ways. \cweb{} provides a patching
  438. mechanism which can be used to experiment with the code without risk of
  439. clobbering it. Instructions for the construction of such a change file can be
  440. found in the \cweb{} documentation. Adding the name of the change file to the
  441. invocation of {\tt ctangle} and {\tt cweave} will incorporate that change
  442. seamlessly in both source and documentation files. A section is provided at the
  443. end of this program for use with this mechanism in the case that new sections
  444. must be added. Another way to create persistent modifications is to alter
  445. {\tt \filebase.w} however this may make it more difficult to use changes with
  446. future versions of the software. Changes should not be made to
  447. {\tt \filebase.cpp} if these changes are expected to persist. Finally, it is
  448. possible to make many changes to how the program looks and behaves by creating a
  449. new configuration document for the program to load. Modifications made in this
  450. way do not even require recompiling the software. Examples that can serve as a
  451. starting point for such customizations are provided with \pn{}.
  452. \pn{} is a work in progress. There are several portions of the documentation
  453. that contain suggestions for future improvement. These notes provide clues for
  454. my future development plans. Naturally, if you have needs which are not quite
  455. addressed by this program, you should feel free to modify the code to suit your
  456. needs. Hopefully this will be easy to do.
  457. In the spirit of Benjamin Franklin\nfnote{``\dots as we enjoy great advantages
  458. from the inventions of others, we should be glad of an opportunity to serve
  459. others by any invention of ours; and this we should do freely and
  460. generously.''
  461. --- Benjamin Franklin, \underbar{The Private Life of the Late
  462. Benjamin Franklin, LL.D.~Originally
  463. Written By Himself, And Now}\par\noindent
  464. \underbar{Translated From The French} (1793)}, \pn{} is shared
  465. with minimal restriction (see the license after the table of contents for legal
  466. requirements). Libraries used by \pn{} may have other restrictions. Before
  467. undertaking to distribute a binary created from this code, you may want to
  468. either determine your rights with regard to these libraries or modify the
  469. program to remove them.
  470. As CWEB generates files with the wrong extension, we leave the default
  471. generated file empty.
  472. @c
  473. /* Nothing to see here. */
  474. @ The following is an overview of the structure of \pn:
  475. @(typica.cpp@>=
  476. #define PROGRAM_NAME "Typica"
  477. @<Header files to include@>@/
  478. @<Additional type definitions@>@/
  479. @<Additional function prototypes@>@/
  480. @<Class declarations@>@/
  481. @<Additional functions@>@/
  482. @<Function prototypes for scripting@>@/
  483. @<Logging function prototype@>@/
  484. @<Class implementations@>@/
  485. @<Functions for scripting@>@/
  486. @<Logging function implementation@>@/
  487. @<The main program@>
  488. #include "moc_typica.cpp"
  489. @ \pn{} is made of a number of distinct classes.
  490. @<Class implementations@>=
  491. @<NodeInserter implementation@>@/
  492. @<Measurement implementation@>@/
  493. @<DAQ Implementation@>@/
  494. @<DataqSdkDevice implementation@>@/
  495. @<FakeDAQ Implementation@>@/
  496. @<Channel Implementation@>@/
  497. @<TemperatureDisplay Implementation@>@/
  498. @<MeasurementTimeOffset Implementation@>@/
  499. @<ZeroEmitter Implementation@>@/
  500. @<MeasurementAdapter Implementation@>@/
  501. @<GraphView Implementation@>@/
  502. @<ZoomLog Implementation@>@/
  503. @<MeasurementModel Implementation@>@/
  504. @<AnnotationButton Implementation@>@/
  505. @<AnnotationSpinBox Implementation@>@/
  506. @<TimerDisplay Implementation@>@/
  507. @<PackLayout Implementation@>@/
  508. @<SceneButton Implementation@>@/
  509. @<WidgetDecorator Implementation@>@/
  510. @<LogEditWindow Implementation@>@/
  511. @<XMLOutput Implementation@>@/
  512. @<XMLInput Implementation@>@/
  513. @<CSVOutput Implementation@>@/
  514. @<SaltModel Implementation@>@/
  515. @<SqlComboBox Implementation@>@/
  516. @<SqlComboBoxDelegate Implementation@>@/
  517. @<Application Implementation@>@/
  518. @<SqlConnectionSetup implementation@>@/
  519. @<SqlQueryView implementation@>@/
  520. @<SqlQueryConnection implementation@>@/
  521. @<ReportTable implementation@>@/
  522. @<FormArray implementation@>@/
  523. @<ScaleControl implementation@>@/
  524. @<IntensityControl implementation@>@/
  525. @<ThresholdDetector Implementation@>@/
  526. @<PortSelector implementation@>@/
  527. @<BaudSelector implementation@>@/
  528. @<ParitySelector implementation@>@/
  529. @<FlowSelector implementation@>@/
  530. @<StopSelector implementation@>@/
  531. @<ModbusConfigurator implementation@>@/
  532. @<ShortHexSpinBox implementation@>@/
  533. @<ModbusRTUDevice implementation@>@/
  534. @<DeviceTreeModelNode implementation@>@/
  535. @<DeviceTreeModel implementation@>@/
  536. @<BasicDeviceConfigurationWidget implementation@>@/
  537. @<DeviceConfigurationWindow implementation@>@/
  538. @<Ni9211TcConfWidget implementation@>@/
  539. @<NiDaqMxBase9211ConfWidget implementation@>@/
  540. @<NiDaqMxBaseDriverConfWidget implementation@>@/
  541. @<ReportAction implementation@>@/
  542. @<NumericDelegate implementation@>@/
  543. @<NiDaqMxDriverConfWidget implementation@>@/
  544. @<NiDaqMx9211ConfWidget implementation@>@/
  545. @<NiDaqMxTc01ConfWidget implementation@>@/
  546. @<ModbusRtuPortConfWidget implementation@>@/
  547. @<ModbusRtuDeviceConfWidget implementation@>@/
  548. @<ModbusRtuDeviceTPvConfWidget implementation@>@/
  549. @<ModbusRtuDeviceTSvConfWidget implementation@>@/
  550. @<RoasterConfWidget implementation@>@/
  551. @<AnnotationButtonConfWidget implementation@>@/
  552. @<NoteSpinConfWidget implementation@>@/
  553. @<LinearCalibrator Implementation@>@/
  554. @<LinearSplineInterpolator Implementation@>@/
  555. @<LinearSplineInterpolationConfWidget implementation@>@/
  556. @<TranslationConfWidget implementation@>@/
  557. @<FreeAnnotationConfWidget implementation@>@/
  558. @<RateOfChange implementation@>@/
  559. @<SettingsWindow implementation@>@/
  560. @<GraphSettingsWidget implementation@>@/
  561. @<DataqSdkDeviceConfWidget implementation@>@/
  562. @<SerialScaleConfWidget implementation@>@/
  563. @<ValueAnnotation implementation@>@/
  564. @<ValueAnnotationConfWidget implementation@>@/
  565. @<ModbusNG implementation@>@/
  566. @<ThresholdAnnotationConfWidget implementation@>@/
  567. @<Annotator implementation@>@/
  568. @ A few headers are required for various parts of \pn{}. These allow the use of
  569. various Qt modules.
  570. @<Header files to include@>=
  571. #include <QtCore>
  572. #include <QtGui>
  573. #include <QtScript>
  574. #include <QtScriptTools>
  575. #include <QtXml>
  576. #include <QtSql>
  577. #include <QtDebug>
  578. #include <QtXmlPatterns>
  579. #include <QtWebKit>
  580. #include <QtSvg>
  581. #include <QtNetwork>
  582. @ New code is being written in separate files in a long term effort to improve
  583. organization of the code. The result of this is that some additional headers
  584. are required here.
  585. @<Header files to include@>=
  586. #include "helpmenu.h"
  587. @** The Scripting Engine.
  588. \noindent The main enhancement of \pn{} version 1.1 is the introduction of a
  589. scriptable environment. This change allows people to easily customize \pn{}
  590. without having to alter the program code. Instead, the user interface and
  591. program data flow is set up with a small script that runs in an ECMA-262 host
  592. environment\nfnote{Standard ECMA-262, 3$^{\rm{rd}}$ Edition\par\hbox{\indent%
  593. \pdfURL{%
  594. http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf}%
  595. {http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf}}}
  596. which requires
  597. significantly less expertise to modify than \pn{} itself. Such a scripting
  598. environment will be familiar to anybody with experience using JavaScript on web
  599. pages or ActionScript in Flash. \pn{}'@q'@>s configuration system was later updated
  600. to support running several script fragments found in an XML configuration
  601. document.
  602. Most of the application classes are available from the scripting environment.
  603. The functions that make this possible are presented along with the classes. A
  604. selection of classes provided by Qt are also available. These are presented
  605. here.
  606. This chunk provides two |QScriptValue| objects which are used in other sections
  607. appended to this chunk.
  608. @<Set up the scripting engine@>=
  609. QScriptEngine *engine = new QScriptEngine;
  610. QScriptValue constructor;
  611. QScriptValue value;
  612. @ A common task when working with objects created from a script is finding the
  613. object a method is called on from the current script context. The code for this
  614. is simple, but lengthy. This is shortened with the use of a template function
  615. that obtains the object in question and casts it to the appropriate type. If an
  616. incorrect type is specified, a null pointer or similarly invalid value will be
  617. returned.
  618. @<Functions for scripting@>=
  619. template<class TYPE> TYPE@, getself(QScriptContext *context)
  620. {
  621. TYPE@, self = qobject_cast<TYPE>(context->thisObject().toQObject());
  622. return self;
  623. }
  624. template<> QTime getself(QScriptContext *context)
  625. {
  626. QTime self = context->thisObject().toVariant().toTime();
  627. return self;
  628. }
  629. template<> QByteArray getself(QScriptContext *context)
  630. {
  631. QByteArray self = context->thisObject().toVariant().toByteArray();
  632. return self;
  633. }
  634. template<> SqlQueryConnection* getself(QScriptContext *context)
  635. {
  636. SqlQueryConnection *self =@|
  637. (SqlQueryConnection *)qscriptvalue_cast<void *>(context->thisObject());
  638. return self;
  639. }
  640. template<> QXmlQuery* getself(QScriptContext *context)
  641. {
  642. QXmlQuery *self =
  643. (QXmlQuery *)qscriptvalue_cast<void *>(context->thisObject());
  644. return self;
  645. }
  646. template<> QXmlStreamWriter* getself(QScriptContext *context)
  647. {
  648. QXmlStreamWriter *self = @|
  649. (QXmlStreamWriter *)qscriptvalue_cast<void *>(context->thisObject());
  650. return self;
  651. }
  652. template<> QXmlStreamReader* getself(QScriptContext *context)
  653. {
  654. QXmlStreamReader *self = @|
  655. (QXmlStreamReader *)qscriptvalue_cast<void *>(context->thisObject());
  656. return self;
  657. }
  658. @ Another common task is obtaining the arguments of a method call from the
  659. script context and casting these arguments to the proper type. This is once
  660. again done with templates.
  661. @<Functions for scripting@>=
  662. template<class TYPE> TYPE@, argument(int arg, QScriptContext *context)
  663. {
  664. TYPE@, argument = qobject_cast<TYPE>(context->argument(arg).toQObject());
  665. return argument;
  666. }
  667. template<> QString argument(int arg, QScriptContext *context)
  668. {
  669. return context->argument(arg).toString();
  670. }
  671. template<> QVariant argument(int arg, QScriptContext *context)
  672. {
  673. return context->argument(arg).toVariant();
  674. }
  675. template<> int argument(int arg, QScriptContext *context)
  676. {
  677. return context->argument(arg).toInt32();
  678. }
  679. template<> SqlQueryConnection* argument(int arg, QScriptContext *context)
  680. {
  681. return (SqlQueryConnection *)
  682. qscriptvalue_cast<void *>(context->argument(arg));
  683. }
  684. template<> QModelIndex argument(int arg, QScriptContext *context)
  685. {
  686. return qscriptvalue_cast<QModelIndex>(context->argument(arg));
  687. }
  688. template<> double argument(int arg, QScriptContext *context)
  689. {
  690. return (double)(context->argument(arg).toNumber());
  691. }
  692. template<> Units::Unit argument(int arg, QScriptContext *context)
  693. {
  694. return (Units::Unit)(context->argument(arg).toInt32());
  695. }
  696. template<> QByteArray argument(int arg, QScriptContext *context)
  697. {
  698. return qscriptvalue_cast<QByteArray>(context->argument(arg));
  699. }
  700. template<> bool argument(int arg, QScriptContext *context)
  701. {
  702. return context->argument(arg).toBool();
  703. }
  704. @ The scripting engine is informed of a number of classes defined elsewhere in
  705. the program. Code related to scripting these classes is grouped with the code
  706. implementing the classes. Additionally, there are several classes from Qt which
  707. are also made scriptable. These are detailed in the following sections.
  708. @* Exposing an Object Hierarchy to the Host Environment.
  709. \noindent While QtScript does a generally acceptable job of exposing
  710. information about objects that are available through the meta-object system,
  711. some methods require special handling in order to make them fully available to
  712. the host environment. Several functions are provided which provide a
  713. |QScriptValue| with these additional properties. The functions providing these
  714. properties also call other functions providing the properties of any base
  715. classes. In this way, any additional functionality provided to the host
  716. environment for a base class is also provided for any class that inherits that
  717. base class.
  718. For example, a |QBoxLayout| created in a script will have properties from
  719. |QLayout| which in turn brings in properties from |QObject| and |QLayoutItem|.
  720. A |QMainWindow| would bring in properties from |QWidget| which would bring in
  721. properties from |QObject|.
  722. Neither all methods nor all Qt classes are available from the host environment.
  723. When adding functionality to the host environment, there is a priority on
  724. classes and methods that are useful for \pn{}'@q'@>s intended purpose.
  725. @* Base Classes.
  726. \noindent There are a few classes that are base classes of classes exposed to
  727. the scripting engine. There is no need for the host environment to allow the
  728. creation of these base classes and there may not be methods that must be added
  729. as properties in derived classes, however stub functions are provided so that
  730. in the event that a method from one of these base classes is needed later, it
  731. can be added once for all derived classes.
  732. The first of these is |QObject|.
  733. @<Function prototypes for scripting@>=
  734. void setQObjectProperties(QScriptValue value, QScriptEngine *engine);
  735. QScriptValue QObject_setProperty(QScriptContext *context, QScriptEngine *engine);
  736. @ Attaching properties to a |QScriptValue| that wraps a |QObject| does not
  737. create a dynamic property on the underlying |QObject| by default. This can
  738. cause issues with certain interactions between script and native code. Rather
  739. than change every wrapper, we can instead expose a |setProperty()| method.
  740. @<Functions for scripting@>=
  741. void setQObjectProperties(QScriptValue value, QScriptEngine *engine)
  742. {
  743. value.setProperty("setProperty", engine->newFunction(QObject_setProperty));
  744. }
  745. QScriptValue QObject_setProperty(QScriptContext *context, QScriptEngine *)
  746. {
  747. QObject *self = getself<QObject *>(context);
  748. self->setProperty(argument<QString>(0, context).toUtf8().constData(),
  749. argument<QVariant>(1, context));
  750. return QScriptValue();
  751. }
  752. @ The same can be done for |QPaintDevice| and |QLayoutItem|.
  753. @<Function prototypes for scripting@>=
  754. void setQPaintDeviceProperties(QScriptValue value, QScriptEngine *engine);
  755. void setQLayoutItemProperties(QScriptValue value, QScriptEngine *engine);
  756. @ The implementations are similarly empty.
  757. @<Functions for scripting@>=
  758. void setQPaintDeviceProperties(QScriptValue, QScriptEngine *)
  759. {
  760. /* Nothing needs to be done here. */
  761. }
  762. void setQLayoutItemProperties(QScriptValue, QScriptEngine *)
  763. {
  764. /* Nothing needs to be done here. */
  765. }
  766. @* Timers.
  767. \noindent Some features in Typica require access to functionality similar to
  768. what |QTimer| provides from the host environment. This includes allowing
  769. script devices to periodically poll connected hardware and allowing a safety
  770. delay on profile translation.
  771. <@Function prototypes for scripting@>=
  772. void setQTimerProperties(QScriptValue value, QScriptEngine *engine);
  773. QScriptValue constructQTimer(QScriptContext *context, QScriptEngine *engine);
  774. @ The host environment is informed of the constructor.
  775. @<Set up the scripting engine@>=
  776. constructor = engine->newFunction(constructQTimer);
  777. value = engine->newQMetaObject(&QTimer::staticMetaObject, constructor);
  778. engine->globalObject().setProperty("Timer", value);
  779. @ Everything that we are interested in here is a signal, slot, or property so
  780. there is little else to do.
  781. @<Functions for scripting@>=
  782. void setQTimerProperties(QScriptValue value, QScriptEngine *engine)
  783. {
  784. setQObjectProperties(value, engine);
  785. }
  786. QScriptValue constructQTimer(QScriptContext *, QScriptEngine *engine)
  787. {
  788. QScriptValue object = engine->newQObject(new QTimer);
  789. setQTimerProperties(object, engine);
  790. return object;
  791. }
  792. @* Scripting QWidget.
  793. \noindent The first interesting class in this hierarchy is |QWidget|. This is
  794. mainly used as a base class for other widgets and in such a role it is not
  795. particularly interesting. It is, however, possible to apply a layout to a
  796. |QWidget| and use that to manage the size and position of one or more child
  797. widgets. A few functions are used to accomplish this.
  798. @<Function prototypes for scripting@>=
  799. void setQWidgetProperties(QScriptValue value, QScriptEngine *engine);
  800. QScriptValue constructQWidget(QScriptContext *context, QScriptEngine *engine);
  801. QScriptValue QWidget_setLayout(QScriptContext *context, QScriptEngine *engine);
  802. QScriptValue QWidget_activateWindow(QScriptContext *context,
  803. QScriptEngine *engine);
  804. @ The script constructor must be passed to the scripting engine.
  805. @<Set up the scripting engine@>=
  806. constructor = engine->newFunction(constructQWidget);
  807. value = engine->newQMetaObject(&QWidget::staticMetaObject, constructor);
  808. engine->globalObject().setProperty("QWidget", value);
  809. @ The constructor creates a script value, but uses another function to add
  810. properties that wrap methods we want to make available to subclasses. Note that
  811. properties of the base classes are added before properties of this class. This
  812. procedure ensures that properties added from base classes can be be replaced in
  813. subclasses.
  814. @<Functions for scripting@>=
  815. QScriptValue constructQWidget(QScriptContext *, QScriptEngine *engine)
  816. {
  817. QScriptValue object = engine->newQObject(new QWidget);
  818. setQWidgetProperties(object, engine);
  819. return object;
  820. }
  821. void setQWidgetProperties(QScriptValue value, QScriptEngine *engine)
  822. {
  823. setQObjectProperties(value, engine);
  824. setQPaintDeviceProperties(value, engine);
  825. value.setProperty("setLayout", engine->newFunction(QWidget_setLayout));
  826. value.setProperty("activateWindow",
  827. engine->newFunction(QWidget_activateWindow));
  828. }
  829. @ This just leaves the property implementations. |QWidget::setLayout()| takes
  830. one argument, a |QLayout| and returns |void|. This wrapper duplicates this
  831. interface. |QWidget::activateWindow()| takes no arguments and returns nothing
  832. meaningful.
  833. @<Functions for scripting@>=
  834. QScriptValue QWidget_setLayout(QScriptContext *context, QScriptEngine *)
  835. {
  836. if(context->argumentCount() == 1)
  837. {
  838. QWidget *self = getself<QWidget *>(context);
  839. QLayout *layout = argument<QLayout *>(0, context);
  840. if(layout)
  841. {
  842. self->setLayout(layout);
  843. }
  844. else
  845. {
  846. context->throwError("Incorrect argument type passed to "@|
  847. "QWidget::setLayout(). This method requires "@|
  848. "a QLayout.");
  849. }
  850. }
  851. else
  852. {
  853. context->throwError("Incorrect number of arguments passed to "@|
  854. "QWidget::setLayout(). This method takes one "@|
  855. "QLayout as an argument.");
  856. }
  857. return QScriptValue();
  858. }
  859. QScriptValue QWidget_activateWindow(QScriptContext *context,
  860. QScriptEngine *)
  861. {
  862. QWidget *self = getself<QWidget *>(context);
  863. self->activateWindow();
  864. return QScriptValue();
  865. }
  866. @* Scripting QMessageBox.
  867. \noindent Some features require that \pn{} pauses an operation until further
  868. information can be obtained. An example of this is discretionary validation
  869. where input is checked and if it seems unlikely but not impossible to be
  870. correct a dialog should come up asking if that input is correct. If it is not,
  871. the operation should be cancelled and the person using \pn{} should be allowed
  872. to correct the information and try again.
  873. For this use case, it is not necessary to fully expose the |QMessageBox| class.
  874. Instead, it is enough to provide a function that will raise an appropriate
  875. message and return the selected action.
  876. @<Function prototypes for scripting@>=
  877. QScriptValue displayWarning(QScriptContext *context, QScriptEngine *engine);
  878. QScriptValue displayError(QScriptContext *context, QScriptEngine *engine);
  879. QScriptValue displayInfo(QScriptContext *context, QScriptEngine *engine);
  880. @ This function is exposed to the host environment.
  881. @<Set up the scripting engine@>=
  882. constructor = engine->newFunction(displayWarning);
  883. engine->globalObject().setProperty("displayWarning", constructor);
  884. constructor = engine->newFunction(displayError);
  885. engine->globalObject().setProperty("displayError", constructor);
  886. constructor = engine->newFunction(displayInfo);
  887. engine->globalObject().setProperty("displayInfo", constructor);
  888. @ The function takes some arguments.
  889. @<Functions for scripting@>=
  890. QScriptValue displayWarning(QScriptContext *context, QScriptEngine *)
  891. {
  892. QMessageBox::StandardButton selection = QMessageBox::warning(NULL,
  893. argument<QString>(0, context),
  894. argument<QString>(1, context),
  895. QMessageBox::Ok | QMessageBox::Cancel);
  896. if(selection == QMessageBox::Ok) {
  897. return QScriptValue(true);
  898. }
  899. return QScriptValue(false);
  900. }
  901. QScriptValue displayError(QScriptContext *context, QScriptEngine *)
  902. {
  903. QMessageBox::critical(NULL, argument<QString>(0, context),
  904. argument<QString>(1, context));
  905. return QScriptValue();
  906. }
  907. QScriptValue displayInfo(QScriptContext *context, QScriptEngine *)
  908. {
  909. QMessageBox::information(NULL, argument<QString>(0, context),
  910. argument<QString>(1, context));
  911. return QScriptValue();
  912. }
  913. @* Scripting QMainWindow.
  914. \noindent Rather than directly exposing |QMainWindow| to the scripting engine,
  915. we expose a class derived from |QMainWindow| with a minor change allowing the
  916. script to be notified when the window is about to be closed.
  917. This allows us to save settings for objects populating the window. Close
  918. handlers can be established by connecting to the |aboutToClose()| signal which
  919. is emitted in the |closeEvent()| handler. The close event is always accepted
  920. after the script has had a chance to respond, so this cannot be used to present
  921. an, ``Are you sure?'' message without additional modification.
  922. Slots are also provided for saving the size and position of the window to
  923. settings and restoring the window geometry from these settings.
  924. As of version 1.4 window geometry management is provided for all windows. The
  925. |restoreSizeAndPosition()| and |saveSizeAndPosition()| methods should be
  926. considered depreciated.
  927. Version 1.6 adds a new property for handling the |windowModified| property
  928. such that an appropriate prompt is provided to confirm or cancel close events.
  929. Version 1.8 adds a new |setupFinished()| slot which is called after the
  930. initial |show()| at the end of window creation. This emits a |windowReady()|
  931. signal. Scripts can connect to this signal to perform tasks that must happen
  932. after the window has fully finished opening. The initial use for this is
  933. validating that all required configuration has been performed for a given
  934. window to be useful and, if not, immediately closing that. Without this, a
  935. call to |close()| in the script is reversed when the function creating the
  936. window calls |show()|.
  937. @<Class declarations@>=
  938. class ScriptQMainWindow : public QMainWindow@/
  939. {@t\1@>@/
  940. Q_OBJECT@;@/
  941. Q_PROPERTY(QString closePrompt READ closePrompt WRITE setClosePrompt)@;@/
  942. public:@/
  943. ScriptQMainWindow();
  944. QString closePrompt();@/
  945. @t\4@>public slots@t\kern-3pt@>:@/
  946. void show();
  947. void saveSizeAndPosition(const QString &key);
  948. void restoreSizeAndPosition(const QString &key);
  949. void displayStatus(const QString &message = QString());
  950. void setClosePrompt(QString prompt);
  951. void setupFinished();@/
  952. signals:@/
  953. void aboutToClose(void);
  954. void windowReady(void);@/
  955. protected:@/
  956. void closeEvent(QCloseEvent *event);
  957. void showEvent(QShowEvent *event);@/
  958. private:@/
  959. QString cprompt;@t\2@>@/
  960. }@t\kern-3pt@>;
  961. @ The implementation of these functions is simple.
  962. @<Functions for scripting@>=
  963. ScriptQMainWindow::ScriptQMainWindow()@+: QMainWindow(NULL),
  964. cprompt(tr("Closing this window may result in loss of data. Continue?"))@/
  965. {
  966. if(!AppInstance->databaseConnected())
  967. {
  968. statusBar()->addWidget(new QLabel(tr("Not connected to database")));
  969. }
  970. else
  971. {
  972. statusBar()->addWidget(new UserLabel);
  973. }
  974. }
  975. void ScriptQMainWindow::saveSizeAndPosition(const QString &key)
  976. {
  977. QSettings settings;
  978. settings.beginGroup(key);
  979. settings.setValue("pos", pos());
  980. settings.setValue("size", size());
  981. settings.endGroup();
  982. }
  983. void ScriptQMainWindow::restoreSizeAndPosition(const QString &key)
  984. {
  985. QSettings settings;
  986. settings.beginGroup(key);
  987. if(settings.contains("size"))
  988. {
  989. resize(settings.value("size").toSize());
  990. }
  991. if(settings.contains("pos"))
  992. {
  993. move(settings.value("pos").toPoint());
  994. }
  995. settings.endGroup();
  996. }
  997. void ScriptQMainWindow::displayStatus(const QString &message)
  998. {
  999. statusBar()->showMessage(message);
  1000. }
  1001. void ScriptQMainWindow::showEvent(QShowEvent *event)
  1002. {
  1003. if(!event->spontaneous())
  1004. {
  1005. @<Restore window geometry@>@;
  1006. event->accept();
  1007. }
  1008. else
  1009. {
  1010. event->ignore();
  1011. }
  1012. }
  1013. void ScriptQMainWindow::show()
  1014. {
  1015. QMainWindow::show();
  1016. }
  1017. void ScriptQMainWindow::setupFinished()
  1018. {
  1019. emit windowReady();
  1020. }
  1021. @ When a close event occurs, we check the |windowModified| property to
  1022. determine if closing the window could result in loss of data. If this is
  1023. true, we allow the event to be cancelled. Otherwise, a signal is emitted which
  1024. allows scripts to perform any cleanup that may be required before closing the
  1025. window and the window geometry data is saved before allowing the window to
  1026. close.
  1027. @<Functions for scripting@>=
  1028. void ScriptQMainWindow::closeEvent(QCloseEvent *event)
  1029. {
  1030. if(isWindowModified()) {
  1031. @<Allow close event to be cancelled@>@;
  1032. }
  1033. emit aboutToClose();
  1034. @<Save window geometry@>@;
  1035. event->accept();
  1036. }
  1037. @ The prompt text for our confirmation window is provided through the
  1038. |closePrompt| property.
  1039. @<Allow close event to be cancelled@>=
  1040. QMessageBox::StandardButton result;
  1041. result = QMessageBox::warning(this, "Typica", closePrompt(),
  1042. QMessageBox::Ok | QMessageBox::Cancel);
  1043. if(result == QMessageBox::Cancel)
  1044. {
  1045. event->ignore();
  1046. return;
  1047. }
  1048. @ Implementation of the |closePrompt| property is trivial.
  1049. @<Functions for scripting@>=
  1050. QString ScriptQMainWindow::closePrompt()
  1051. {
  1052. return cprompt;
  1053. }
  1054. void ScriptQMainWindow::setClosePrompt(QString prompt)
  1055. {
  1056. cprompt = prompt;
  1057. }
  1058. @ Window geometry management from version 1.4 on makes use of the window ID to
  1059. produce an appropriate QSettings key. This decision relies on the ID being set
  1060. before any show or close events are received and it relies on every distinct
  1061. type of window having a unique ID. If this is not the case then other things
  1062. are likely very broken. Note that with this approach multiple instances of the
  1063. same type of window will use the same key. This may not be ideal in all cases,
  1064. but further refinements can be produced if necessary.
  1065. @<Save window geometry@>=
  1066. QSettings settings;
  1067. settings.setValue(QString("geometries/%1").arg(objectName()), saveGeometry());
  1068. @ Restoring saved geometry is performed similarly to saving it.
  1069. @<Restore window geometry@>=
  1070. QSettings settings;
  1071. restoreGeometry(settings.value(QString("geometries/%1").arg(objectName())).
  1072. toByteArray());
  1073. @ Three functions are required to obtain the required functionality from a
  1074. script. A fourth adds properties for the object hierarchy.
  1075. @<Function prototypes for scripting@>=
  1076. QScriptValue constructQMainWindow(QScriptContext *context,
  1077. QScriptEngine *engine);
  1078. QScriptValue QMainWindow_setCentralWidget(QScriptContext *context,@|
  1079. QScriptEngine *engine);
  1080. QScriptValue QMainWindow_menuBar(QScriptContext *context,
  1081. QScriptEngine *engine);
  1082. void setQMainWindowProperties(QScriptValue value, QScriptEngine *engine);
  1083. @ Of these, the engine only needs to be informed of the constructor initially.
  1084. @<Set up the scripting engine@>=
  1085. constructor = engine->newFunction(constructQMainWindow);
  1086. value = engine->newQMetaObject(&ScriptQMainWindow::staticMetaObject,
  1087. constructor);
  1088. engine->globalObject().setProperty("QMainWindow", value);
  1089. @ The constructor calls a function to add the additional properties to the
  1090. newly created value.
  1091. @<Functions for scripting@>=
  1092. QScriptValue constructQMainWindow(QScriptContext *, QScriptEngine *engine)
  1093. {
  1094. QScriptValue object = engine->newQObject(new ScriptQMainWindow);
  1095. setQMainWindowProperties(object, engine);
  1096. return object;
  1097. }
  1098. void setQMainWindowProperties(QScriptValue value, QScriptEngine *engine)
  1099. {
  1100. setQWidgetProperties(value, engine);
  1101. value.setProperty("setCentralWidget",
  1102. engine->newFunction(QMainWindow_setCentralWidget));
  1103. value.setProperty("menuBar", engine->newFunction(QMainWindow_menuBar));
  1104. }
  1105. @ The |"setCentralWidget"| property is used for setting a widget in the main
  1106. area of the window. In \pn{} this will usually be a |QSplitter| object, but it
  1107. could also be a bare |QWidget| with a layout managing multiple widgets or a
  1108. custom widget defined in a local change. This is a simple wrapper around
  1109. |QMainWindow::setCentralWidget()|.
  1110. @<Functions for scripting@>=
  1111. QScriptValue QMainWindow_setCentralWidget(QScriptContext *context,
  1112. QScriptEngine *)
  1113. {
  1114. if(context->argumentCount() == 1)
  1115. {
  1116. QMainWindow *self = getself<QMainWindow *>(context);
  1117. QWidget *widget = argument<QWidget *>(0, context);
  1118. if(widget)
  1119. {
  1120. self->setCentralWidget(widget);
  1121. }
  1122. else
  1123. {
  1124. context->throwError("Incorrect argument type passed to "@|
  1125. "QMainWindow::setCentralWidget(). This "@|
  1126. "method requires a QWidget.");
  1127. }
  1128. }
  1129. else
  1130. {
  1131. context->throwError("Incorrect number of arguments passed to "@|
  1132. "QMainWindow::setCentralWidget(). This method "@|
  1133. "takes one QWidget as an argument.");
  1134. }
  1135. return QScriptValue();
  1136. }
  1137. @ The |"menuBar"| property requires that we expose |QMenuBar| to the scripting
  1138. environment in a limited fashion. We don'@q'@>t need to allow scripts to create a
  1139. new menu bar as it can be obtained from the window, however to add the menus to
  1140. the menu bar, we need to add a property to the |QMenuBar| object before passing
  1141. it back.
  1142. @<Functions for scripting@>=
  1143. QScriptValue QMainWindow_menuBar(QScriptContext *context, QScriptEngine *engine)
  1144. {
  1145. QScriptValue object;
  1146. if(context->argumentCount() == 0)
  1147. {
  1148. QMainWindow *self = getself<@[QMainWindow *@]>(context);
  1149. QMenuBar *bar = self->menuBar();
  1150. object = engine->newQObject(bar);
  1151. setQMenuBarProperties(object, engine);
  1152. }
  1153. else
  1154. {
  1155. context->throwError("Incorrect number of arguments passed to "@|
  1156. "QMainWindow::menuBar(). This method takes no "@|
  1157. "arguments.");
  1158. }
  1159. return object;
  1160. }
  1161. @ The previous function is the only place a new |QMenuBar| is created through
  1162. the host environment. Two functions are used in handling this object creation.
  1163. @<Function prototypes for scripting@>=
  1164. void setQMenuBarProperties(QScriptValue value, QScriptEngine *engine);
  1165. QScriptValue QMenuBar_addMenu(QScriptContext *context, QScriptEngine *engine);
  1166. @ The first of these adds the appropriate properties to the newly created
  1167. object.
  1168. @<Functions for scripting@>=
  1169. void setQMenuBarProperties(QScriptValue value, QScriptEngine *engine)
  1170. {
  1171. setQWidgetProperties(value, engine);
  1172. value.setProperty("addMenu", engine->newFunction(QMenuBar_addMenu));
  1173. }
  1174. @ This function can be used to add new menus to a menu bar. In order to do
  1175. anything with the newly created menus, two properties are added to the |QMenu|
  1176. objects which allow actions to be added as menu items and allow separators to be
  1177. placed between groups of menu items.
  1178. At the time of this writing, there are three |QMenuBar::addMenu()| methods. This
  1179. function wraps |QMenu* QMenuBar::addMenu(const QString &title)|.
  1180. @<Functions for scripting@>=
  1181. QScriptValue QMenuBar_addMenu(QScriptContext *context, QScriptEngine *engine)
  1182. {
  1183. QScriptValue object;
  1184. if(context->argumentCount() == 1)
  1185. {
  1186. QMenuBar *self = getself<@[QMenuBar *@]>(context);
  1187. QString title = argument<QString>(0, context);
  1188. object = engine->newQObject(self->addMenu(title));
  1189. setQMenuProperties(object, engine);
  1190. }
  1191. else
  1192. {
  1193. context->throwError("Incorrect number of arguments passed to "@|
  1194. "QMenuBar::addMenu(). This method takes one "@|
  1195. "string as an argument.");
  1196. }
  1197. return object;
  1198. }
  1199. @ These three functions allow adding items to the menu and adding separators
  1200. between groups of items.
  1201. @<Function prototypes for scripting@>=
  1202. void setQMenuProperties(QScriptValue value, QScriptEngine *engine);
  1203. QScriptValue QMenu_addAction(QScriptContext *context, QScriptEngine *engine);
  1204. QScriptValue QMenu_addSeparator(QScriptContext *context, QScriptEngine *engine);
  1205. @ The first of these add properties to newly created |QMenu| objects.
  1206. @<Functions for scripting@>=
  1207. void setQMenuProperties(QScriptValue value, QScriptEngine *engine)
  1208. {
  1209. setQWidgetProperties(value, engine);
  1210. value.setProperty("addAction", engine->newFunction(QMenu_addAction));
  1211. value.setProperty("addSeparator", engine->newFunction(QMenu_addSeparator));
  1212. }
  1213. @ These functions are simple wrappers around |QMenu| methods.
  1214. @<Functions for scripting@>=
  1215. QScriptValue QMenu_addAction(QScriptContext *context, QScriptEngine *)
  1216. {
  1217. if(context->argumentCount() == 1)
  1218. {
  1219. QMenu *self = getself<@[QMenu *@]>(context);
  1220. QAction *action = argument<QAction *>(0, context);
  1221. if(action)
  1222. {
  1223. self->addAction(action);
  1224. }
  1225. else
  1226. {
  1227. context->throwError("Incorrect argument type passed to "@|
  1228. "QMenu::addAction(). This method requires a "@|
  1229. "QAction.");
  1230. }
  1231. }
  1232. else
  1233. {
  1234. context->throwError("Incorrect number of arguments passed to "@|
  1235. "QMenu::addAction(). This method takes one "@|
  1236. "QAction as an argument.");
  1237. }
  1238. return QScriptValue();
  1239. }
  1240. QScriptValue QMenu_addSeparator(QScriptContext *context, QScriptEngine *)
  1241. {
  1242. if(context->argumentCount() == 0)
  1243. {
  1244. QMenu *self = getself<@[QMenu *@]>(context);
  1245. self->addSeparator();
  1246. }
  1247. else
  1248. {
  1249. context->throwError("Incorrect number of arguments passed to "@|
  1250. "QMenu::addSeparator(). This method takes no "@|
  1251. "arguments.");
  1252. }
  1253. return QScriptValue();
  1254. }
  1255. @* Scripting QFrame.
  1256. \noindent |QFrame| is another class for which little needs to be done. It exists
  1257. as a subclass of |QWidget| and a superclass for |QSplitter|, |QLCDNumber|, and
  1258. |QAbstractScrollArea| among other classes.
  1259. @<Function prototypes for scripting@>=
  1260. void setQFrameProperties(QScriptValue value, QScriptEngine *engine);
  1261. QScriptValue constructQFrame(QScriptContext *context, QScriptEngine *engine);
  1262. @ The constructor must be passed to the scripting engine.
  1263. @<Set up the scripting engine@>=
  1264. constructor = engine->newFunction(constructQFrame);
  1265. value = engine->newQMetaObject(&QFrame::staticMetaObject, constructor);
  1266. engine->globalObject().setProperty("QFrame", value);
  1267. @ The implementation of these functions should seem familiar.
  1268. @<Functions for scripting@>=
  1269. QScriptValue constructQFrame(QScriptContext *, QScriptEngine *engine)
  1270. {
  1271. QScriptValue object = engine->newQObject(new QFrame);
  1272. setQFrameProperties(object, engine);
  1273. return object;
  1274. }
  1275. void setQFrameProperties(QScriptValue value, QScriptEngine *engine)
  1276. {
  1277. setQWidgetProperties(value, engine);
  1278. }
  1279. @* Scripting QLabel.
  1280. \noindent When constructing an interface wholly or partially through dynamic
  1281. means rather than entirely through the XML configuration document it can
  1282. sometimes be desirable to construct |QLabel| instances. This is usually used
  1283. to provide a very small amount of text.
  1284. @<Function prototypes for scripting@>=
  1285. void setQLabelProperties(QScriptValue value, QScriptEngine *engine);
  1286. QScriptValue constructQLabel(QScriptContext *context, QScriptEngine *engine);
  1287. @ The constructor must be passed to the scripting engine.
  1288. @<Set up the scripting engine@>=
  1289. constructor = engine->newFunction(constructQLabel);
  1290. value = engine->newQMetaObject(&QLabel::staticMetaObject, constructor);
  1291. engine->globalObject().setProperty("QLabel", value);
  1292. @ In the constructor we allow an optional argument to specify the text of the
  1293. label.
  1294. @<Functions for scripting@>=
  1295. QScriptValue constructQLabel(QScriptContext *context, QScriptEngine *engine)
  1296. {
  1297. QString text;
  1298. if(context->argumentCount() == 1)
  1299. {
  1300. text = argument<QString>(0, context);
  1301. }
  1302. QScriptValue object = engine->newQObject(new QLabel(text));
  1303. setQLabelProperties(object, engine);
  1304. return object;
  1305. }
  1306. void setQLabelProperties(QScriptValue value, QScriptEngine *engine)
  1307. {
  1308. setQFrameProperties(value, engine);
  1309. }
  1310. @* Scripting QSvgWidget.
  1311. \noindent Sometimes it is useful to provide a space for simple drawings without
  1312. the need for all of the other capabilities of a web view. This was introduced
  1313. as a way to draw box plots to help guide the creation of roast specifications.
  1314. @<Function prototypes for scripting@>=
  1315. void setQSvgWidgetProperties(QScriptValue value, QScriptEngine *engine);
  1316. QScriptValue constructQSvgWidget(QScriptContext *context,
  1317. QScriptEngine *engine);
  1318. QScriptValue QSvgWidget_loadDevice(QScriptContext *context,
  1319. QScriptEngine *engine);
  1320. void addSvgWidgetToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  1321. QStack<QLayout *> *layoutStack);
  1322. @ The constructor must be passed to the scripting engine.
  1323. @<Set up the scripting engine@>=
  1324. constructor = engine->newFunction(constructQSvgWidget);
  1325. value = engine->newQMetaObject(&QSvgWidget::staticMetaObject, constructor);
  1326. engine->globalObject().setProperty("QSvgWidget", value);
  1327. @ The constructor is trivial.
  1328. @<Functions for scripting@>=
  1329. QScriptValue constructQSvgWidget(QScriptContext *,
  1330. QScriptEngine *engine)
  1331. {
  1332. QScriptValue object = engine->newQObject(new QSvgWidget);
  1333. setQSvgWidgetProperties(object, engine);
  1334. return object;
  1335. }
  1336. @ A property is added that allows loading data from a |QIODevice|.
  1337. @<Functions for scripting@>=
  1338. void setQSvgWidgetProperties(QScriptValue value, QScriptEngine *engine)
  1339. {
  1340. setQWidgetProperties(value, engine);
  1341. value.setProperty("loadDevice",
  1342. engine->newFunction(QSvgWidget_loadDevice));
  1343. }
  1344. QScriptValue QSvgWidget_loadDevice(QScriptContext *context, QScriptEngine *)
  1345. {
  1346. if(context->argumentCount() == 1)
  1347. {
  1348. QSvgWidget *self = getself<@[QSvgWidget *@]>(context);
  1349. QIODevice *device = argument<QIODevice *>(0, context);
  1350. device->reset();
  1351. QByteArray data = device->readAll();
  1352. self->load(data);
  1353. }
  1354. else
  1355. {
  1356. context->throwError("Incorrect number of arguments passed to "@|
  1357. "QSvgWidget::loadData(). This method takes one "@|
  1358. "QIODevice as an argument.");
  1359. }
  1360. return QScriptValue();
  1361. }
  1362. @ Additional work is needed to allow including this from the XML description of
  1363. a window.
  1364. @<Additional box layout elements@>=
  1365. else if(currentElement.tagName() == "svgwidget")
  1366. {
  1367. addSvgWidgetToLayout(currentElement, widgetStack, layoutStack);
  1368. }
  1369. @ The function used to create this follows the usual pattern.
  1370. @<Functions for scripting@>=
  1371. void addSvgWidgetToLayout(QDomElement element, QStack<QWidget *> *,
  1372. QStack<QLayout *> *layoutStack)
  1373. {
  1374. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  1375. QSvgWidget *widget = new QSvgWidget;
  1376. layout->addWidget(widget);
  1377. QString id = element.attribute("id");
  1378. if(!id.isEmpty())
  1379. {
  1380. widget->setObjectName(id);
  1381. }
  1382. }
  1383. @* Scripting QLineEdit.
  1384. \noindent Similarly, we may want to allow line edits in interfaces defined
  1385. through the host environment. For example, this is used for the free text
  1386. annotation control for roasters this has been configured on.
  1387. @<Function prototypes for scripting@>=
  1388. void setQLineEditProperties(QScriptValue value, QScriptEngine *engine);
  1389. QScriptValue constructQLineEdit(QScriptContext *context, QScriptEngine *engine);
  1390. @ The constructor must be passed to the host environment.
  1391. @<Set up the scripting engine@>=
  1392. constructor = engine->newFunction(constructQLineEdit);
  1393. value = engine->newQMetaObject(&QLineEdit::staticMetaObject, constructor);
  1394. engine->globalObject().setProperty("QLineEdit", value);
  1395. @ The constructor is trivial.
  1396. @<Functions for scripting@>=
  1397. QScriptValue constructQLineEdit(QScriptContext *, QScriptEngine *engine)
  1398. {
  1399. QScriptValue object = engine->newQObject(new QLineEdit());
  1400. setQLineEditProperties(object, engine);
  1401. return object;
  1402. }
  1403. @ At present all of the QLineEdit functionality exposed through this interface
  1404. is provided automatically through the meta-object system.
  1405. @<Functions for scripting@>=
  1406. void setQLineEditProperties(QScriptValue value, QScriptEngine *engine)
  1407. {
  1408. setQWidgetProperties(value, engine);
  1409. }
  1410. @* Scripting QSplitter.
  1411. \noindent The |QSplitter| class is one of the main classes used for user
  1412. interface object layout in \pn{}. To provide this class to the scripting engine,
  1413. we provide five functions: a constructor, a method for adding widgets to the
  1414. splitter, a method for saving the size of each widget in the splitter, a
  1415. method for restoring these saved sizes, and a function for adding these methods
  1416. as properties of newly created |QSplitter| objects.
  1417. @<Function prototypes for scripting@>=
  1418. QScriptValue constructQSplitter(QScriptContext *context, QScriptEngine *engine);
  1419. QScriptValue QSplitter_addWidget(QScriptContext *context,
  1420. QScriptEngine *engine);
  1421. QScriptValue QSplitter_saveState(QScriptContext *context,
  1422. QScriptEngine *engine);
  1423. QScriptValue QSplitter_restoreState(QScriptContext *context,
  1424. QScriptEngine *engine);
  1425. QScriptValue QSplitter_count(QScriptContext *context,
  1426. QScriptEngine *engine);
  1427. QScriptValue QSplitter_setCollapsible(QScriptContext *context,
  1428. QScriptEngine *engine);
  1429. void setQSplitterProperties(QScriptValue value, QScriptEngine *engine);
  1430. @ Of these, the scripting engine must be informed of the constructor.
  1431. @<Set up the scripting engine@>=
  1432. constructor = engine->newFunction(constructQSplitter);
  1433. value = engine->newQMetaObject(&QSplitter::staticMetaObject, constructor);
  1434. engine->globalObject().setProperty("QSplitter", value);
  1435. @ The constructor creates the object and adds the required properties to it.
  1436. @<Functions for scripting@>=
  1437. QScriptValue constructQSplitter(QScriptContext *, QScriptEngine *engine)
  1438. {
  1439. QScriptValue object = engine->newQObject(new QSplitter);
  1440. setQSplitterProperties(object, engine);
  1441. return object;
  1442. }
  1443. void setQSplitterProperties(QScriptValue value, QScriptEngine *engine)
  1444. {
  1445. setQFrameProperties(value, engine);
  1446. value.setProperty("addWidget", engine->newFunction(QSplitter_addWidget));
  1447. value.setProperty("saveState", engine->newFunction(QSplitter_saveState));
  1448. value.setProperty("restoreState",
  1449. engine->newFunction(QSplitter_restoreState));
  1450. value.setProperty("count", engine->newFunction(QSplitter_count));
  1451. value.setProperty("setCollapsible", engine->newFunction(QSplitter_setCollapsible));
  1452. }
  1453. @ The |"addWidget"| property is a simple wrapper around
  1454. |QSplitter::addWidget()|.
  1455. @<Functions for scripting@>=
  1456. QScriptValue QSplitter_addWidget(QScriptContext *context, QScriptEngine *)
  1457. {
  1458. if(context->argumentCount() == 1)
  1459. {
  1460. QSplitter *self = getself<QSplitter *>(context);
  1461. QWidget *widget = argument<QWidget *>(0, context);
  1462. if(widget)
  1463. {
  1464. self->addWidget(widget);
  1465. }
  1466. else
  1467. {
  1468. context->throwError("Incorrect argument type passed to "@|
  1469. "QSplitter::addWidget(). This method "@|
  1470. "requires a QWidget.");
  1471. }
  1472. }
  1473. else
  1474. {
  1475. context->throwError("Incorrect number of arguments passed to "@|
  1476. "QSplitter::addWidget(). This method takes one "@|
  1477. "QWidget as an argument.");
  1478. }
  1479. return QScriptValue();
  1480. }
  1481. @ The methods for saving and restoring the state of a splitter do not behave
  1482. well when the number of widgets contained in the splitter increase. This is a
  1483. problem in the logging view where we may want to allow zero width indicators
  1484. but reconfiguration can cause the number of indicators to increase. This would
  1485. result in the right most indicators such as the batch timer disappearing. Most
  1486. people do not notice the splitter handle or think to drag that to the left to
  1487. correct this issue so it would be better to save the number of indicators when
  1488. saving the state and if the number of indicators does not match, we should not
  1489. restore the obsolete saved state.
  1490. @<Functions for scripting@>=
  1491. QScriptValue QSplitter_count(QScriptContext *context, QScriptEngine *)
  1492. {
  1493. QSplitter *self = getself<QSplitter *>(context);
  1494. return QScriptValue(self->count());
  1495. }
  1496. @ When saving and restoring the state of a splitter, we always want to do this
  1497. through a |QSettings| object. For this, we take an extra argument specifying the
  1498. settings key to read from or write to. Unlike the equivalent functions called
  1499. from native code, neither of these functions called from a script will return
  1500. the data being saved.
  1501. @<Functions for scripting@>=
  1502. QScriptValue QSplitter_saveState(QScriptContext *context, QScriptEngine *)
  1503. {
  1504. if(context->argumentCount() == 1)
  1505. {
  1506. QSplitter *self = getself<QSplitter *>(context);
  1507. QString key = argument<QString>(0, context);
  1508. QSettings settings;
  1509. settings.setValue(key, self->saveState());
  1510. }
  1511. else
  1512. {
  1513. context->throwError("Incorrect number of arguments passed to "@|
  1514. "QSplitter::saveState(). This method takes one "@|
  1515. "string as an argument.");
  1516. }
  1517. return QScriptValue();
  1518. }
  1519. QScriptValue QSplitter_restoreState(QScriptContext *context, QScriptEngine *)
  1520. {
  1521. if(context->argumentCount() == 1)
  1522. {
  1523. QSplitter *self = getself<QSplitter *>(context);
  1524. QString key = argument<QString>(0, context);
  1525. QSettings settings;
  1526. self->restoreState(settings.value(key).toByteArray());
  1527. }
  1528. else
  1529. {
  1530. context->throwError("Incorrect number of arguments passed to "@|
  1531. "QSplitter::restoreState(). This method takes "@|
  1532. "one string as an argument.");
  1533. }
  1534. return QScriptValue();
  1535. }
  1536. @ Sometimes a |QSplitter| is used to make it easy to hide optional elements. In
  1537. this use case it can be useful to indicate that required elements cannot be
  1538. collapsed.
  1539. @<Functions for scripting@>=
  1540. QScriptValue QSplitter_setCollapsible(QScriptContext *context, QScriptEngine *)
  1541. {
  1542. if(context->argumentCount() == 2)
  1543. {
  1544. QSplitter *self = getself<QSplitter *>(context);
  1545. self->setCollapsible(argument<int>(0, context), argument<bool>(1, context));
  1546. }
  1547. else
  1548. {
  1549. context->throwError("Incorrect number of arguments");
  1550. }
  1551. return QScriptValue();
  1552. }
  1553. @* Scripting Layout classes.
  1554. \noindent Layout classes simplify managing the size and position of widgets in a
  1555. user interface. Qt provides several such classes, including |QBoxLayout| which
  1556. can be used to construct a variety of different interfaces. As widgets
  1557. containing a layout should not really need to care which layout is being used,
  1558. the |QLayout| class acts as an abstract base for all layout classes. A bare
  1559. |QLayout| will never be constructed, however subclasses can make use of the
  1560. |addWidget()| property.
  1561. @<Function prototypes for scripting@>=
  1562. void setQLayoutProperties(QScriptValue value, QScriptEngine *engine);
  1563. QScriptValue QLayout_addWidget(QScriptContext *context, QScriptEngine *engine);
  1564. @ The implementation is trivial.
  1565. @<Functions for scripting@>=
  1566. void setQLayoutProperties(QScriptValue value, QScriptEngine *engine)
  1567. {
  1568. setQLayoutItemProperties(value, engine);
  1569. value.setProperty("addWidget", engine->newFunction(QLayout_addWidget));
  1570. }
  1571. QScriptValue QLayout_addWidget(QScriptContext *context, QScriptEngine *)
  1572. {
  1573. if(context->argumentCount() == 1)
  1574. {
  1575. QLayout *self = getself<QLayout *>(context);
  1576. QWidget *widget = argument<QWidget *>(0, context);
  1577. if(widget)
  1578. {
  1579. self->addWidget(widget);
  1580. }
  1581. else
  1582. {
  1583. context->throwError("Incorrect argument type passed to "@|
  1584. "QLayout::addWidget(). This method requires "@|
  1585. "a QWidget.");
  1586. }
  1587. }
  1588. else
  1589. {
  1590. context->throwError("Incorrect number of arguments passed to "@|
  1591. "QLayout::addWidget(). This method takes one "@|
  1592. "QWidget as an argument.");
  1593. }
  1594. return QScriptValue();
  1595. }
  1596. @ |QBoxLayout| is a more interesting layout class. This allows widgets to be
  1597. arranged in a single row or column and can be used, for example, to arrange a
  1598. row of buttons as in figure \secno.
  1599. \medskip
  1600. \resizebox*{6.3in}{!}{\includegraphics{boxlayoutexample}}
  1601. \smallskip
  1602. \centerline{Figure \secno: Buttons in a |QBoxLayout|.}
  1603. \medskip
  1604. This class makes use of the |addWidget()| method from |QLayout|.
  1605. @<Function prototypes for scripting@>=
  1606. QScriptValue constructQBoxLayout(QScriptContext *context,
  1607. QScriptEngine *engine);
  1608. void setQBoxLayoutProperties(QScriptValue value, QScriptEngine *engine);
  1609. QScriptValue QBoxLayout_addLayout(QScriptContext *context, QScriptEngine *engine);
  1610. QScriptValue QBoxLayout_addWidget(QScriptContext *context, QScriptEngine *engine);
  1611. @ The script constructor must be passed to the scripting engine.
  1612. @<Set up the scripting engine@>=
  1613. constructor = engine->newFunction(constructQBoxLayout);
  1614. value = engine->newQMetaObject(&QBoxLayout::staticMetaObject, constructor);
  1615. engine->globalObject().setProperty("QBoxLayout", value);
  1616. @ The implementation of these functions should seem familiar by now. Note that
  1617. while a horizontal layout is provided by default, this can be changed from the
  1618. script once the layout is created.
  1619. @<Functions for scripting@>=
  1620. QScriptValue constructQBoxLayout(QScriptContext *, QScriptEngine *engine)
  1621. {
  1622. QScriptValue object =
  1623. engine->newQObject(new QBoxLayout(QBoxLayout::LeftToRight));
  1624. setQBoxLayoutProperties(object, engine);
  1625. return object;
  1626. }
  1627. void setQBoxLayoutProperties(QScriptValue value, QScriptEngine *engine)
  1628. {
  1629. setQLayoutProperties(value, engine);
  1630. value.setProperty("addLayout", engine->newFunction(QBoxLayout_addLayout));
  1631. value.setProperty("addWidget", engine->newFunction(QBoxLayout_addWidget));
  1632. }
  1633. QScriptValue QBoxLayout_addLayout(QScriptContext *context, QScriptEngine *)
  1634. {
  1635. if(context->argumentCount() > 0 && context->argumentCount() < 3)
  1636. {
  1637. QBoxLayout *self = getself<QBoxLayout *>(context);
  1638. QLayout *layout = argument<QLayout *>(0, context);
  1639. int stretch = 0;
  1640. if(context->argumentCount() == 2)
  1641. {
  1642. stretch = argument<int>(1, context);
  1643. }
  1644. if(layout)
  1645. {
  1646. self->addLayout(layout, stretch);
  1647. }
  1648. else
  1649. {
  1650. context->throwError("Incorrect argument type passed to "@|
  1651. "QLayout::addLayout(). This method requires "@|
  1652. "a QLayout.");
  1653. }
  1654. }
  1655. else
  1656. {
  1657. context->throwError("Incorrect number of arguments passed to "@|
  1658. "QLayout::addLayout(). This method takes one "@|
  1659. "QLayout as an argument and optionally one integer.");
  1660. }
  1661. return QScriptValue();
  1662. }
  1663. @ We override the base class wrapper for |addWidget| to add two optional
  1664. arguments: one specifies the stretch factor of the widget and the other
  1665. specifies the alignment of the widget within the layout.
  1666. @<Functions for scripting@>=
  1667. QScriptValue QBoxLayout_addWidget(QScriptContext *context, QScriptEngine *)
  1668. {
  1669. if(context->argumentCount() > 0 && context->argumentCount() < 4)
  1670. {
  1671. QBoxLayout *self = getself<QBoxLayout *>(context);
  1672. QWidget *widget = argument<QWidget *>(0, context);
  1673. int stretch = 0;
  1674. Qt::Alignment alignment = 0;
  1675. if(context->argumentCount() > 1)
  1676. {
  1677. stretch = argument<int>(1, context);
  1678. }
  1679. if(context->argumentCount() > 2)
  1680. {
  1681. alignment = (Qt::Alignment)(argument<int>(2, context));
  1682. }
  1683. if(widget)
  1684. {
  1685. self->addWidget(widget, stretch, alignment);
  1686. }
  1687. else
  1688. {
  1689. context->throwError("Incorrect argument type passed to "@|
  1690. "QBoxLayout::addWidget(). This method requires "@|
  1691. "a QWidget.");
  1692. }
  1693. }
  1694. else
  1695. {
  1696. context->throwError("Incorrect number of arguments passed to "@|
  1697. "QBoxLayout::addWidget(). This method takes one "@|
  1698. "QWidget and optionally up to two integers as "@|
  1699. "arguments.");
  1700. }
  1701. return QScriptValue();
  1702. }
  1703. @* Scripting QAction.
  1704. \noindent The |QAction| class is used in \pn{} to create menu items and respond
  1705. to the selection of these items. Three functions are required for our scripting
  1706. needs with regard to this class.
  1707. @<Function prototypes for scripting@>=
  1708. QScriptValue constructQAction(QScriptContext *context, QScriptEngine *engine);
  1709. QScriptValue QAction_setShortcut(QScriptContext *context,
  1710. QScriptEngine *engine);
  1711. void setQActionProperties(QScriptValue value, QScriptEngine *engine);
  1712. @ The scripting engine must be informed of the constructor.
  1713. @<Set up the scripting engine@>=
  1714. constructor = engine->newFunction(constructQAction);
  1715. value = engine->newQMetaObject(&QAction::staticMetaObject, constructor);
  1716. engine->globalObject().setProperty("QAction", value);
  1717. @ The constructor is simple, however some might sensibly question why the
  1718. |"setShortcut"| property is needed at all. Why not have scripts simply set the
  1719. |shortcut| property of the |QAction| directly? The answer to this is that the
  1720. property expects data of the |QKeySequence| type. While this can be created from
  1721. a |QString|, passing a string to the property through the scripting engine did
  1722. not work at the time this was written.
  1723. @<Functions for scripting@>=
  1724. QScriptValue constructQAction(QScriptContext *, QScriptEngine *engine)
  1725. {
  1726. QScriptValue object = engine->newQObject(new QAction(NULL));
  1727. setQActionProperties(object, engine);
  1728. return object;
  1729. }
  1730. void setQActionProperties(QScriptValue value, QScriptEngine *engine)
  1731. {
  1732. setQObjectProperties(value, engine);
  1733. value.setProperty("setShortcut", engine->newFunction(QAction_setShortcut));
  1734. }
  1735. QScriptValue QAction_setShortcut(QScriptContext *context, QScriptEngine *)
  1736. {
  1737. if(context->argumentCount() == 1)
  1738. {
  1739. QAction *self = getself<@[QAction *@]>(context);
  1740. self->setShortcut(argument<QString>(0, context));
  1741. }
  1742. else
  1743. {
  1744. context->throwError("Incorrect number of arguments passed to "@|
  1745. "QAction::setShortcut(). This method takes one "@|
  1746. "string as an argument.");
  1747. }
  1748. return QScriptValue();
  1749. }
  1750. @* Scripting QFileDialog.
  1751. \noindent |QFileDialog| provides two static member functions which is all that
  1752. we need. The objects returned from these methods are built on the |QDialog|
  1753. abstract base class.
  1754. @<Function prototypes for scripting@>=
  1755. QScriptValue QFileDialog_getOpenFileName(QScriptContext *context,
  1756. QScriptEngine *engine);
  1757. QScriptValue QFileDialog_getSaveFileName(QScriptContext *context,
  1758. QScriptEngine *engine);
  1759. void setQFileDialogProperties(QScriptValue value, QScriptEngine *engine);
  1760. void setQDialogProperties(QScriptValue value, QScriptEngine *engine);
  1761. @ The scripting engine must be informed of the wrapper functions for the static
  1762. methods.
  1763. @<Set up the scripting engine@>=
  1764. value = engine->newQMetaObject(&QFileDialog::staticMetaObject);
  1765. value.setProperty("getOpenFileName",
  1766. engine->newFunction(QFileDialog_getOpenFileName));
  1767. value.setProperty("getSaveFileName",
  1768. engine->newFunction(QFileDialog_getSaveFileName));
  1769. engine->globalObject().setProperty("QFileDialog", value);
  1770. @ This function is just a simple wrapper around the |QFileDialog| method, but
  1771. the object returned has any properties added to the base class available.
  1772. @<Functions for scripting@>=
  1773. QScriptValue QFileDialog_getOpenFileName(QScriptContext *context,
  1774. QScriptEngine *engine)
  1775. {
  1776. QScriptValue retval;
  1777. if(context->argumentCount() == 3)
  1778. {
  1779. QWidget *widget = argument<QWidget *>(0, context);
  1780. if(widget)
  1781. {
  1782. QString caption = argument<QString>(1, context);
  1783. QString dir = argument<QString>(2, context);
  1784. retval = QScriptValue(engine,
  1785. QFileDialog::getOpenFileName(widget, caption,
  1786. dir, "", 0, 0));
  1787. setQFileDialogProperties(retval, engine);
  1788. }
  1789. else
  1790. {
  1791. context->throwError("Incorrect argument type passed to "@|
  1792. "QFileDialog::getOpenFileName(). The first "@|
  1793. "argument to this method must be a QWidget.");
  1794. }
  1795. }
  1796. else
  1797. {
  1798. context->throwError("Incorrect number of arguments passed to "@|
  1799. "QFileDialog::getOpenFileName(). This method "@|
  1800. "takes one QWidget followed by two strings for a "@|
  1801. "total of three arguments.");
  1802. }
  1803. return retval;
  1804. }
  1805. @ Similarly, this just wraps |QFileDialog::getSaveFileName()|.
  1806. @<Functions for scripting@>=
  1807. QScriptValue QFileDialog_getSaveFileName(QScriptContext *context,
  1808. QScriptEngine *engine)
  1809. {
  1810. QScriptValue retval;
  1811. if(context->argumentCount() == 3)
  1812. {
  1813. QWidget *widget = argument<QWidget *>(0, context);
  1814. if(widget)
  1815. {
  1816. QString caption = argument<QString>(1, context);
  1817. QString dir = argument<QString>(2, context);
  1818. retval = QScriptValue(engine,
  1819. QFileDialog::getSaveFileName(widget, caption,
  1820. dir, "", 0, 0));
  1821. setQFileDialogProperties(retval, engine);
  1822. }
  1823. else
  1824. {
  1825. context->throwError("Incorrect argument type passed to "@|
  1826. "QFileDialog::getSaveFileName(). The first "@|
  1827. "argument to this method must be a QWidget.");
  1828. }
  1829. }
  1830. else
  1831. {
  1832. context->throwError("Incorrect number of arguments passed to "@|
  1833. "QFileDialog::getSaveFileName(). This method "@|
  1834. "takes one QWidget followed by two strings for a "@|
  1835. "total of three arguments.");
  1836. }
  1837. return retval;
  1838. }
  1839. @ Adding object hierarchy properties to the objects created above is simple.
  1840. @<Functions for scripting@>=
  1841. void setQFileDialogProperties(QScriptValue value, QScriptEngine *engine)
  1842. {
  1843. setQDialogProperties(value, engine);
  1844. }
  1845. void setQDialogProperties(QScriptValue value, QScriptEngine *engine)
  1846. {
  1847. setQWidgetProperties(value, engine);
  1848. }
  1849. @* Scripting QFile.
  1850. \noindent When using a |QFile| in a script, we only need the constructor and two
  1851. functions for hooking it in with the rest of the object hierarchy.
  1852. @<Function prototypes for scripting@>=
  1853. QScriptValue constructQFile(QScriptContext *context, QScriptEngine *engine);
  1854. void setQFileProperties(QScriptValue value, QScriptEngine *engine);
  1855. QScriptValue QFile_remove(QScriptContext *context, QScriptEngine *engine);
  1856. void setQIODeviceProperties(QScriptValue value, QScriptEngine *engine);
  1857. QScriptValue QIODevice_open(QScriptContext *context, QScriptEngine *engine);
  1858. QScriptValue QIODevice_close(QScriptContext *context, QScriptEngine *engine);
  1859. QScriptValue QIODevice_readToString(QScriptContext *context,
  1860. QScriptEngine *engine);
  1861. QScriptValue QIODevice_putChar(QScriptContext *context, QScriptEngine *engine);
  1862. QScriptValue QIODevice_writeString(QScriptContext *context, QScriptEngine *engine);
  1863. QScriptValue QIODevice_writeBytes(QScriptContext *context, QScriptEngine *engine);
  1864. QScriptValue QIODevice_readBytes(QScriptContext *context, QScriptEngine *engine);
  1865. QScriptValue QIODevice_peek(QScriptContext *context, QScriptEngine *engine);
  1866. QScriptValue QIODevice_read(QScriptContext *context, QScriptEngine *engine);
  1867. @ This function is passed to the scripting engine.
  1868. @<Set up the scripting engine@>=
  1869. constructor = engine->newFunction(constructQFile);
  1870. value = engine->newQMetaObject(&QFile::staticMetaObject, constructor);
  1871. engine->globalObject().setProperty("QFile", value);
  1872. @ The implementation is trivial.
  1873. @<Functions for scripting@>=
  1874. QScriptValue constructQFile(QScriptContext *context, QScriptEngine *engine)
  1875. {
  1876. QScriptValue object =
  1877. engine->newQObject(new QFile(argument<QString>(0, context)));@/
  1878. setQFileProperties(object, engine);
  1879. return object;
  1880. }
  1881. @ |QFile| gets a wrapper around |remove()| to support deleting temporary files.
  1882. @<Functions for scripting@>=
  1883. void setQFileProperties(QScriptValue value, QScriptEngine *engine)
  1884. {
  1885. setQIODeviceProperties(value, engine);
  1886. value.setProperty("remove", engine->newFunction(QFile_remove));
  1887. }
  1888. QScriptValue QFile_remove(QScriptContext *context, QScriptEngine *engine)
  1889. {
  1890. QFile *self = getself<QFile *>(context);
  1891. bool retval = self->remove();
  1892. return QScriptValue(engine, retval);
  1893. }
  1894. @ Although we aren'@q'@>t going to create any instances of |QIODevice| directly,
  1895. subclasses such as |QFile| and |QBuffer| get two additional properties for
  1896. opening and closing the device.
  1897. In order to solve some class interoperability issues, a convenience method is
  1898. also added which is equivalent to creating a |QString| from the |QByteArray|
  1899. returned from the |readAll()| method.
  1900. @<Functions for scripting@>=
  1901. void setQIODeviceProperties(QScriptValue value, QScriptEngine *engine)
  1902. {
  1903. setQObjectProperties(value, engine);
  1904. value.setProperty("open", engine->newFunction(QIODevice_open));
  1905. value.setProperty("close", engine->newFunction(QIODevice_close));
  1906. value.setProperty("readToString",
  1907. engine->newFunction(QIODevice_readToString));
  1908. value.setProperty("putChar", engine->newFunction(QIODevice_putChar));
  1909. value.setProperty("writeString", engine->newFunction(QIODevice_writeString));
  1910. value.setProperty("writeBytes", engine->newFunction(QIODevice_writeBytes));
  1911. value.setProperty("readBytes", engine->newFunction(QIODevice_readBytes));
  1912. value.setProperty("peek", engine->newFunction(QIODevice_peek));
  1913. value.setProperty("read", engine->newFunction(QIODevice_read));
  1914. }
  1915. @ These are simple wrappers. In the case of the |open()| property, one argument
  1916. may be passed specifying the mode used for opening. The supported values for
  1917. this are 1 (Read Only), 2 (Write Only), and 3 (Read Write). If this argument is
  1918. not passed, it is assumed that the user wants read and write access.
  1919. @<Functions for scripting@>=
  1920. QScriptValue QIODevice_open(QScriptContext *context, QScriptEngine *)
  1921. {
  1922. QIODevice *self = getself<QIODevice *>(context);
  1923. bool retval = false;
  1924. if(context->argumentCount() == 1)
  1925. {
  1926. switch(argument<int>(0, context))
  1927. {
  1928. case 1:
  1929. retval = self->open(QIODevice::ReadOnly);
  1930. break;
  1931. case 2:
  1932. retval = self->open(QIODevice::WriteOnly);
  1933. break;
  1934. case 3:
  1935. retval = self->open(QIODevice::ReadWrite);
  1936. break;
  1937. default:
  1938. break;
  1939. }
  1940. }
  1941. else
  1942. {
  1943. retval = self->open(QIODevice::ReadWrite);
  1944. }
  1945. return QScriptValue(retval);
  1946. }
  1947. QScriptValue QIODevice_close(QScriptContext *context, QScriptEngine *)
  1948. {
  1949. QIODevice *self = getself<QIODevice *>(context);
  1950. self->close();
  1951. return QScriptValue();
  1952. }
  1953. @ The |readToString()| method is a simple extension of |QIODevice::readAll()| to
  1954. interface with classes that expect document data in the form of a string. Most
  1955. notably, this includes |QWebView|.
  1956. @<Functions for scripting@>=
  1957. QScriptValue QIODevice_readToString(QScriptContext *context, QScriptEngine *)
  1958. {
  1959. QIODevice *self = getself<QIODevice *>(context);
  1960. self->reset();
  1961. return QScriptValue(QString(self->readAll()));
  1962. }
  1963. @ In support of serial port communications, wrappers around two methods for
  1964. writing data have been added. As these are valid for other classes derived from
  1965. |QIODevice|, they are added here so the functionality is available more
  1966. broadly.
  1967. As we are unable to pass a type that guarantees only a single character, we
  1968. instead accept a string and only pass along the first character.
  1969. @<Functions for scripting@>=
  1970. QScriptValue QIODevice_putChar(QScriptContext *context, QScriptEngine *)
  1971. {
  1972. QIODevice *self = getself<QIODevice *>(context);
  1973. if(context->argumentCount() == 1)
  1974. {
  1975. return QScriptValue(self->putChar(argument<QString>(0, context).toUtf8().at(0)));
  1976. }
  1977. context->throwError("Incorrect number of arguments passed to "@|
  1978. "QIODevice::putChar()");
  1979. return QScriptValue();
  1980. }
  1981. @ Two wrappers are provided around |QIODevice::write()| for outputting
  1982. multi-byte data. If we are writing strings that are valid UTF-8, we can use the
  1983. |writeString| wrapper, but if we require full control over exactly which bytes
  1984. are output, the |writeBytes| wrapper is more appropriate.
  1985. @<Functions for scripting@>=
  1986. QScriptValue QIODevice_writeString(QScriptContext *context, QScriptEngine *)
  1987. {
  1988. QIODevice *self = getself<QIODevice *>(context);
  1989. if(context->argumentCount() == 1)
  1990. {
  1991. self->write(argument<QString>(0, context).toUtf8());
  1992. }
  1993. else
  1994. {
  1995. context->throwError("Incorrect number of arguments passed to "@|
  1996. "QIODevice::writeString()");
  1997. }
  1998. return QScriptValue();
  1999. }
  2000. QScriptValue QIODevice_writeBytes(QScriptContext *context, QScriptEngine *)
  2001. {
  2002. QIODevice *self = getself<QIODevice *>(context);
  2003. if(context->argumentCount() == 1)
  2004. {
  2005. self->write(argument<QByteArray>(0, context));
  2006. }
  2007. else
  2008. {
  2009. context->throwError("Incorrect number of arguments passed to "@|
  2010. "QIODevice::writeBytes()");
  2011. }
  2012. return QScriptValue();
  2013. }
  2014. @ The readBytes method is an alternate wrapper around |QByteArray::readAll()|
  2015. which returns the |QByteArray| instead of converting this to a |QString|.
  2016. @<Functions for scripting@>=
  2017. QScriptValue QIODevice_readBytes(QScriptContext *context, QScriptEngine *engine)
  2018. {
  2019. QIODevice *self = getself<QIODevice *>(context);
  2020. QScriptValue value = engine->toScriptValue<QByteArray>(self->readAll());
  2021. setQByteArrayProperties(value, engine);
  2022. return value;
  2023. }
  2024. @ Wrappers around |peek()| and |read()| are also provided.
  2025. @<Functions for scripting@>=
  2026. QScriptValue QIODevice_peek(QScriptContext *context, QScriptEngine *engine)
  2027. {
  2028. QIODevice *self = getself<QIODevice *>(context);
  2029. QScriptValue value = engine->toScriptValue<QByteArray>(
  2030. self->peek(argument<int>(0, context)));
  2031. setQByteArrayProperties(value, engine);
  2032. return value;
  2033. }
  2034. QScriptValue QIODevice_read(QScriptContext *context, QScriptEngine *engine)
  2035. {
  2036. QIODevice *self = getself<QIODevice *>(context);
  2037. QScriptValue value = engine->toScriptValue<QByteArray>(
  2038. self->read(argument<int>(0, context)));
  2039. setQByteArrayProperties(value, engine);
  2040. return value;
  2041. }
  2042. @* Scripting QProcess.
  2043. \noindent Sometimes it is useful to have \pn work with an external program.
  2044. The initial use case was document generation by typesetting instructions to a
  2045. file and then running \TeX to generate a shelf sign or a sheet of labels.
  2046. Other likely use cases include interfacing with external programs that output
  2047. measurement streams. There are several methods which we may want to expose,
  2048. however this is being done only as needed.
  2049. @<Function prototypes for scripting@>=
  2050. QScriptValue constructQProcess(QScriptContext *context, QScriptEngine *engine);
  2051. void setQProcessProperties(QScriptValue value, QScriptEngine *engine);
  2052. QScriptValue QProcess_execute(QScriptContext *context, QScriptEngine *engine);
  2053. QScriptValue QProcess_startDetached(QScriptContext *context, QScriptEngine *engine);
  2054. QScriptValue QProcess_setWorkingDirectory(QScriptContext *context, QScriptEngine *engine);
  2055. QScriptValue QProcess_start(QScriptContext *context, QScriptEngine *engine);
  2056. @ We follow the same pattern with this as with many other types.
  2057. @<Set up the scripting engine@>=
  2058. constructor = engine->newFunction(constructQProcess);
  2059. value = engine->newQMetaObject(&QProcess::staticMetaObject, constructor);
  2060. engine->globalObject().setProperty("QProcess", value);
  2061. @ The constructor is trivial.
  2062. @<Functions for scripting@>=
  2063. QScriptValue constructQProcess(QScriptContext *, QScriptEngine *engine)
  2064. {
  2065. QScriptValue object = engine->newQObject(new QProcess);
  2066. setQProcessProperties(object, engine);
  2067. return object;
  2068. }
  2069. @ As |QProcess| is a |QIODevice| we inherit some properties from that. We also
  2070. expose some details that are specific to |QProcess|.
  2071. @<Functions for scripting@>=
  2072. void setQProcessProperties(QScriptValue value, QScriptEngine *engine)
  2073. {
  2074. setQIODeviceProperties(value, engine);
  2075. value.setProperty("execute", engine->newFunction(QProcess_execute));
  2076. value.setProperty("startDetached", engine->newFunction(QProcess_startDetached));
  2077. value.setProperty("setWorkingDirectory", engine->newFunction(QProcess_setWorkingDirectory));
  2078. value.setProperty("start", engine->newFunction(QProcess_start));
  2079. }
  2080. @ The |execute()| method comes in two flavors: one with arguments and one without.
  2081. We always call the one with arguments and simply pass in an empty list if no
  2082. arguments are specified.
  2083. @<Functions for scripting@>=
  2084. QScriptValue QProcess_execute(QScriptContext *context, QScriptEngine *)
  2085. {
  2086. QProcess *self = getself<QProcess *>(context);
  2087. QString program = argument<QString>(0, context);
  2088. QStringList arguments = QStringList();
  2089. if(context->argumentCount() > 1) {
  2090. arguments = argument<QVariant>(1, context).toStringList();
  2091. }
  2092. int retval = self->execute(program, arguments);
  2093. return QScriptValue(retval);
  2094. }
  2095. @ Similarly |startDetached()| can be called in a few different ways.
  2096. @<Functions for scripting@>=
  2097. QScriptValue QProcess_startDetached(QScriptContext *context, QScriptEngine *)
  2098. {
  2099. QProcess *self = getself<QProcess *>(context);
  2100. QString program = argument<QString>(0, context);
  2101. QStringList arguments = QStringList();
  2102. if(context->argumentCount() > 1) {
  2103. arguments = argument<QVariant>(1, context).toStringList();
  2104. }
  2105. QString workingDirectory = "";
  2106. if(context->argumentCount() > 2) {
  2107. workingDirectory = argument<QString>(2, context);
  2108. }
  2109. bool retval;
  2110. switch(context->argumentCount())
  2111. {
  2112. case 1:
  2113. retval = self->startDetached(program);
  2114. break;
  2115. case 2:
  2116. retval = self->startDetached(program, arguments);
  2117. break;
  2118. case 3:
  2119. retval = self->startDetached(program, arguments, workingDirectory);
  2120. break;
  2121. default:
  2122. retval = false;
  2123. }
  2124. return QScriptValue(retval);
  2125. }
  2126. @ Sometimes we care about the working directory for our program.
  2127. @<Functions for scripting@>=
  2128. QScriptValue QProcess_setWorkingDirectory(QScriptContext *context, QScriptEngine *)
  2129. {
  2130. QProcess *self = getself<QProcess *>(context);
  2131. QString directory = argument<QString>(0, context);
  2132. self->setWorkingDirectory(directory);
  2133. return QScriptValue();
  2134. }
  2135. @ When using the |start()| method we always assume that we want read and write
  2136. access.
  2137. @<Functions for scripting@>=
  2138. QScriptValue QProcess_start(QScriptContext *context, QScriptEngine *)
  2139. {
  2140. QProcess *self = getself<QProcess *>(context);
  2141. QString program = argument<QString>(0, context);
  2142. QStringList arguments = QStringList();
  2143. if(context->argumentCount() > 1) {
  2144. arguments = argument<QVariant>(1, context).toStringList();
  2145. }
  2146. self->start(program, arguments);
  2147. return QScriptValue();
  2148. }
  2149. @ In order to work with |QByteArray| this should also be exposed to the host
  2150. environment.
  2151. @<Function prototypes for scripting@>=
  2152. QScriptValue QByteArray_toScriptValue(QScriptEngine *engine, const QByteArray &bytes);
  2153. void QByteArray_fromScriptValue(const QScriptValue &value, QByteArray &bytes);
  2154. QScriptValue constructQByteArray(QScriptContext *context, QScriptEngine *engine);
  2155. void setQByteArrayProperties(QScriptValue value, QScriptEngine *engine);
  2156. QScriptValue QByteArray_fromHex(QScriptContext *context, QScriptEngine *engine);
  2157. QScriptValue QByteArray_getAt(QScriptContext *context, QScriptEngine *engine);
  2158. QScriptValue QByteArray_setAt(QScriptContext *context, QScriptEngine *engine);
  2159. QScriptValue QByteArray_appendBytes(QScriptContext *context, QScriptEngine *engine);
  2160. QScriptValue QByteArray_appendString(QScriptContext *context, QScriptEngine *engine);
  2161. QScriptValue QByteArray_size(QScriptContext *context, QScriptEngine *engine);
  2162. QScriptValue QByteArray_left(QScriptContext *context, QScriptEngine *engine);
  2163. QScriptValue QByteArray_right(QScriptContext *context, QScriptEngine *engine);
  2164. QScriptValue QByteArray_mid(QScriptContext *context, QScriptEngine *engine);
  2165. QScriptValue QByteArray_chop(QScriptContext *context, QScriptEngine *engine);
  2166. QScriptValue QByteArray_remove(QScriptContext *context, QScriptEngine *engine);
  2167. QScriptValue QByteArray_toInt8(QScriptContext *context, QScriptEngine *engine);
  2168. QScriptValue QByteArray_toInt16(QScriptContext *context, QScriptEngine *engine);
  2169. QScriptValue QByteArray_toInt32(QScriptContext *context, QScriptEngine *engine);
  2170. QScriptValue QByteArray_toFloat(QScriptContext *context, QScriptEngine *engine);
  2171. QScriptValue QByteArray_toDouble(QScriptContext *context, QScriptEngine *engine);
  2172. @ First, we provide some functionns for moving array data across the
  2173. language barrier.
  2174. @<Functions for scripting@>=
  2175. QScriptValue QByteArray_toScriptValue(QScriptEngine *engine, const QByteArray &bytes)
  2176. {
  2177. QScriptValue object = engine->newVariant(QVariant(bytes));
  2178. setQByteArrayProperties(object, engine);
  2179. return object;
  2180. }
  2181. void QByteArray_fromScriptValue(const QScriptValue &value, QByteArray &bytes)
  2182. {
  2183. bytes = value.toVariant().toByteArray();
  2184. }
  2185. @ We register this our conversion functions and allow creation of new arrays
  2186. next.
  2187. @<Set up the scripting engine@>=
  2188. qScriptRegisterMetaType(engine, QByteArray_toScriptValue, QByteArray_fromScriptValue);
  2189. constructor = engine->newFunction(constructQByteArray);
  2190. engine->globalObject().setProperty("QByteArray", constructor);
  2191. @ The constructor is straightforward.
  2192. @<Functions for scripting@>=
  2193. QScriptValue constructQByteArray(QScriptContext *, QScriptEngine *engine)
  2194. {
  2195. QScriptValue object = engine->toScriptValue<QByteArray>(QByteArray());
  2196. setQByteArrayProperties(object, engine);
  2197. return object;
  2198. }
  2199. @ There are many methods which are not automatically available which we may
  2200. want to have wrappers around. These should be added as required.
  2201. @<Functions for scripting@>=
  2202. void setQByteArrayProperties(QScriptValue value, QScriptEngine *engine)
  2203. {
  2204. value.setProperty("fromHex", engine->newFunction(QByteArray_fromHex));
  2205. value.setProperty("getAt", engine->newFunction(QByteArray_getAt));
  2206. value.setProperty("setAt", engine->newFunction(QByteArray_setAt));
  2207. value.setProperty("appendBytes", engine->newFunction(QByteArray_appendBytes));
  2208. value.setProperty("appendString", engine->newFunction(QByteArray_appendString));
  2209. value.setProperty("size", engine->newFunction(QByteArray_size));
  2210. value.setProperty("left", engine->newFunction(QByteArray_left));
  2211. value.setProperty("right", engine->newFunction(QByteArray_right));
  2212. value.setProperty("mid", engine->newFunction(QByteArray_mid));
  2213. value.setProperty("chop", engine->newFunction(QByteArray_chop));
  2214. value.setProperty("remove", engine->newFunction(QByteArray_remove));
  2215. value.setProperty("toInt8", engine->newFunction(QByteArray_toInt8));
  2216. value.setProperty("toInt16", engine->newFunction(QByteArray_toInt16));
  2217. value.setProperty("toInt32", engine->newFunction(QByteArray_toInt32));
  2218. value.setProperty("toFloat", engine->newFunction(QByteArray_toFloat));
  2219. value.setProperty("toDouble", engine->newFunction(QByteArray_toDouble));
  2220. }
  2221. @ Perhaps the easiest way to deal with fixed byte strings for serial
  2222. communications across script boundaries is to use a hex encoded string.
  2223. @<Functions for scripting@>=
  2224. QScriptValue QByteArray_fromHex(QScriptContext *context, QScriptEngine *engine)
  2225. {
  2226. QByteArray self = getself<QByteArray>(context);
  2227. QByteArray retval;
  2228. retval = self.fromHex(argument<QString>(0, context).toUtf8());
  2229. QScriptValue value = engine->toScriptValue<QByteArray>(retval);
  2230. setQByteArrayProperties(value, engine);
  2231. return value;
  2232. }
  2233. @ A pair of methods is provided for getting and setting values at a particular
  2234. byte.
  2235. @<Functions for scripting@>=
  2236. QScriptValue QByteArray_getAt(QScriptContext *context, QScriptEngine *)
  2237. {
  2238. QByteArray self = getself<QByteArray>(context);
  2239. return QScriptValue((int)(self.at(argument<int>(0, context))));
  2240. }
  2241. QScriptValue QByteArray_setAt(QScriptContext *context, QScriptEngine *)
  2242. {
  2243. QByteArray self = getself<QByteArray>(context);
  2244. self[argument<int>(0, context)] = (char)(argument<int>(1, context));
  2245. return QScriptValue();
  2246. }
  2247. @ Methods are provided for appending either another |QByteArray| or a string
  2248. to a |QByteArray|. The only difference between these functions is the expected
  2249. argument type.
  2250. @<Functions for scripting@>=
  2251. QScriptValue QByteArray_appendBytes(QScriptContext *context, QScriptEngine *engine)
  2252. {
  2253. QByteArray self = getself<QByteArray>(context);
  2254. QScriptValue value =
  2255. engine->toScriptValue<QByteArray>(
  2256. self.append(argument<QByteArray>(0, context)));
  2257. setQByteArrayProperties(value, engine);
  2258. return value;
  2259. }
  2260. QScriptValue QByteArray_appendString(QScriptContext *context, QScriptEngine *engine)
  2261. {
  2262. QByteArray self = getself<QByteArray>(context);
  2263. QScriptValue value = engine->toScriptValue<QByteArray>(
  2264. self.append(argument<QString>(0, context)));
  2265. setQByteArrayProperties(value, engine);
  2266. return value;
  2267. }
  2268. @ Checking the size of our byte array frequently a requirement.
  2269. @<Functions for scripting@>=
  2270. QScriptValue QByteArray_size(QScriptContext *context, QScriptEngine *)
  2271. {
  2272. QByteArray self = getself<QByteArray>(context);
  2273. return QScriptValue(self.size());
  2274. }
  2275. @ It is also frequently useful to be able to work with specific parts of a byte
  2276. array, so a few methods are provided for carving these up.
  2277. @<Functions for scripting@>=
  2278. QScriptValue QByteArray_left(QScriptContext *context, QScriptEngine *engine)
  2279. {
  2280. QByteArray self = getself<QByteArray>(context);
  2281. QScriptValue value = engine->toScriptValue<QByteArray>(
  2282. self.left(argument<int>(0, context)));
  2283. setQByteArrayProperties(value, engine);
  2284. return value;
  2285. }
  2286. QScriptValue QByteArray_right(QScriptContext *context, QScriptEngine *engine)
  2287. {
  2288. QByteArray self = getself<QByteArray>(context);
  2289. QScriptValue value = engine->toScriptValue<QByteArray>(
  2290. self.right(argument<int>(0, context)));
  2291. setQByteArrayProperties(value, engine);
  2292. return value;
  2293. }
  2294. QScriptValue QByteArray_mid(QScriptContext *context, QScriptEngine *engine)
  2295. {
  2296. QByteArray self = getself<QByteArray>(context);
  2297. int length = -1;
  2298. if(context->argumentCount() > 1)
  2299. {
  2300. length = argument<int>(1, context);
  2301. }
  2302. QScriptValue value = engine->toScriptValue<QByteArray>(
  2303. self.mid(argument<int>(0, context), length));
  2304. setQByteArrayProperties(value, engine);
  2305. return value;
  2306. }
  2307. @ We may also want to remove bytes from an array.
  2308. @<Functions for scripting@>=
  2309. QScriptValue QByteArray_chop(QScriptContext *context, QScriptEngine *)
  2310. {
  2311. QByteArray self = getself<QByteArray>(context);
  2312. self.chop(argument<int>(0, context));
  2313. return QScriptValue();
  2314. }
  2315. QScriptValue QByteArray_remove(QScriptContext *context, QScriptEngine *engine)
  2316. {
  2317. QByteArray self = getself<QByteArray>(context);
  2318. QScriptValue value = engine->toScriptValue<QByteArray>(
  2319. self.remove(argument<int>(0, context), argument<int>(1, context)));
  2320. setQByteArrayProperties(value, engine);
  2321. return value;
  2322. }
  2323. @ When receiving data in a byte array, bytes are sometimes intended to
  2324. represent 8, 16, or 32 bit integers. In such cases we often want to perform
  2325. some computation on these values so having the ability to split off that
  2326. portion of the array (for example, with |mid()|) and convert to a Number is
  2327. useful.
  2328. @<Functions for scripting@>=
  2329. QScriptValue QByteArray_toInt8(QScriptContext *context, QScriptEngine *)
  2330. {
  2331. QByteArray self = getself<QByteArray>(context);
  2332. int value = 0;
  2333. char *bytes = (char *)&value;
  2334. bytes[0] = self[0];
  2335. return QScriptValue(value);
  2336. }
  2337. QScriptValue QByteArray_toInt16(QScriptContext *context, QScriptEngine *)
  2338. {
  2339. QByteArray self = getself<QByteArray>(context);
  2340. int value = 0;
  2341. char *bytes = (char *)&value;
  2342. bytes[0] = self[0];
  2343. bytes[1] = self[1];
  2344. return QScriptValue(value);
  2345. }
  2346. QScriptValue QByteArray_toInt32(QScriptContext *context, QScriptEngine *)
  2347. {
  2348. QByteArray self = getself<QByteArray>(context);
  2349. int value = 0;
  2350. char *bytes = (char *)&value;
  2351. bytes[0] = self[0];
  2352. bytes[1] = self[1];
  2353. bytes[2] = self[2];
  2354. bytes[3] = self[3];
  2355. return QScriptValue(value);
  2356. }
  2357. @ Similar methods are provided for converting bytes to a |float| or |double|.
  2358. Note that the return value from |toFloat| will, in the host environment, be
  2359. represented as a |double|.
  2360. @<Functions for scripting@>=
  2361. QScriptValue QByteArray_toFloat(QScriptContext *context, QScriptEngine *)
  2362. {
  2363. QByteArray self = getself<QByteArray>(context);
  2364. float value = 0.0;
  2365. char *bytes = (char *)&value;
  2366. bytes[0] = self[0];
  2367. bytes[1] = self[1];
  2368. bytes[2] = self[2];
  2369. bytes[3] = self[3];
  2370. return QScriptValue(value);
  2371. }
  2372. QScriptValue QByteArray_toDouble(QScriptContext *context, QScriptEngine *)
  2373. {
  2374. QByteArray self = getself<QByteArray>(context);
  2375. double value = 0.0;
  2376. char *bytes = (char *)&value;
  2377. bytes[0] = self[0];
  2378. bytes[1] = self[1];
  2379. bytes[2] = self[2];
  2380. bytes[3] = self[3];
  2381. bytes[4] = self[4];
  2382. bytes[5] = self[5];
  2383. bytes[6] = self[6];
  2384. bytes[7] = self[7];
  2385. return QScriptValue(value);
  2386. }
  2387. @ Some protocols require manipulating larger than 8 bit numbers as a sequence
  2388. of bytes. To facilitate this, methods are provided to construct a |QByteArray|
  2389. from different sized numbers. 8 bit numbers are provided for uniformity.
  2390. @<Function prototypes for scripting@>=
  2391. QScriptValue bytesFromInt8(QScriptContext *context, QScriptEngine *engine);
  2392. QScriptValue bytesFromInt16(QScriptContext *context, QScriptEngine *engine);
  2393. QScriptValue bytesFromInt32(QScriptContext *context, QScriptEngine *engine);
  2394. QScriptValue bytesFromFloat(QScriptContext *context, QScriptEngine *engine);
  2395. QScriptValue bytesFromDouble(QScriptContext *context, QScriptEngine *engine);
  2396. @ These are globally available.
  2397. @<Set up the scripting engine@>=
  2398. engine->globalObject().setProperty("bytesFromInt8", engine->newFunction(bytesFromInt8));
  2399. engine->globalObject().setProperty("bytesFromInt16", engine->newFunction(bytesFromInt16));
  2400. engine->globalObject().setProperty("bytesFromInt32", engine->newFunction(bytesFromInt32));
  2401. engine->globalObject().setProperty("bytesFromFloat", engine->newFunction(bytesFromFloat));
  2402. engine->globalObject().setProperty("bytesFromDouble", engine->newFunction(bytesFromDouble));
  2403. @ The methods all work by casting the appropriate numeric type to a |char *|
  2404. and copying the bytes to a new |QByteArray|. Note that the ECMA-262 standard
  2405. only has one type of number and this is an IEEE 754 binary64 double precision
  2406. floating point number. Functions other than |bytesFromDouble| will be cast
  2407. from |double|.
  2408. @<Functions for scripting@>=
  2409. QScriptValue bytesFromInt8(QScriptContext *context, QScriptEngine *engine)
  2410. {
  2411. qint8 value = (qint8)(argument<int>(0, context));
  2412. char *bytes = (char *)&value;
  2413. QByteArray retval;
  2414. retval.resize(1);
  2415. retval[0] = bytes[0];
  2416. QScriptValue v = engine->toScriptValue<QByteArray>(retval);
  2417. setQByteArrayProperties(v, engine);
  2418. return v;
  2419. }
  2420. QScriptValue bytesFromInt16(QScriptContext *context, QScriptEngine *engine)
  2421. {
  2422. qint16 value = (qint16)(argument<int>(0, context));
  2423. char *bytes = (char *)&value;
  2424. QByteArray retval;
  2425. retval.resize(2);
  2426. retval[0] = bytes[0];
  2427. retval[1] = bytes[1];
  2428. QScriptValue v = engine->toScriptValue<QByteArray>(retval);
  2429. setQByteArrayProperties(v, engine);
  2430. return v;
  2431. }
  2432. QScriptValue bytesFromInt32(QScriptContext *context, QScriptEngine *engine)
  2433. {
  2434. qint32 value = (qint32)(argument<int>(0, context));
  2435. char *bytes = (char *)&value;
  2436. QByteArray retval;
  2437. retval.resize(4);
  2438. retval[0] = bytes[0];
  2439. retval[1] = bytes[1];
  2440. retval[2] = bytes[2];
  2441. retval[3] = bytes[3];
  2442. QScriptValue v = engine->toScriptValue<QByteArray>(retval);
  2443. setQByteArrayProperties(v, engine);
  2444. return v;
  2445. }
  2446. QScriptValue bytesFromFloat(QScriptContext *context, QScriptEngine *engine)
  2447. {
  2448. float value = (float)(argument<double>(0, context));
  2449. char *bytes = (char *)&value;
  2450. QByteArray retval;
  2451. retval.resize(4);
  2452. retval[0] = bytes[0];
  2453. retval[1] = bytes[1];
  2454. retval[2] = bytes[2];
  2455. retval[3] = bytes[3];
  2456. QScriptValue v = engine->toScriptValue<QByteArray>(retval);
  2457. setQByteArrayProperties(v, engine);
  2458. return v;
  2459. }
  2460. QScriptValue bytesFromDouble(QScriptContext *context, QScriptEngine *engine)
  2461. {
  2462. double value = (double)(argument<double>(0, context));
  2463. char *bytes = (char *)&value;
  2464. QByteArray retval;
  2465. retval.resize(8);
  2466. retval[0] = bytes[0];
  2467. retval[1] = bytes[1];
  2468. retval[2] = bytes[2];
  2469. retval[3] = bytes[3];
  2470. retval[4] = bytes[4];
  2471. retval[5] = bytes[5];
  2472. retval[6] = bytes[6];
  2473. retval[7] = bytes[7];
  2474. QScriptValue v = engine->toScriptValue<QByteArray>(retval);
  2475. setQByteArrayProperties(v, engine);
  2476. return v;
  2477. }
  2478. @* Scripting QBuffer.
  2479. \noindent Sometimes it is desirable to load a roast profile from a file. At
  2480. other times, it is more useful to load that profile from a byte array stored in
  2481. a database. The |XMLInput| class takes data from a |QIODevice| object, which
  2482. means that we can choose from a |QFile| when we want the former or a |QBuffer|
  2483. when we want the latter.
  2484. @<Function prototypes for scripting@>=
  2485. QScriptValue constructQBuffer(QScriptContext *context, QScriptEngine *engine);
  2486. void setQBufferProperties(QScriptValue value, QScriptEngine *engine);
  2487. QScriptValue QBuffer_setData(QScriptContext *context, QScriptEngine *engine);
  2488. QScriptValue QBuffer_data(QScriptContext *context, QScriptEngine *engine);
  2489. @ The host environment needs to be aware of the constructor.
  2490. @<Set up the scripting engine@>=
  2491. constructor = engine->newFunction(constructQBuffer);
  2492. value = engine->newQMetaObject(&QBuffer::staticMetaObject, constructor);
  2493. engine->globalObject().setProperty("QBuffer", value);
  2494. @ The implementation is trivial.
  2495. @<Functions for scripting@>=
  2496. QScriptValue constructQBuffer(QScriptContext *context, QScriptEngine *engine)
  2497. {
  2498. QByteArray *array = new QByteArray(argument<QString>(0, context).toAscii());
  2499. QScriptValue object = engine->newQObject(new QBuffer(array));
  2500. setQBufferProperties(object, engine);
  2501. return object;
  2502. }
  2503. void setQBufferProperties(QScriptValue value, QScriptEngine *engine)
  2504. {
  2505. setQIODeviceProperties(value, engine);
  2506. value.setProperty("setData", engine->newFunction(QBuffer_setData));
  2507. value.setProperty("data", engine->newFunction(QBuffer_data));
  2508. }
  2509. QScriptValue QBuffer_setData(QScriptContext *context, QScriptEngine *)
  2510. {
  2511. QBuffer *self = getself<QBuffer *>(context);
  2512. self->setData(argument<QString>(0, context).toAscii());
  2513. return QScriptValue();
  2514. }
  2515. QScriptValue QBuffer_data(QScriptContext *context, QScriptEngine *)
  2516. {
  2517. QBuffer *self = getself<QBuffer *>(context);
  2518. return QScriptValue(QString(self->data()));
  2519. }
  2520. @* Scripting QXmlQuery.
  2521. \noindent Sometimes we have some XML data in a file or a buffer and we would
  2522. like to extract certain information from that data in the host environment.
  2523. Rather than write complicated string manipulation routines in an attempt to deal
  2524. with this sensibly, we can use the XQuery language to extract the information we
  2525. want. One common use case for this is extracting all measurements from a roast
  2526. profile that are associated with an annotation.
  2527. @<Function prototypes for scripting@>=
  2528. QScriptValue constructXQuery(QScriptContext *context, QScriptEngine *engine);
  2529. QScriptValue XQuery_bind(QScriptContext *context, QScriptEngine *engine);
  2530. QScriptValue XQuery_exec(QScriptContext *context, QScriptEngine *engine);
  2531. QScriptValue XQuery_setQuery(QScriptContext *context, QScriptEngine *engine);
  2532. QScriptValue XQuery_invalidate(QScriptContext *context, QScriptEngine *engine);
  2533. void setXQueryProperties(QScriptValue value, QScriptEngine *engine);
  2534. @ The constructor must be registered with the host environment. This is done a
  2535. bit differently from most classes as |QXmlQuery| is not a |QObject|.
  2536. @<Set up the scripting engine@>=
  2537. constructor = engine->newFunction(constructXQuery);
  2538. engine->globalObject().setProperty("XQuery", constructor);
  2539. @ The constructor just needs to make sure the functions we want to make
  2540. available are applied. A method is also provided to free the |QXmlQuery|.
  2541. @<Functions for scripting@>=
  2542. QScriptValue constructXQuery(QScriptContext *, QScriptEngine *engine)
  2543. {
  2544. QScriptValue object = engine->toScriptValue<void *>(new QXmlQuery);
  2545. setXQueryProperties(object, engine);
  2546. return object;
  2547. }
  2548. QScriptValue XQuery_invalidate(QScriptContext *context, QScriptEngine *)
  2549. {
  2550. QXmlQuery *self = getself<QXmlQuery *>(context);
  2551. delete self;
  2552. return QScriptValue();
  2553. }
  2554. void setXQueryProperties(QScriptValue value, QScriptEngine *engine)
  2555. {
  2556. value.setProperty("bind", engine->newFunction(XQuery_bind));
  2557. value.setProperty("exec", engine->newFunction(XQuery_exec));
  2558. value.setProperty("setQuery", engine->newFunction(XQuery_setQuery));
  2559. value.setProperty("invalidate", engine->newFunction(XQuery_invalidate));
  2560. }
  2561. @ The |bind()| property can be used to specify a |QIODevice| to be referenced by
  2562. a variable within a query.
  2563. @<Functions for scripting@>=
  2564. QScriptValue XQuery_bind(QScriptContext *context, QScriptEngine *)
  2565. {
  2566. QXmlQuery *self = getself<QXmlQuery *>(context);
  2567. QIODevice *buffer = argument<QIODevice *>(1, context);
  2568. self->bindVariable(argument<QString>(0, context), buffer);
  2569. return QScriptValue();
  2570. }
  2571. @ A method is also required for setting the query we wish to conduct.
  2572. @<Functions for scripting@>=
  2573. QScriptValue XQuery_setQuery(QScriptContext *context, QScriptEngine *)
  2574. {
  2575. QXmlQuery *self = getself<QXmlQuery *>(context);
  2576. self->setQuery(argument<QString>(0, context));
  2577. return QScriptValue();
  2578. }
  2579. @ This method runs the previously specified query.
  2580. @<Functions for scripting@>=
  2581. QScriptValue XQuery_exec(QScriptContext *context, QScriptEngine *)
  2582. {
  2583. QXmlQuery *self = getself<QXmlQuery *>(context);
  2584. QString result;
  2585. self->evaluateTo(&result);
  2586. return QScriptValue(result);
  2587. }
  2588. @* Scripting QXmlStreamWriter.
  2589. \noindent There are some cases where it may be desirable to produce XML from the
  2590. host environment. While there are several ways to accomplish this, the
  2591. |QXmlStreamWriter| class greatly simplifies generating complex XML documents.
  2592. This class is not related to |QObject|, so several functions are needed to
  2593. expose the functionality of this class to the host environment.
  2594. @<Function prototypes for scripting@>=
  2595. QScriptValue constructXmlWriter(QScriptContext *context, QScriptEngine *engine);
  2596. QScriptValue XmlWriter_setDevice(QScriptContext *context,
  2597. QScriptEngine *engine);
  2598. QScriptValue XmlWriter_writeAttribute(QScriptContext *context,
  2599. QScriptEngine *engine);
  2600. QScriptValue XmlWriter_writeCDATA(QScriptContext *context,
  2601. QScriptEngine *engine);
  2602. QScriptValue XmlWriter_writeCharacters(QScriptContext *context,
  2603. QScriptEngine *engine);
  2604. QScriptValue XmlWriter_writeDTD(QScriptContext *context, QScriptEngine *engine);
  2605. QScriptValue XmlWriter_writeEmptyElement(QScriptContext *context,
  2606. QScriptEngine *engine);
  2607. QScriptValue XmlWriter_writeEndDocument(QScriptContext *context,
  2608. QScriptEngine *engine);
  2609. QScriptValue XmlWriter_writeEndElement(QScriptContext *context,
  2610. QScriptEngine *engine);
  2611. QScriptValue XmlWriter_writeEntityReference(QScriptContext *context,
  2612. QScriptEngine *engine);
  2613. QScriptValue XmlWriter_writeProcessingInstruction(QScriptContext *context,
  2614. QScriptEngine *engine);
  2615. QScriptValue XmlWriter_writeStartDocument(QScriptContext *context,
  2616. QScriptEngine *engine);
  2617. QScriptValue XmlWriter_writeStartElement(QScriptContext *context,
  2618. QScriptEngine *engine);
  2619. QScriptValue XmlWriter_writeTextElement(QScriptContext *context,
  2620. QScriptEngine *engine);
  2621. void setXmlWriterProperties(QScriptValue value, QScriptEngine *engine);
  2622. @ The constructor must be registered with the host environment.
  2623. @<Set up the scripting engine@>=
  2624. constructor = engine->newFunction(constructXmlWriter);
  2625. engine->globalObject().setProperty("XmlWriter", constructor);
  2626. @ The constructor takes an optional argument allowing the output device to be
  2627. specified.
  2628. @<Functions for scripting@>=
  2629. QScriptValue constructXmlWriter(QScriptContext *context, QScriptEngine *engine)
  2630. {
  2631. QXmlStreamWriter *retval;
  2632. if(context->argumentCount() == 1)
  2633. {
  2634. retval = new QXmlStreamWriter(argument<QIODevice *>(0, context));
  2635. }
  2636. else
  2637. {
  2638. retval = new QXmlStreamWriter;
  2639. }
  2640. QScriptValue object = engine->toScriptValue<void *>(retval);
  2641. setXmlWriterProperties(object, engine);
  2642. return object;
  2643. }
  2644. void setXmlWriterProperties(QScriptValue value, QScriptEngine *engine)
  2645. {
  2646. value.setProperty("setDevice", engine->newFunction(XmlWriter_setDevice));
  2647. value.setProperty("writeAttribute",
  2648. engine->newFunction(XmlWriter_writeAttribute));
  2649. value.setProperty("writeCDATA", engine->newFunction(XmlWriter_writeCDATA));
  2650. value.setProperty("writeCharacters",
  2651. engine->newFunction(XmlWriter_writeCharacters));
  2652. value.setProperty("writeDTD", engine->newFunction(XmlWriter_writeDTD));
  2653. value.setProperty("writeEmptyElement",
  2654. engine->newFunction(XmlWriter_writeEmptyElement));
  2655. value.setProperty("writeEndDocument",
  2656. engine->newFunction(XmlWriter_writeEndDocument));
  2657. value.setProperty("writeEndElement",
  2658. engine->newFunction(XmlWriter_writeEndElement));
  2659. value.setProperty("writeEntityReference",
  2660. engine->newFunction(XmlWriter_writeEntityReference));
  2661. value.setProperty("writeProcessingInstruction",
  2662. engine->newFunction(XmlWriter_writeProcessingInstruction));
  2663. value.setProperty("writeStartDocument",
  2664. engine->newFunction(XmlWriter_writeStartDocument));
  2665. value.setProperty("writeStartElement",
  2666. engine->newFunction(XmlWriter_writeStartElement));
  2667. value.setProperty("writeTextElement",
  2668. engine->newFunction(XmlWriter_writeTextElement));
  2669. }
  2670. @ If the output device needs to be changed or if one is not passed to the
  2671. constructor, the |setDevice()| method can be used.
  2672. @<Functions for scripting@>=
  2673. QScriptValue XmlWriter_setDevice(QScriptContext *context, QScriptEngine *)
  2674. {
  2675. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2676. QIODevice *device = argument<QIODevice *>(0, context);
  2677. self->setDevice(device);
  2678. return QScriptValue();
  2679. }
  2680. @ The remaining functions are simple wrappers used for writing various types of
  2681. data. After creating a writer and setting the output device, the start of the
  2682. document should be written. One argument is required containing the XML version
  2683. number. Another function handles writing the end of the document.
  2684. @<Functions for scripting@>=
  2685. QScriptValue XmlWriter_writeStartDocument(QScriptContext *context,
  2686. QScriptEngine *)
  2687. {
  2688. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2689. self->writeStartDocument(argument<QString>(0, context));
  2690. return QScriptValue();
  2691. }
  2692. QScriptValue XmlWriter_writeEndDocument(QScriptContext *context,
  2693. QScriptEngine *)
  2694. {
  2695. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2696. self->writeEndDocument();
  2697. return QScriptValue();
  2698. }
  2699. @ After the start of the document, a DTD is commonly needed.
  2700. @<Functions for scripting@>=
  2701. QScriptValue XmlWriter_writeDTD(QScriptContext *context, QScriptEngine *)
  2702. {
  2703. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2704. self->writeDTD(argument<QString>(0, context));
  2705. return QScriptValue();
  2706. }
  2707. @ After this, elements need to be written. For this, we write the start
  2708. element, any attributes needed, character data, and the end element.
  2709. @<Functions for scripting@>=
  2710. QScriptValue XmlWriter_writeStartElement(QScriptContext *context,
  2711. QScriptEngine *)
  2712. {
  2713. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2714. self->writeStartElement(argument<QString>(0, context));
  2715. return QScriptValue();
  2716. }
  2717. QScriptValue XmlWriter_writeAttribute(QScriptContext *context, QScriptEngine *)
  2718. {
  2719. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2720. self->writeAttribute(argument<QString>(0, context),
  2721. argument<QString>(1, context));
  2722. return QScriptValue();
  2723. }
  2724. QScriptValue XmlWriter_writeCharacters(QScriptContext *context, QScriptEngine *)
  2725. {
  2726. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2727. self->writeCharacters(argument<QString>(0, context));
  2728. return QScriptValue();
  2729. }
  2730. QScriptValue XmlWriter_writeEndElement(QScriptContext *context, QScriptEngine *)
  2731. {
  2732. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2733. self->writeEndElement();
  2734. return QScriptValue();
  2735. }
  2736. @ For convenience, two other methods are provided for writing elements. Elements
  2737. which do not require anything between the start and end elements can be created
  2738. with |writeEmptyElement()|. Elements which do not require attributes, but do
  2739. contain text can be created with |writeTextElement()|.
  2740. @<Functions for scripting@>=
  2741. QScriptValue XmlWriter_writeEmptyElement(QScriptContext *context,
  2742. QScriptEngine *)
  2743. {
  2744. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2745. self->writeEmptyElement(argument<QString>(0, context));
  2746. return QScriptValue();
  2747. }
  2748. QScriptValue XmlWriter_writeTextElement(QScriptContext *context,
  2749. QScriptEngine *)
  2750. {
  2751. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2752. self->writeTextElement(argument<QString>(0, context),
  2753. argument<QString>(1, context));
  2754. return QScriptValue();
  2755. }
  2756. @ Less commonly needed are functions for writing CDATA sections, entity
  2757. references, and processing instructions.
  2758. @<Functions for scripting@>=
  2759. QScriptValue XmlWriter_writeCDATA(QScriptContext *context, QScriptEngine *)
  2760. {
  2761. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2762. self->writeCDATA(argument<QString>(0, context));
  2763. return QScriptValue();
  2764. }
  2765. QScriptValue XmlWriter_writeEntityReference(QScriptContext *context,
  2766. QScriptEngine *)
  2767. {
  2768. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2769. self->writeEntityReference(argument<QString>(0, context));
  2770. return QScriptValue();
  2771. }
  2772. QScriptValue XmlWriter_writeProcessingInstruction(QScriptContext *context,
  2773. QScriptEngine *)
  2774. {
  2775. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2776. self->writeProcessingInstruction(argument<QString>(0, context),
  2777. argument<QString>(1, context));
  2778. return QScriptValue();
  2779. }
  2780. @* Scripting QXmlStreamReader.
  2781. \noindent When a serializer is written using |QXmlStreamWriter|, a corresponding
  2782. deserializer should also be written. While there are several possible ways to do
  2783. this, using |QXmlStreamReader| is often the best choice. \pn{} provides a subset
  2784. of the functionality from this class which should be adequate for most purposes.
  2785. @<Function prototypes for scripting@>=
  2786. QScriptValue constructXmlReader(QScriptContext *context, QScriptEngine *engine);
  2787. QScriptValue XmlReader_atEnd(QScriptContext *context, QScriptEngine *engine);
  2788. QScriptValue XmlReader_attribute(QScriptContext *context,
  2789. QScriptEngine *engine);
  2790. QScriptValue XmlReader_hasAttribute(QScriptContext *context,
  2791. QScriptEngine *engine);
  2792. QScriptValue XmlReader_isDTD(QScriptContext *context, QScriptEngine *engine);
  2793. QScriptValue XmlReader_isStartElement(QScriptContext *context,
  2794. QScriptEngine *engine);
  2795. QScriptValue XmlReader_name(QScriptContext *context, QScriptEngine *engine);
  2796. QScriptValue XmlReader_readElementText(QScriptContext *context,
  2797. QScriptEngine *engine);
  2798. QScriptValue XmlReader_readNext(QScriptContext *context, QScriptEngine *engine);
  2799. QScriptValue XmlReader_text(QScriptContext *context, QScriptEngine *engine);
  2800. void setXmlReaderProperties(QScriptValue value, QScriptEngine *engine);
  2801. @ The constructor must be registered with the host environment.
  2802. @<Set up the scripting engine@>=
  2803. constructor = engine->newFunction(constructXmlReader);
  2804. engine->globalObject().setProperty("XmlReader", constructor);
  2805. @ The constructor requires an argument specifying the output device. This can be
  2806. any |QIODevice|. The |open()| method must be called on the device before passing
  2807. it as an argument to this function.
  2808. @<Functions for scripting@>=
  2809. QScriptValue constructXmlReader(QScriptContext *context, QScriptEngine *engine)
  2810. {
  2811. QXmlStreamReader *retval =
  2812. new QXmlStreamReader(argument<QIODevice *>(0, context));
  2813. QScriptValue object = engine->toScriptValue<void *>(retval);
  2814. setXmlReaderProperties(object, engine);
  2815. return object;
  2816. }
  2817. void setXmlReaderProperties(QScriptValue value, QScriptEngine *engine)
  2818. {
  2819. value.setProperty("atEnd", engine->newFunction(XmlReader_atEnd));
  2820. value.setProperty("attribute", engine->newFunction(XmlReader_attribute));
  2821. value.setProperty("hasAttribute",
  2822. engine->newFunction(XmlReader_hasAttribute));
  2823. value.setProperty("isDTD", engine->newFunction(XmlReader_isDTD));
  2824. value.setProperty("isStartElement",
  2825. engine->newFunction(XmlReader_isStartElement));
  2826. value.setProperty("name", engine->newFunction(XmlReader_name));
  2827. value.setProperty("readElementText",
  2828. engine->newFunction(XmlReader_readElementText));
  2829. value.setProperty("readNext",
  2830. engine->newFunction(XmlReader_readNext));
  2831. value.setProperty("text", engine->newFunction(XmlReader_text));
  2832. }
  2833. @ Most of the functions are simple member function wrappers. Two of these
  2834. properties are not. These are the |attribute()| and |hasAttribute()| properties.
  2835. @<Functions for scripting@>=
  2836. QScriptValue XmlReader_attribute(QScriptContext *context, QScriptEngine *)
  2837. {
  2838. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2839. QString retval =
  2840. self->attributes().value(argument<QString>(0, context)).toString();
  2841. return QScriptValue(retval);
  2842. }
  2843. QScriptValue XmlReader_hasAttribute(QScriptContext *context, QScriptEngine *)
  2844. {
  2845. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2846. bool retval =
  2847. self->attributes().hasAttribute(argument<QString>(0, context));
  2848. return QScriptValue(retval);
  2849. }
  2850. @ Other properties can be used for determining how to proceed with the
  2851. processing.
  2852. @<Functions for scripting@>=
  2853. QScriptValue XmlReader_atEnd(QScriptContext *context, QScriptEngine *)
  2854. {
  2855. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2856. return QScriptValue(self->atEnd());
  2857. }
  2858. QScriptValue XmlReader_isDTD(QScriptContext *context, QScriptEngine *)
  2859. {
  2860. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2861. return QScriptValue(self->isDTD());
  2862. }
  2863. QScriptValue XmlReader_isStartElement(QScriptContext *context, QScriptEngine *)
  2864. {
  2865. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2866. return QScriptValue(self->isStartElement());
  2867. }
  2868. @ We move from one element to the next with the |readNext()| property.
  2869. @<Functions for scripting@>=
  2870. QScriptValue XmlReader_readNext(QScriptContext *context, QScriptEngine *)
  2871. {
  2872. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2873. self->readNext();
  2874. return QScriptValue();
  2875. }
  2876. @ The remaining properties return the element name and text.
  2877. @<Functions for scripting@>=
  2878. QScriptValue XmlReader_name(QScriptContext *context, QScriptEngine *)
  2879. {
  2880. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2881. return QScriptValue(self->name().toString());
  2882. }
  2883. QScriptValue XmlReader_readElementText(QScriptContext *context, QScriptEngine *)
  2884. {
  2885. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2886. return QScriptValue(self->readElementText());
  2887. }
  2888. QScriptValue XmlReader_text(QScriptContext *context, QScriptEngine *)
  2889. {
  2890. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2891. return QScriptValue(self->text().toString());
  2892. }
  2893. @* Scripting QSettings.
  2894. \noindent Rather than have a script create a |QSettings| object when it needs to
  2895. save or load settings, the object is provided along with properties for getting
  2896. and setting values. Two functions are needed for this along with a third which
  2897. ensures any properties added to |QObject| are also available to |QSettings| from
  2898. the host environment.
  2899. @<Function prototypes for scripting@>=
  2900. QScriptValue QSettings_value(QScriptContext *context, QScriptEngine *engine);
  2901. QScriptValue QSettings_setValue(QScriptContext *context, QScriptEngine *engine);
  2902. void setQSettingsProperties(QScriptValue value, QScriptEngine *engine);
  2903. @ The object with properties for these functions is passed to the scripting
  2904. engine.
  2905. @<Set up the scripting engine@>=
  2906. value = engine->newQObject(&settings);
  2907. setQSettingsProperties(value, engine);
  2908. engine->globalObject().setProperty("QSettings", value);
  2909. @ Adding properties to the |QSettings| object should seem familiar.
  2910. @<Functions for scripting@>=
  2911. void setQSettingsProperties(QScriptValue value, QScriptEngine *engine)
  2912. {
  2913. setQObjectProperties(value, engine);
  2914. value.setProperty("value", engine->newFunction(QSettings_value));
  2915. value.setProperty("setValue", engine->newFunction(QSettings_setValue));
  2916. }
  2917. @ When getting a value from saved settings, there is the possibility that there
  2918. will not be a value saved for the requested key. An optional second argument can
  2919. be used to supply a default value.
  2920. @<Functions for scripting@>=
  2921. QScriptValue QSettings_value(QScriptContext *context, QScriptEngine *engine)
  2922. {
  2923. QScriptValue object;
  2924. if(context->argumentCount() == 1 || context->argumentCount() == 2)
  2925. {
  2926. QSettings settings;
  2927. QString key = argument<QString>(0, context);
  2928. QVariant value;
  2929. QVariant retval;
  2930. if(context->argumentCount() > 1)
  2931. {
  2932. value = argument<QVariant>(1, context);
  2933. retval = settings.value(key, value);
  2934. }
  2935. else
  2936. {
  2937. retval = settings.value(key);
  2938. }
  2939. object = engine->newVariant(retval);
  2940. }
  2941. else
  2942. {
  2943. context->throwError("Incorrect number of arguments passed to "@|
  2944. "QSettings::value(). This method takes one "@|
  2945. "string and one optional variant type.");
  2946. }
  2947. return object;
  2948. }
  2949. QScriptValue QSettings_setValue(QScriptContext *context, QScriptEngine *)
  2950. {
  2951. if(context->argumentCount() == 2)
  2952. {
  2953. QSettings settings;
  2954. QString key = argument<QString>(0, context);
  2955. QVariant value = argument<QVariant>(1, context);
  2956. settings.setValue(key, value);
  2957. }
  2958. else
  2959. {
  2960. context->throwError("Incorrect number of arguments passed to "@|
  2961. "QSettings::setValue(). This method takes one "@|
  2962. "string and one variant type for a total of two "@|
  2963. "arguments.");
  2964. }
  2965. return QScriptValue();
  2966. }
  2967. @* Scripting QLCDNumber.
  2968. \noindent |QLCDNumber| is used as a base class for \pn{}'@q'@>s |TemperatureDisplay|
  2969. and |TimerDisplay| classes, but it can also be used on its own for the display
  2970. of mainly numeric information.
  2971. @<Function prototypes for scripting@>=
  2972. QScriptValue constructQLCDNumber(QScriptContext *context,
  2973. QScriptEngine *engine);
  2974. void setQLCDNumberProperties(QScriptValue value, QScriptEngine *engine);
  2975. @ The constructor must be passed to the scripting engine.
  2976. @<Set up the scripting engine@>=
  2977. constructor = engine->newFunction(constructQLCDNumber);
  2978. value = engine->newQMetaObject(&QLCDNumber::staticMetaObject, constructor);
  2979. engine->globalObject().setProperty("QLCDNumber", value);
  2980. @ There is nothing special about the implementation.
  2981. @<Functions for scripting@>=
  2982. QScriptValue constructQLCDNumber(QScriptContext *, QScriptEngine *engine)
  2983. {
  2984. QScriptValue object = engine->newQObject(new QLCDNumber());
  2985. setQLCDNumberProperties(object, engine);
  2986. return object;
  2987. }
  2988. void setQLCDNumberProperties(QScriptValue value, QScriptEngine *engine)
  2989. {
  2990. setQFrameProperties(value, engine);
  2991. }
  2992. @* Scripting QTime.
  2993. \noindent |QTime| is a little different from the classes examined so far. This
  2994. class can be used for synchonizing time among various objects by creating a
  2995. common base reference time. This should not be needed as ECMA-262 already
  2996. specifies a |Date| class, however this has historically been troublesome to use.
  2997. One thing that makes this class different is that it is not related to
  2998. |QObject|. This makes usefully exposing it to the scripting engine a little more
  2999. difficult.
  3000. @<Function prototypes for scripting@>=
  3001. QScriptValue constructQTime(QScriptContext *context, QScriptEngine *engine);
  3002. QScriptValue QTime_addMSecs(QScriptContext *context, QScriptEngine *engine);
  3003. QScriptValue QTime_addSecs(QScriptContext *context, QScriptEngine *engine);
  3004. QScriptValue QTime_elapsed(QScriptContext *context, QScriptEngine *engine);
  3005. QScriptValue QTime_hour(QScriptContext *context, QScriptEngine *engine);
  3006. QScriptValue QTime_isNull(QScriptContext *context, QScriptEngine *engine);
  3007. QScriptValue QTime_isValid(QScriptContext *context, QScriptEngine *engine);
  3008. QScriptValue QTime_minute(QScriptContext *context, QScriptEngine *engine);
  3009. QScriptValue QTime_msec(QScriptContext *context, QScriptEngine *engine);
  3010. QScriptValue QTime_msecsTo(QScriptContext *context, QScriptEngine *engine);
  3011. QScriptValue QTime_restart(QScriptContext *context, QScriptEngine *engine);
  3012. QScriptValue QTime_second(QScriptContext *context, QScriptEngine *engine);
  3013. QScriptValue QTime_secsTo(QScriptContext *context, QScriptEngine *engine);
  3014. QScriptValue QTime_setHMS(QScriptContext *context, QScriptEngine *engine);
  3015. QScriptValue QTime_start(QScriptContext *context, QScriptEngine *engine);
  3016. QScriptValue QTime_toString(QScriptContext *context, QScriptEngine *engine);
  3017. QScriptValue QTime_currentTime(QScriptContext *context, QScriptEngine *engine);
  3018. QScriptValue QTime_fromString(QScriptContext *context, QScriptEngine *engine);
  3019. QScriptValue QTime_valueOf(QScriptContext *context, QScriptEngine *engine);
  3020. void setQTimeProperties(QScriptValue value, QScriptEngine *engine);
  3021. @ We must tell the script engine about the constructor. This is not done in
  3022. quite the same way as is done for |QObject| derived types.
  3023. @<Set up the scripting engine@>=
  3024. constructor = engine->newFunction(constructQTime);
  3025. engine->globalObject().setProperty("QTime", constructor);
  3026. @ The constructor has a couple interesting twists. The first is the ability to
  3027. accept a variable number of integer arguments. The other is that |QTime| is not
  3028. derived from |QObject|. The lack of |break| statements in the |switch| is
  3029. intended.
  3030. @<Functions for scripting@>=
  3031. QScriptValue constructQTime(QScriptContext *context,
  3032. QScriptEngine *engine)
  3033. {
  3034. QScriptValue object;
  3035. if(context->argumentCount() == 0 ||
  3036. (context->argumentCount() >= 2 && context->argumentCount() <= 4))@/
  3037. {
  3038. int arg1 = 0;
  3039. int arg2 = 0;
  3040. int arg3 = 0;
  3041. int arg4 = 0;
  3042. switch(context->argumentCount())
  3043. {@t\1@>@/
  3044. case 4:@/
  3045. arg4 = argument<int>(3, context);
  3046. case 3:@/
  3047. arg3 = argument<int>(2, context);
  3048. case 2:@/
  3049. arg2 = argument<int>(1, context);
  3050. arg1 = argument<int>(0, context);
  3051. default:@/
  3052. break;@t\2@>@/
  3053. }
  3054. if(context->argumentCount())
  3055. {
  3056. object = engine->toScriptValue<QTime>(QTime(arg1, arg2, arg3,
  3057. arg4));
  3058. }
  3059. else
  3060. {
  3061. object = engine->toScriptValue<QTime>(QTime());
  3062. }
  3063. setQTimeProperties(object, engine);
  3064. }
  3065. else
  3066. {
  3067. context->throwError("Incorrect number of arguments passed to "@|
  3068. "QTime::QTime(). This method takes zero, two, "@|
  3069. "three, or four integer arguments.");
  3070. }
  3071. return object;
  3072. }
  3073. @ In order to use the various |QTime| methods, we must add wrapper functions as
  3074. properties of newly created script objects. The last two of these should really
  3075. be callable without starting from an existing |QTime|.
  3076. @<Functions for scripting@>=
  3077. void setQTimeProperties(QScriptValue value, QScriptEngine *engine)
  3078. {
  3079. value.setProperty("addMSecs", engine->newFunction(QTime_addMSecs));
  3080. value.setProperty("addSecs", engine->newFunction(QTime_addSecs));
  3081. value.setProperty("elapsed", engine->newFunction(QTime_elapsed));
  3082. value.setProperty("hour", engine->newFunction(QTime_hour));
  3083. value.setProperty("isNull", engine->newFunction(QTime_isNull));
  3084. value.setProperty("isValid", engine->newFunction(QTime_isValid));
  3085. value.setProperty("minute", engine->newFunction(QTime_minute));
  3086. value.setProperty("msec", engine->newFunction(QTime_msec));
  3087. value.setProperty("msecsTo", engine->newFunction(QTime_msecsTo));
  3088. value.setProperty("restart", engine->newFunction(QTime_restart));
  3089. value.setProperty("second", engine->newFunction(QTime_second));
  3090. value.setProperty("secsTo", engine->newFunction(QTime_secsTo));
  3091. value.setProperty("setHMS", engine->newFunction(QTime_setHMS));
  3092. value.setProperty("start", engine->newFunction(QTime_start));
  3093. value.setProperty("toString", engine->newFunction(QTime_toString));
  3094. value.setProperty("currentTime", engine->newFunction(QTime_currentTime));
  3095. value.setProperty("fromString", engine->newFunction(QTime_fromString));
  3096. value.setProperty("valueOf", engine->newFunction(QTime_valueOf));
  3097. }
  3098. @ The |valueOf()| method exposes a numeric representation of the time
  3099. suitable for use in comparing two time values. With this it is possible to
  3100. take two |QTime| values in script code {\tt t1} and {\tt t2} and get the
  3101. expected results from {\tt t1 == t2}, {\tt t1 < t2}, {\tt t1 > t2} and
  3102. similar comparative operations.
  3103. @<Functions for scripting@>=
  3104. QScriptValue QTime_valueOf(QScriptContext *context, QScriptEngine *)
  3105. {
  3106. QTime self = getself<QTime>(context);
  3107. int retval = (self.hour() * 60 * 60 * 1000) + (self.minute() * 60 * 1000) +
  3108. (self.second() * 1000) + self.msec();
  3109. return QScriptValue(retval);
  3110. }
  3111. @ These functions are effectively wrapper functions around existing |QTime|
  3112. functionality with some error checking for the scripting engine.
  3113. The |addMSecs()| and |addSecs()| methods return a new |QTime| object.
  3114. @<Functions for scripting@>=
  3115. QScriptValue QTime_addMSecs(QScriptContext *context, QScriptEngine *engine)
  3116. {
  3117. QTime time;
  3118. QScriptValue retval;
  3119. if(context->argumentCount() == 1)
  3120. {
  3121. QTime self = getself<QTime>(context);
  3122. time = self.addMSecs(argument<int>(0, context));
  3123. retval = engine->toScriptValue<QTime>(time);
  3124. setQTimeProperties(retval, engine);
  3125. }
  3126. else
  3127. {
  3128. context->throwError("Incorrect number of arguments passed to "@|
  3129. "QTime::addMSecs(). This method takes one "@|
  3130. "integer as an argument.");
  3131. }
  3132. return retval;
  3133. }
  3134. QScriptValue QTime_addSecs(QScriptContext *context, QScriptEngine *engine)
  3135. {
  3136. QTime time;
  3137. QScriptValue retval;
  3138. if(context->argumentCount() == 1)
  3139. {
  3140. QTime self = getself<QTime>(context);
  3141. time = self.addSecs(argument<int>(0, context));
  3142. retval = engine->toScriptValue<QTime>(time);
  3143. setQTimeProperties(retval, engine);
  3144. }
  3145. else
  3146. {
  3147. context->throwError("Incorrect number of arguments passed to "@|
  3148. "QTime::addSecs(). This method takes one "@|
  3149. "integer as an argument.");
  3150. }
  3151. return retval;
  3152. }
  3153. @ The |elapsed()| method returns an integer value.
  3154. @<Functions for scripting@>=
  3155. QScriptValue QTime_elapsed(QScriptContext *context, QScriptEngine *engine)
  3156. {
  3157. QScriptValue retval;
  3158. if(context->argumentCount() == 0)
  3159. {
  3160. QTime self = getself<QTime>(context);
  3161. retval = QScriptValue(engine, self.elapsed());
  3162. }
  3163. else
  3164. {
  3165. context->throwError("Incorrect number of arguments passed to "@|
  3166. "QTime::elapsed(). This method takes no "@|
  3167. "arguments.");
  3168. }
  3169. return retval;
  3170. }
  3171. @ The |hour()|, |minute()|, |second()| and |msec()| methods return an integer
  3172. with various parts of the time. The |hour()| method is typical of these methods.
  3173. @<Functions for scripting@>=
  3174. QScriptValue QTime_hour(QScriptContext *context, QScriptEngine *engine)
  3175. {
  3176. QScriptValue retval;
  3177. if(context->argumentCount() == 0)
  3178. {
  3179. QTime self = getself<QTime>(context);
  3180. retval = QScriptValue(engine, self.hour());
  3181. }
  3182. else
  3183. {
  3184. context->throwError("Incorrect number of arguments passed to "@|
  3185. "QTime::hour(). This method takes no "@|
  3186. "arguments.");
  3187. }
  3188. return retval;
  3189. }
  3190. @ The |minute()|, |second()|, and |msec()| methods are implemented similarly.
  3191. @<Functions for scripting@>=
  3192. QScriptValue QTime_minute(QScriptContext *context, QScriptEngine *engine)
  3193. {
  3194. QScriptValue retval;
  3195. if(context->argumentCount() == 0)
  3196. {
  3197. QTime self = getself<QTime>(context);
  3198. retval = QScriptValue(engine, self.minute());
  3199. }
  3200. else
  3201. {
  3202. context->throwError("Incorrect number of arguments passed to "@|
  3203. "QTime::minute(). This method takes no "@|
  3204. "arguments.");
  3205. }
  3206. return retval;
  3207. }
  3208. QScriptValue QTime_second(QScriptContext *context, QScriptEngine *engine)
  3209. {
  3210. QScriptValue retval;
  3211. if(context->argumentCount() == 0)
  3212. {
  3213. QTime self = getself<QTime>(context);
  3214. retval = QScriptValue(engine, self.second());
  3215. }
  3216. else
  3217. {
  3218. context->throwError("Incorrect number of arguments passed to "@|
  3219. "QTime::second(). This method takes no "@|
  3220. "arguments.");
  3221. }
  3222. return retval;
  3223. }
  3224. QScriptValue QTime_msec(QScriptContext *context, QScriptEngine *engine)
  3225. {
  3226. QScriptValue retval;
  3227. if(context->argumentCount() == 0)
  3228. {
  3229. QTime self = getself<QTime>(context);
  3230. retval = QScriptValue(engine, self.msec());
  3231. }
  3232. else
  3233. {
  3234. context->throwError("Incorrect number of arguments passed to "@|
  3235. "QTime::msec(). This method takes no "@|
  3236. "arguments.");
  3237. }
  3238. return retval;
  3239. }
  3240. @ The |isNull()| and |isValid()| methods return a boolean value. A |QTime| is
  3241. considered null if it was created with a constructor with no arguments. It is
  3242. considered invalid if it is null or if part of the time is out of range.
  3243. @<Functions for scripting@>=
  3244. QScriptValue QTime_isNull(QScriptContext *context, QScriptEngine *engine)
  3245. {
  3246. QScriptValue retval;
  3247. if(context->argumentCount() == 0)
  3248. {
  3249. QTime self = getself<QTime>(context);
  3250. retval = QScriptValue(engine, self.isNull());
  3251. }
  3252. else
  3253. {
  3254. context->throwError("Incorrect number of arguments passed to "@|
  3255. "QTime::isNull(). This method takes no "@|
  3256. "arguments.");
  3257. }
  3258. return retval;
  3259. }
  3260. QScriptValue QTime_isValid(QScriptContext *context, QScriptEngine *engine)
  3261. {
  3262. QScriptValue retval;
  3263. if(context->argumentCount() == 0)
  3264. {
  3265. QTime self = getself<QTime>(context);
  3266. retval = QScriptValue(engine, self.isValid());
  3267. }
  3268. else
  3269. {
  3270. context->throwError("Incorrect number of arguments passed to "@|
  3271. "QTime::isValid(). This method takes no "@|
  3272. "arguments.");
  3273. }
  3274. return retval;
  3275. }
  3276. @ The |secsTo()| and |msecsTo()| methods return an integer value indicating the
  3277. number of seconds or milliseconds until a |QTime| argument.
  3278. @<Functions for scripting@>=
  3279. QScriptValue QTime_msecsTo(QScriptContext *context, QScriptEngine *engine)
  3280. {
  3281. QScriptValue retval;
  3282. if(context->argumentCount() == 1)
  3283. {
  3284. QTime self = getself<QTime>(context);
  3285. QTime arg = argument<QVariant>(0, context).toTime();
  3286. retval = QScriptValue(engine, self.msecsTo(arg));
  3287. }
  3288. else
  3289. {
  3290. context->throwError("Incorrect number of arguments passed to "@|
  3291. "QTime::msecsTo(). This method takes one QTime.");
  3292. }
  3293. return retval;
  3294. }
  3295. QScriptValue QTime_secsTo(QScriptContext *context, QScriptEngine *engine)
  3296. {
  3297. QScriptValue retval;
  3298. if(context->argumentCount() == 1)
  3299. {
  3300. QTime self = getself<QTime>(context);
  3301. QTime arg = argument<QVariant>(0, context).toTime();
  3302. retval = QScriptValue(engine, self.secsTo(arg));
  3303. }
  3304. else
  3305. {
  3306. context->throwError("Incorrect number of arguments passed to "@|
  3307. "QTime::secsTo(). This method takes one QTime.");
  3308. }
  3309. return retval;
  3310. }
  3311. @ The |start()| and |restart()| methods each set the value of the |QTime()| to
  3312. the current time. The |restart()| method additionally returns the same value as
  3313. the |elapsed()| method.
  3314. @<Functions for scripting@>=
  3315. QScriptValue QTime_restart(QScriptContext *context, QScriptEngine *engine)
  3316. {
  3317. QScriptValue retval;
  3318. if(context->argumentCount() == 0)
  3319. {
  3320. QTime self = getself<QTime>(context);
  3321. retval = QScriptValue(engine, self.restart());
  3322. }
  3323. else
  3324. {
  3325. context->throwError("Incorrect number of arguments passed to "@|
  3326. "QTime::restart(). This method takes no "@|
  3327. "arguments.");
  3328. }
  3329. return retval;
  3330. }
  3331. QScriptValue QTime_start(QScriptContext *context, QScriptEngine *)
  3332. {
  3333. if(context->argumentCount() == 0)
  3334. {
  3335. QTime self = getself<QTime>(context);
  3336. self.start();
  3337. }
  3338. else
  3339. {
  3340. context->throwError("Incorrect number of arguments passed to "@|
  3341. "QTime::start(). This method takes no arguments.");
  3342. }
  3343. return QScriptValue();
  3344. }
  3345. @ The slightly inappropriately named |setHMS()| method changes the current value
  3346. of the time and returns a boolean to indicate if the new time value is valid.
  3347. @<Functions for scripting@>=
  3348. QScriptValue QTime_setHMS(QScriptContext *context, QScriptEngine *engine)
  3349. {
  3350. QScriptValue retval;
  3351. if(context->argumentCount() == 3 || context->argumentCount() == 4)
  3352. {
  3353. QTime self = getself<QTime>(context);
  3354. int arg1 = 0;
  3355. int arg2 = 0;
  3356. int arg3 = 0;
  3357. int arg4 = 0;
  3358. switch(context->argumentCount())@/
  3359. {@t\1@>@/
  3360. case 4:@/
  3361. arg4 = argument<int>(3, context);
  3362. case 3:@/
  3363. arg3 = argument<int>(2, context);
  3364. arg2 = argument<int>(1, context);
  3365. arg1 = argument<int>(0, context);
  3366. default:@/
  3367. break;@t\2@>@/
  3368. }
  3369. retval = QScriptValue(engine, self.setHMS(arg1, arg2, arg3, arg4));
  3370. }
  3371. else
  3372. {
  3373. context->throwError("Incorrect number of arguments passed to "@|
  3374. "QTime::setHMS(). This method takes three or "@|
  3375. "four integer arguments.");
  3376. }
  3377. return retval;
  3378. }
  3379. @ The |toString()| method returns a string representation of the time. See the
  3380. Qt documentation for instructions on creating a valid format string.
  3381. @<Functions for scripting@>=
  3382. QScriptValue QTime_toString(QScriptContext *context, QScriptEngine *engine)
  3383. {
  3384. QScriptValue retval;
  3385. if(context->argumentCount() == 1)
  3386. {
  3387. QTime self = getself<QTime>(context);
  3388. retval = QScriptValue(engine, self.toString(argument<QString>(0, context)));
  3389. }
  3390. else
  3391. {
  3392. context->throwError("Incorrect number of arguments passed to "@|
  3393. "QTime::toString(). This method takes one QString "@|
  3394. "as an argument.");
  3395. }
  3396. return retval;
  3397. }
  3398. @ The |currentTime()| and |fromString()| methods return a new |QTime| object.
  3399. These methods make no reference to the any other existing |QTime|.
  3400. @<Functions for scripting@>=
  3401. QScriptValue QTime_currentTime(QScriptContext *, QScriptEngine *engine)
  3402. {
  3403. QScriptValue object;
  3404. object = engine->toScriptValue<QTime>(QTime::currentTime());
  3405. setQTimeProperties(object, engine);
  3406. return object;
  3407. }
  3408. QScriptValue QTime_fromString(QScriptContext *context, QScriptEngine *engine)
  3409. {
  3410. QScriptValue object;
  3411. if(context->argumentCount() == 2)
  3412. {
  3413. QString time = argument<QString>(0, context);
  3414. QString format = argument<QString>(1, context);
  3415. object = engine->toScriptValue<QTime>(QTime::fromString(time, format));
  3416. setQTimeProperties(object, engine);
  3417. }
  3418. else
  3419. {
  3420. context->throwError("Incorrect number of arguments passed to "@|
  3421. "QTime::fromString(). This method takes two "@|
  3422. "string arguments.");
  3423. }
  3424. return object;
  3425. }
  3426. @ In order to pass |QTime| objects back from a script, we also need to overload
  3427. |argument()| for this type.
  3428. @<Functions for scripting@>=
  3429. template<> QTime argument(int arg, QScriptContext *context)
  3430. {
  3431. return qscriptvalue_cast<QTime>(context->argument(arg));
  3432. }
  3433. @* Scripting Item View Classes.
  3434. \noindent |QAbstractScrollArea| is a |QFrame| that serves as the base class for
  3435. classes such as |QGraphicsView| and |QAbstractItemView|. Objects from this class
  3436. are not created directly.
  3437. @<Function prototypes for scripting@>=
  3438. void setQAbstractScrollAreaProperties(QScriptValue value,
  3439. QScriptEngine *engine);
  3440. @ The implementation of this is simple.
  3441. @<Functions for scripting@>=
  3442. void setQAbstractScrollAreaProperties(QScriptValue value, QScriptEngine *engine)
  3443. {
  3444. setQFrameProperties(value, engine);
  3445. }
  3446. @ This class is used by the |QAbstractItemView| class. This is another class
  3447. that we do not need a script constructor for.
  3448. @<Function prototypes for scripting@>=
  3449. void setQAbstractItemViewProperties(QScriptValue value, QScriptEngine *engine);
  3450. @ This function has another simple implementation.
  3451. @<Functions for scripting@>=
  3452. void setQAbstractItemViewProperties(QScriptValue value, QScriptEngine *engine)
  3453. {
  3454. setQAbstractScrollAreaProperties(value, engine);
  3455. }
  3456. @ The |QGraphicsView| and |QTableView| classes form the base of \pn{} classes.
  3457. @<Function prototypes for scripting@>=
  3458. void setQGraphicsViewProperties(QScriptValue value, QScriptEngine *engine);
  3459. void setQTableViewProperties(QScriptValue value, QScriptEngine *engine);
  3460. @ Again, the implementations are boring.
  3461. @<Functions for scripting@>=
  3462. void setQGraphicsViewProperties(QScriptValue value, QScriptEngine *engine)
  3463. {
  3464. setQAbstractScrollAreaProperties(value, engine);
  3465. }
  3466. void setQTableViewProperties(QScriptValue value, QScriptEngine *engine)
  3467. {
  3468. setQAbstractItemViewProperties(value, engine);
  3469. }
  3470. @* Scripting Button Classes.
  3471. \noindent \pn{} provides an |AnnotationButton| class which is a special kind of
  3472. |QPushButton| which in turn comes from |QAbstractButton|. While
  3473. |AnnotationButton| can be used in exactly the same way as a |QPushButton|, if
  3474. an annotation is not needed, there is little reason not to use the base class.
  3475. @<Function prototypes for scripting@>=
  3476. void setQAbstractButtonProperties(QScriptValue value, QScriptEngine *engine);
  3477. void setQPushButtonProperties(QScriptValue value, QScriptEngine *engine);
  3478. QScriptValue constructQPushButton(QScriptContext *context,
  3479. QScriptEngine *engine);
  3480. @ The constructor for |QPushButton| should be passed to the scripting engine.
  3481. @<Set up the scripting engine@>=
  3482. constructor = engine->newFunction(constructQPushButton);
  3483. value = engine->newQMetaObject(&QPushButton::staticMetaObject, constructor);
  3484. engine->globalObject().setProperty("QPushButton", value);
  3485. @ The implementation should seem familiar.
  3486. @<Functions for scripting@>=
  3487. QScriptValue constructQPushButton(QScriptContext *, QScriptEngine *engine)
  3488. {
  3489. QScriptValue object = engine->newQObject(new QPushButton());
  3490. setQPushButtonProperties(object, engine);
  3491. return object;
  3492. }
  3493. void setQPushButtonProperties(QScriptValue value, QScriptEngine *engine)
  3494. {
  3495. setQAbstractButtonProperties(value, engine);
  3496. }
  3497. void setQAbstractButtonProperties(QScriptValue value, QScriptEngine *engine)
  3498. {
  3499. setQWidgetProperties(value, engine);
  3500. }
  3501. @* Scripting QSqlQuery.
  3502. \noindent With this class exposed to the host environment, it becomes possible
  3503. for script code to execute SQL queries and evaluate the result.
  3504. Rather than use |QSqlQuery| directly, however, we use a proxy \nfnote{Erich
  3505. Gamma, Richard Helm, Raph Johnson, and John
  3506. Vlissides,\par\indent\underbar{Design Patterns: elements of reusable
  3507. object-oriented software} (1995) pp. 207--217} class. This class obtains its own
  3508. database connection and handles properly closing and removing these connections
  3509. when the query object is destroyed.
  3510. @<Class declarations@>=
  3511. class SqlQueryConnection : public QSqlQuery@/
  3512. {
  3513. public:@/
  3514. SqlQueryConnection(const QString &query = QString());
  3515. ~SqlQueryConnection();
  3516. QSqlQuery* operator->() const;
  3517. private:@/
  3518. QString connection;
  3519. QSqlQuery *q;
  3520. };
  3521. @ The constructor can be somewhat simplified from the four forms of |QSqlQuery|.
  3522. We are not interested in creating an object from a |QSqlResult| or from another
  3523. |QSqlQuery|. The database connection is managed by the class itself so the
  3524. constructor only needs an optional string containing a query. This is used to
  3525. initialize a real |QSqlQuery| object.
  3526. @<SqlQueryConnection implementation@>=
  3527. SqlQueryConnection::SqlQueryConnection(const QString &query)
  3528. {
  3529. QSqlDatabase database = AppInstance->database();
  3530. database.open();
  3531. q = new QSqlQuery(query, database);
  3532. connection = database.connectionName();
  3533. }
  3534. @ The destructor handles removing the |QSqlQuery| and the database connection
  3535. associated with it. The extra brackets introduce a new scope for the
  3536. |QSqlDatabase| so that it is out of scope when the connection is removed.
  3537. @<SqlQueryConnection implementation@>=
  3538. SqlQueryConnection::~SqlQueryConnection()
  3539. {
  3540. delete q;
  3541. {
  3542. QSqlDatabase database = QSqlDatabase::database(connection);
  3543. database.close();
  3544. }
  3545. QSqlDatabase::removeDatabase(connection);
  3546. }
  3547. @ For all other functionality, we simply forward the request to our |QSqlQuery|
  3548. object.
  3549. @<SqlQueryConnection implementation@>=
  3550. QSqlQuery* SqlQueryConnection::operator->() const
  3551. {
  3552. return q;
  3553. }
  3554. @ In order to use this new class in the host environment, a number of functions
  3555. are needed.
  3556. @<Function prototypes for scripting@>=
  3557. void setQSqlQueryProperties(QScriptValue value, QScriptEngine *engine);
  3558. QScriptValue constructQSqlQuery(QScriptContext *context, QScriptEngine *engine);
  3559. QScriptValue QSqlQuery_bind(QScriptContext *context, QScriptEngine *engine);
  3560. QScriptValue QSqlQuery_bindDeviceData(QScriptContext *context,
  3561. QScriptEngine *engine);
  3562. QScriptValue QSqlQuery_bindFileData(QScriptContext *context,
  3563. QScriptEngine *engine);
  3564. QScriptValue QSqlQuery_exec(QScriptContext *context,
  3565. QScriptEngine *engine);
  3566. QScriptValue QSqlQuery_executedQuery(QScriptContext *context,
  3567. QScriptEngine *engine);
  3568. QScriptValue QSqlQuery_invalidate(QScriptContext *context, QScriptEngine *engine);
  3569. QScriptValue QSqlQuery_next(QScriptContext *context, QScriptEngine *engine);
  3570. QScriptValue QSqlQuery_prepare(QScriptContext *context, QScriptEngine *engine);
  3571. QScriptValue QSqlQuery_value(QScriptContext *context, QScriptEngine *engine);
  3572. @ For conceptual convenience we simply pretend that we are working with a real
  3573. |QSqlQuery| object.
  3574. @<Set up the scripting engine@>=
  3575. constructor = engine->newFunction(constructQSqlQuery);
  3576. engine->globalObject().setProperty("QSqlQuery", constructor);
  3577. @ With connection creation no longer needed in the constructor, all that is
  3578. needed is object creation and applying the appropriate properties to the script
  3579. value.
  3580. @<Functions for scripting@>=
  3581. QScriptValue constructQSqlQuery(QScriptContext *, QScriptEngine *engine)
  3582. {
  3583. SqlQueryConnection *obj = new SqlQueryConnection();
  3584. QScriptValue object =
  3585. engine->toScriptValue<void *>(obj);
  3586. setQSqlQueryProperties(object, engine);
  3587. return object;
  3588. }
  3589. @ As this class does not derive from |QObject|, we must wrap all of the methods
  3590. we might want to use.
  3591. @<Functions for scripting@>=
  3592. void setQSqlQueryProperties(QScriptValue value, QScriptEngine *engine)
  3593. {
  3594. value.setProperty("bind", engine->newFunction(QSqlQuery_bind));
  3595. value.setProperty("bindFileData",
  3596. engine->newFunction(QSqlQuery_bindFileData));
  3597. value.setProperty("bindDeviceData",
  3598. engine->newFunction(QSqlQuery_bindDeviceData));
  3599. value.setProperty("exec", engine->newFunction(QSqlQuery_exec));
  3600. value.setProperty("executedQuery", engine->newFunction(QSqlQuery_executedQuery));
  3601. value.setProperty("invalidate", engine->newFunction(QSqlQuery_invalidate));
  3602. value.setProperty("next", engine->newFunction(QSqlQuery_next));
  3603. value.setProperty("prepare", engine->newFunction(QSqlQuery_prepare));
  3604. value.setProperty("value", engine->newFunction(QSqlQuery_value));
  3605. }
  3606. @ Most of these properties are wrappers around existing |QSqlQuery| functions.
  3607. @<Functions for scripting@>=
  3608. QScriptValue QSqlQuery_exec(QScriptContext *context, QScriptEngine *engine)
  3609. {
  3610. QSqlQuery *q = getself<SqlQueryConnection *>(context)->operator->();
  3611. QScriptValue retval;
  3612. if(context->argumentCount() == 1)
  3613. {
  3614. retval = QScriptValue(engine,
  3615. q->exec(argument<QString>(0, context)));
  3616. }
  3617. else
  3618. {
  3619. retval = QScriptValue(engine, q->exec());
  3620. }
  3621. if(q->lastError().isValid())
  3622. {
  3623. qDebug() << q->lastQuery();
  3624. qDebug() << q->lastError().text();
  3625. }
  3626. return retval;
  3627. }
  3628. QScriptValue QSqlQuery_executedQuery(QScriptContext *context, QScriptEngine *)
  3629. {
  3630. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3631. return QScriptValue(query->lastQuery());
  3632. }
  3633. QScriptValue QSqlQuery_next(QScriptContext *context, QScriptEngine *engine)
  3634. {
  3635. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3636. return QScriptValue(engine, query->next());
  3637. }
  3638. QScriptValue QSqlQuery_value(QScriptContext *context, QScriptEngine *engine)
  3639. {
  3640. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3641. return QScriptValue(engine,
  3642. query->value(argument<int>(0, context)).toString());
  3643. }
  3644. @ For prepared queries, we support binding variables available to the script,
  3645. data available in a named file, or data from any open |QIODevice|.
  3646. @<Functions for scripting@>=
  3647. QScriptValue QSqlQuery_prepare(QScriptContext *context, QScriptEngine *engine)
  3648. {
  3649. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3650. return QScriptValue(engine, query->prepare(argument<QString>(0, context)));
  3651. }
  3652. QScriptValue QSqlQuery_bind(QScriptContext *context, QScriptEngine *)
  3653. {
  3654. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3655. query->bindValue(argument<QString>(0, context),
  3656. argument<QVariant>(1, context));
  3657. return QScriptValue();
  3658. }
  3659. QScriptValue QSqlQuery_bindFileData(QScriptContext *context,
  3660. QScriptEngine *)
  3661. {
  3662. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3663. QString placeholder = argument<QString>(0, context);
  3664. QString filename = argument<QString>(1, context);
  3665. QFile file(filename);
  3666. QByteArray data;
  3667. if(file.open(QIODevice::ReadOnly))
  3668. {
  3669. data = file.readAll();
  3670. file.close();
  3671. }
  3672. query->bindValue(placeholder, data);
  3673. return QScriptValue();
  3674. }
  3675. QScriptValue QSqlQuery_bindDeviceData(QScriptContext *context,
  3676. QScriptEngine *)
  3677. {
  3678. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3679. QString placeholder = argument<QString>(0, context);
  3680. QIODevice *device = argument<QIODevice *>(1, context);
  3681. device->reset();
  3682. QByteArray data;
  3683. data = device->readAll();
  3684. query->bindValue(placeholder, data);
  3685. return QScriptValue();
  3686. }
  3687. @ To avoid leaking database connections, we add the |invalidate()| property
  3688. which destroys our object. The object on which this method is called must not be
  3689. used after calling this method. In script code this will typically be used as in
  3690. the following example:
  3691. {\tt query = query.invalidate();}
  3692. @<Functions for scripting@>=
  3693. QScriptValue QSqlQuery_invalidate(QScriptContext *context, QScriptEngine *)
  3694. {
  3695. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  3696. delete query;
  3697. return QScriptValue::UndefinedValue;
  3698. }
  3699. @* Other scripting functions.
  3700. \noindent There are a few functions that are exposed to the scripting engine
  3701. that are not associated with any class. Two functions are used for extracting
  3702. information from file names. Another is used to construct array values from SQL
  3703. array values. There is also a function for setting the default font for the
  3704. application or some part of the application.
  3705. @<Function prototypes for scripting@>=
  3706. QScriptValue baseName(QScriptContext *context, QScriptEngine *engine);
  3707. QScriptValue dir(QScriptContext *context, QScriptEngine *engine);
  3708. QScriptValue sqlToArray(QScriptContext *context, QScriptEngine *engine);
  3709. QScriptValue setFont(QScriptContext *context, QScriptEngine *engine);
  3710. QScriptValue annotationFromRecord(QScriptContext *context,
  3711. QScriptEngine *engine);
  3712. QScriptValue setTabOrder(QScriptContext *context, QScriptEngine *engine);
  3713. QScriptValue saveFileFromDatabase(QScriptContext *context, QScriptEngine *engine);
  3714. QScriptValue scriptTr(QScriptContext *context, QScriptEngine *engine);
  3715. @ These functions are passed to the scripting engine.
  3716. @<Set up the scripting engine@>=
  3717. engine->globalObject().setProperty("baseName", engine->newFunction(baseName));
  3718. engine->globalObject().setProperty("dir", engine->newFunction(dir));
  3719. engine->globalObject().setProperty("sqlToArray",
  3720. engine->newFunction(sqlToArray));
  3721. engine->globalObject().setProperty("setFont", engine->newFunction(setFont));
  3722. engine->globalObject().setProperty("annotationFromRecord",
  3723. engine->newFunction(annotationFromRecord));
  3724. engine->globalObject().setProperty("setTabOrder",
  3725. engine->newFunction(setTabOrder));
  3726. engine->globalObject().setProperty("saveFileFromDatabase",
  3727. engine->newFunction(saveFileFromDatabase));
  3728. engine->globalObject().setProperty("TTR", engine->newFunction(scriptTr));
  3729. @ These functions are not part of an object. They expect a string specifying
  3730. the path to a file and return a string with either the name of the file without
  3731. the path and extension or the path of the directory containing the file.
  3732. @<Functions for scripting@>=
  3733. QScriptValue baseName(QScriptContext *context, QScriptEngine *engine)
  3734. {
  3735. QFileInfo info(argument<QString>(0, context));
  3736. QScriptValue retval(engine, info.baseName());
  3737. return retval;
  3738. }
  3739. QScriptValue dir(QScriptContext *context, QScriptEngine *engine)
  3740. {
  3741. QFileInfo info(argument<QString>(0, context));
  3742. QDir dir = info.dir();
  3743. QScriptValue retval(engine, dir.path());
  3744. return retval;
  3745. }
  3746. @ This function takes a file ID and a file name and copies file data stored in
  3747. the database out to the file system.
  3748. @<Functions for scripting@>=
  3749. QScriptValue saveFileFromDatabase(QScriptContext *context, QScriptEngine *)
  3750. {
  3751. SqlQueryConnection h;
  3752. QSqlQuery *query = h.operator->();
  3753. QString q = "SELECT file FROM files WHERE id = :file";
  3754. query->prepare(q);
  3755. query->bindValue(":file", argument<int>(0, context));
  3756. query->exec();
  3757. query->next();
  3758. QByteArray array = query->value(0).toByteArray();
  3759. QFile file(argument<QString>(1, context));
  3760. file.open(QIODevice::WriteOnly);
  3761. file.write(array);
  3762. file.close();
  3763. return QScriptValue();
  3764. }
  3765. @ This function takes a string representing a SQL array and returns an array
  3766. value.
  3767. @<Functions for scripting@>=
  3768. QScriptValue sqlToArray(QScriptContext *context, QScriptEngine *engine)
  3769. {
  3770. QString source = argument<QString>(0, context);
  3771. source.remove(0, 1);
  3772. source.chop(1);
  3773. QStringList elements = source.split(",");
  3774. QString element;
  3775. QScriptValue dest = engine->newArray(elements.size());
  3776. int i = 0;
  3777. foreach(element, elements)
  3778. {
  3779. if(element.startsWith("\"") && element.endsWith("\""))
  3780. {
  3781. element.chop(1);
  3782. element = element.remove(0, 1);
  3783. }
  3784. dest.setProperty(i, QScriptValue(engine, element));
  3785. i++;
  3786. }
  3787. return dest;
  3788. }
  3789. @ This function can be used to set the default font for the application or on
  3790. a per-class hierarchy basis.
  3791. @<Functions for scripting@>=
  3792. QScriptValue setFont(QScriptContext *context, QScriptEngine *)
  3793. {
  3794. QString font = argument<QString>(0, context);
  3795. QString classname;
  3796. if(context->argumentCount() > 1)
  3797. {
  3798. classname = argument<QString>(1, context);
  3799. QApplication::setFont(QFont(font), classname.toLatin1().constData());
  3800. }
  3801. else
  3802. {
  3803. QApplication::setFont(QFont(font));
  3804. }
  3805. return QScriptValue();
  3806. }
  3807. @ This function was briefly used prior to adding support for |QXmlQuery| in the
  3808. host environment. The function is now depreciated and should not be used.
  3809. @<Functions for scripting@>=
  3810. QScriptValue annotationFromRecord(QScriptContext *context, QScriptEngine *)
  3811. {
  3812. SqlQueryConnection h;
  3813. QSqlQuery *query = h.operator->();
  3814. QString q = "SELECT file FROM files WHERE id = :file";
  3815. query->prepare(q);
  3816. query->bindValue(":file", argument<int>(0, context));
  3817. query->exec();
  3818. query->next();
  3819. QByteArray array = query->value(0).toByteArray();
  3820. QBuffer buffer(&array);
  3821. buffer.open(QIODevice::ReadOnly);
  3822. QXmlQuery xquery;
  3823. xquery.bindVariable("profile", &buffer);
  3824. QString xq;
  3825. xq = "for $b in doc($profile) //tuple where exists($b/annotation) return $b";
  3826. xquery.setQuery(xq);
  3827. QString result;
  3828. xquery.evaluateTo(&result);
  3829. return QScriptValue(result);
  3830. }
  3831. @ This function can be used to change the tab order for controls in Typica.
  3832. Changes to the example configuration in \pn{} 1.4 made the default handling
  3833. of tab controls in the logging window unacceptable.
  3834. @<Functions for scripting@>=
  3835. QScriptValue setTabOrder(QScriptContext *context, QScriptEngine *)
  3836. {
  3837. QWidget::setTabOrder(argument<QWidget*>(0, context),
  3838. argument<QWidget*>(1, context));
  3839. return QScriptValue();
  3840. }
  3841. @ This function is used to allow text that must be placed in scripts to be
  3842. translated into other languages.
  3843. @<Functions for scripting@>=
  3844. QScriptValue scriptTr(QScriptContext *context, QScriptEngine *)
  3845. {
  3846. return QScriptValue(QCoreApplication::translate(
  3847. "configuration",
  3848. argument<QString>(1, context).toUtf8().data()));
  3849. }
  3850. @** Application Configuration.
  3851. \noindent While \pn{} is intended as a data logging application, the diversity
  3852. of equipment and supporting technology precludes the option of providing a
  3853. single interface for common tasks. It is important that the application can be
  3854. configured to work with different roasting equipment, databases, and the like.
  3855. To accomplish this, \pn{} utilizes an XML description of the desired application
  3856. configuration and provides an ECMA-262 host environment which allows application
  3857. dataflow to be configured.
  3858. The scripting environment provides access to elements of the XML file and also
  3859. allows access to most of the application classes. A selection of classes
  3860. provided by Qt is also available. See the section on The Scripting Engine for
  3861. more details.
  3862. \danger While the code is the ultimate documentation of what is possible with
  3863. this interface, additional documentation should be provided to document the
  3864. meaning of supported elements and the objects available through the scripting
  3865. engine.\endanger
  3866. The application configuration is loaded when the program is started.
  3867. Starting with version 1.4, we check for a command line option with the path to
  3868. the configuration file and load that instead of prompting for the information
  3869. if possible.
  3870. Starting with version 1.8, if there is not a -c argument, Typica will first
  3871. search a small number of locations relative to the executable.
  3872. @<Load the application configuration@>=
  3873. QStringList arguments = QCoreApplication::arguments();
  3874. int position = arguments.indexOf("-c");
  3875. QString filename = QString();
  3876. if(position != -1)
  3877. {
  3878. if(arguments.size() >= position + 1)
  3879. {
  3880. filename = arguments.at(position + 1);
  3881. }
  3882. } else {
  3883. QDir checkPath(QCoreApplication::applicationDirPath() + "/../config/");
  3884. if(checkPath.exists("config.xml")) {
  3885. filename = checkPath.filePath("config.xml");
  3886. } else {
  3887. checkPath = QDir(QCoreApplication::applicationDirPath() + "/config/");
  3888. if(checkPath.exists("config.xml")) {
  3889. filename = checkPath.filePath("config.xml");
  3890. }
  3891. }
  3892. }
  3893. if(filename.isEmpty())
  3894. {
  3895. filename = QFileDialog::getOpenFileName(NULL, "Open Configuration File",
  3896. settings.value("config", "").toString());
  3897. }
  3898. QDir directory;
  3899. if(!filename.isEmpty())
  3900. {
  3901. QFile file(filename);
  3902. QFileInfo info(filename);
  3903. directory = info.dir();
  3904. QTextCodec::setCodecForTr(QTextCodec::codecForName("utf-8"));
  3905. QTranslator *configtr = new QTranslator;
  3906. if(configtr->load(QString("config.%1").arg(QLocale::system().name()),
  3907. QString("%1/Translations").arg(directory.canonicalPath())))
  3908. {
  3909. QCoreApplication::installTranslator(configtr);
  3910. }
  3911. settings.setValue("config", directory.path());
  3912. if(file.open(QIODevice::ReadOnly))
  3913. {
  3914. app.configuration()->setContent(&file, true);
  3915. }
  3916. } else {
  3917. return 1;
  3918. }
  3919. @<Substitute included fragments@>@;
  3920. @ The {\tt <application>} element can contain an arbitrary number of
  3921. {\tt <include>} elements. These elements should not appear in the DOM. Instead,
  3922. the element should be replaced by the content of the specified document.
  3923. @<Substitute included fragments@>=
  3924. QDomElement root = app.configuration()->documentElement();
  3925. QDomNodeList children = root.childNodes();
  3926. QString replacementDoc;
  3927. QDomDocument includedDoc;
  3928. QDomDocumentFragment fragment;
  3929. for(int i = 0; i < children.size(); i++)
  3930. {
  3931. QDomNode currentNode = children.at(i);
  3932. QDomElement currentElement;
  3933. if(currentNode.nodeName() == "include")
  3934. {
  3935. currentElement = currentNode.toElement();
  3936. if(currentElement.hasAttribute("src"))
  3937. {
  3938. replacementDoc = directory.path();
  3939. replacementDoc.append('/');
  3940. replacementDoc.append(currentElement.attribute("src"));
  3941. QFile doc(replacementDoc);
  3942. if(doc.open(QIODevice::ReadOnly))
  3943. {
  3944. includedDoc.setContent(&doc, true);
  3945. fragment = includedDoc.createDocumentFragment();
  3946. fragment.appendChild(includedDoc.documentElement());
  3947. root.replaceChild(fragment, currentNode);
  3948. doc.close();
  3949. }
  3950. }
  3951. }
  3952. }
  3953. @ Simply loading the configuration document does not display a user interface or
  3954. set up any objects that allow the program to do anything. To do this, a script
  3955. obtained from the configuration document is run. The root element of the
  3956. document should be {\tt <application>}. This element should have a number of
  3957. child elements including {\tt <window>} elements which describe the various
  3958. windows that can be opened in the application and {\tt <program>} elements
  3959. containing script code. These {\tt <program>} elements can occur in a number of
  3960. different contexts including within {\tt <window>} elements which would indicate
  3961. that such scripts should be evaluated when the window being described is
  3962. created. After the configuration document is loaded, all {\tt <program>}
  3963. elements that are direct children of the {\tt <application>} element are
  3964. concatenated and the script is run.
  3965. Before the script is run and user interface elements are drawn, we also check
  3966. for {\tt <style>} elements which can be used to set up a stylesheet for the
  3967. application.
  3968. @<Find and evaluate starting script@>=
  3969. QString styleText;
  3970. QString programText;
  3971. QDomElement currentElement;
  3972. for(int i = 0; i < children.size(); i++)
  3973. {
  3974. QDomNode currentNode = children.at(i);
  3975. if(currentNode.nodeName() == "style")
  3976. {
  3977. currentElement = currentNode.toElement();
  3978. styleText.append(currentElement.text());
  3979. }
  3980. else if(currentNode.nodeName() == "program")
  3981. {
  3982. currentElement = currentNode.toElement();
  3983. programText.append(currentElement.text());
  3984. }
  3985. }
  3986. app.setStyleSheet(styleText);
  3987. QScriptValue result = engine->evaluate(programText);
  3988. @<Report scripting errors@>
  3989. @ When a script is evaluated, there is a chance that there will be some error in
  3990. the execution of that script. If this occurs, we want to report that.
  3991. @<Report scripting errors@>=
  3992. if(engine->hasUncaughtException())
  3993. {
  3994. int line = engine->uncaughtExceptionLineNumber();
  3995. qDebug() << "Uncaught excpetion at line " << line << " : " <<
  3996. result.toString();
  3997. QString trace;
  3998. foreach(trace, engine->uncaughtExceptionBacktrace())
  3999. {
  4000. qDebug() << trace;
  4001. }
  4002. }
  4003. @* Creating a window.
  4004. \noindent When a configuration document is loaded, none of the {\tt <window>}
  4005. elements are interpreted or used to create a graphical user interface. Instead,
  4006. any {\tt <program>} elements that are immediate children of the
  4007. {\tt <application>} element are interpreted. In order to convert a
  4008. {\tt <window>} element into a window displayed on screen, the script in the
  4009. {\tt <program>} elements must call a function to display a specified window.
  4010. Report windows can be produced by scripts in a similar, but slightly different
  4011. manner.
  4012. \danger This design works, but it'@q'@>s not particularly good design. It was written
  4013. under severe time constraints and should be redesigned or at least cleaned up
  4014. and reorganized.\endanger
  4015. @<Function prototypes for scripting@>=
  4016. QScriptValue createWindow(QScriptContext *context, QScriptEngine *engine);
  4017. QScriptValue createReport(QScriptContext *context, QScriptEngine *engine);
  4018. void addLayoutToWidget(QDomElement element, QStack<QWidget*> *widgetStack,
  4019. QStack<QLayout*> *layoutStack);
  4020. void addLayoutToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4021. QStack<QLayout *> *layoutStack);
  4022. void addSplitterToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4023. QStack<QLayout *> *layoutStack);
  4024. void addSplitterToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4025. QStack<QLayout *> *layoutStack);
  4026. void populateGridLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4027. QStack<QLayout *> *layoutStack);
  4028. void populateBoxLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4029. QStack<QLayout *> *layoutStack);
  4030. void populateSplitter(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4031. QStack<QLayout *> *layoutStack);
  4032. void populateWidget(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4033. QStack<QLayout *> *layoutStack);
  4034. void populateStackedLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4035. QStack<QLayout *> *layoutStack);
  4036. void addTemperatureDisplayToSplitter(QDomElement element,@|
  4037. QStack<QWidget *> *widgetStack,
  4038. QStack<QLayout *> *layoutStack);
  4039. void addTemperatureDisplayToLayout(QDomElement element,@|
  4040. QStack<QWidget *> *widgetStack,
  4041. QStack<QLayout *> *layoutStack);
  4042. void addTimerDisplayToSplitter(QDomElement element,@|
  4043. QStack<QWidget *> *widgetStack,
  4044. QStack<QLayout *> *layoutStack);
  4045. void addTimerDisplayToLayout(QDomElement element,@|
  4046. QStack<QWidget *> *widgetStack,
  4047. QStack<QLayout *> *layoutStack);
  4048. void addDecorationToSplitter(QDomElement element,@|
  4049. QStack<QWidget *> *widgetStack,
  4050. QStack<QLayout *> *layoutStack);
  4051. void addDecorationToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4052. QStack<QLayout *> *layoutStack);
  4053. void addWidgetToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4054. QStack<QLayout *> *layoutStack);
  4055. void addButtonToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4056. QStack<QLayout *> *layoutStack);
  4057. void addZoomLogToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4058. QStack<QLayout *> *layoutStack);
  4059. void addGraphToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4060. QStack<QLayout *> *layoutStack);
  4061. void addSqlDropToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4062. QStack<QLayout *> *layoutStack);
  4063. void addSaltToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4064. QStack<QLayout *> *layoutStack);
  4065. void addLineToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4066. QStack<QLayout *> *layoutStack);
  4067. void addTextToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4068. QStack<QLayout *> *layoutStack);
  4069. void addSqlQueryViewToLayout(QDomElement element,
  4070. QStack<QWidget *> *widgetStack,
  4071. QStack<QLayout *> *layoutStack);
  4072. void addCalendarToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4073. QStack<QLayout *> *layoutStack);
  4074. void addSpinBoxToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4075. QStack<QLayout *> *layoutStack);
  4076. void addTimeEditToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4077. QStack<QLayout *> *layoutStack);
  4078. @ The functions for creating windows must be made available to the scripting
  4079. engine.
  4080. @<Set up the scripting engine@>=
  4081. engine->globalObject().setProperty("createWindow",
  4082. engine->newFunction(createWindow));
  4083. engine->globalObject().setProperty("createReport",
  4084. engine->newFunction(createReport));
  4085. @ This function must examine the configuration document in search of the
  4086. appropriate window element, parse the contents of that element, and create a
  4087. multitude of objects, all of which must be passed to the scripting engine.
  4088. @<Functions for scripting@>=
  4089. QScriptValue createWindow(QScriptContext *context, QScriptEngine *engine)@/
  4090. {
  4091. QString targetID = argument<QString>(0, context);
  4092. QDomNode element;
  4093. QScriptValue object;
  4094. @<Find the window element@>@;
  4095. if(!element.isNull())
  4096. {
  4097. @<Display the window@>@;
  4098. }
  4099. return object;
  4100. }
  4101. @ Report files are not part of the configuration document and must be created
  4102. differently. While there is a special menu type that handles all of this
  4103. without involving the host environment, scripted generation and manipulation of
  4104. report windows requires another function. This function will only work after a
  4105. window with a reports menu has been created.
  4106. @<Functions for scripting@>=
  4107. QScriptValue createReport(QScriptContext *context, QScriptEngine *engine)
  4108. {
  4109. QString targetID = argument<QString>(0, context);
  4110. QFile file(QString("reports:%1").arg(targetID));
  4111. QScriptValue object;
  4112. if(file.open(QIODevice::ReadOnly))
  4113. {
  4114. QDomDocument document;
  4115. document.setContent(&file, true);
  4116. QDomElement element = document.documentElement();
  4117. if(!element.isNull())
  4118. {
  4119. @<Display the window@>@;
  4120. }
  4121. file.close();
  4122. }
  4123. return object;
  4124. }
  4125. @ First we must locate the {\tt <window>} element. The most sensible way to do
  4126. this would require that each {\tt <window>} element has an ID attribute and
  4127. search the DOM tree for that ID. Unfortunately, as of this writing,
  4128. |QDomDocument::elementByID()| always returns a null element, so that won'@q'@>t work.
  4129. Instead, we search the tree for all {\tt <window>} elements and then examine
  4130. the resulting list to find the element with the appropriate ID.
  4131. @<Find the window element@>=
  4132. QDomNodeList windows =
  4133. AppInstance->configuration()->documentElement().elementsByTagName("window");
  4134. QDomNode nullNode;
  4135. int i = 0;
  4136. element = nullNode;
  4137. while(i < windows.count())
  4138. {
  4139. element = windows.at(i);
  4140. QDomNamedNodeMap attributes = element.attributes();
  4141. if(attributes.contains("id"))
  4142. {
  4143. if(attributes.namedItem("id").toAttr().value() == targetID)
  4144. {
  4145. break;
  4146. }
  4147. }
  4148. element = nullNode;
  4149. i++;
  4150. }
  4151. @ In order to display a window, we start by creating a new |ScriptQMainWindow|
  4152. and set the central widget of that window to a new |QWidget|. After this, we see
  4153. if the window element has any children and proceed to populate the window.
  4154. When creating child elements, care must be taken that all objects are descended
  4155. from the window. If an object is descended from the window and has an object
  4156. name, it will be possible for script code to recover the created object.
  4157. As of version 1.4, the window itself is given the value of its {\tt id}
  4158. attribute as an object name to facilitate automatic window geometry management.
  4159. @<Display the window@>=
  4160. ScriptQMainWindow *window = new ScriptQMainWindow;
  4161. window->setObjectName(targetID);
  4162. object = engine->newQObject(window);
  4163. setQMainWindowProperties(object, engine);
  4164. QWidget *central = new(QWidget);
  4165. central->setParent(window);
  4166. central->setObjectName("centralWidget");
  4167. window->setCentralWidget(central);
  4168. if(element.hasChildNodes())
  4169. {
  4170. @<Process window children@>@;
  4171. }
  4172. @<Insert help menu@>@;
  4173. window->show();
  4174. window->setupFinished();
  4175. @ Three element types make sense as top level children of a {\tt <window>}
  4176. element. An element representing a layout element can be used to apply that
  4177. layout to the central widget. An element representing a menu can be used to add
  4178. a menu to the window. A {\tt <program>} element can be used to specify a script
  4179. to be run after the window has been assembled.
  4180. \danger As the window comes with a blank central widget, elements representing
  4181. a widget to be used as the central widget of the window cannot be used directly
  4182. here. If only one widget is needed in the window, there is a need to create a
  4183. layout element and place that widget in the layout. Also note that there is not
  4184. enough error checking in the following code. Provide invalid input at your
  4185. peril.\endanger
  4186. Program fragments pulled from the window description are executed with the
  4187. newly created window available as {\tt this}. When such a fragment is run, the
  4188. entire description of the window will have already been evaluated and any
  4189. necessary objects created. Obtaining a child object of the window can be done
  4190. by calling |findChildObject()|.
  4191. @<Process window children@>=
  4192. QStack<QWidget*> widgetStack;
  4193. QStack<QLayout*> layoutStack;
  4194. QString windowScript;
  4195. widgetStack.push(central);
  4196. QDomNodeList windowChildren = element.childNodes();
  4197. int i = 0;
  4198. while(i < windowChildren.count())
  4199. {
  4200. QDomNode current;
  4201. QDomElement element;
  4202. current = windowChildren.at(i);
  4203. if(current.isElement())
  4204. {
  4205. element = current.toElement();
  4206. if(element.tagName() == "program")
  4207. {
  4208. windowScript.append(element.text());
  4209. }
  4210. else if(element.tagName() == "layout")
  4211. {
  4212. element.setAttribute("trcontext", "configuration");
  4213. addLayoutToWidget(element, &widgetStack, &layoutStack);
  4214. }
  4215. else if(element.tagName() == "menu")
  4216. {
  4217. @<Process menus@>@;
  4218. }
  4219. }
  4220. i++;
  4221. }
  4222. QScriptValue oldThis = context->thisObject();
  4223. context->setThisObject(object);
  4224. QScriptValue result = engine->evaluate(windowScript);
  4225. @<Report scripting errors@>@;
  4226. context->setThisObject(oldThis);
  4227. @ Elements representing menus may provide a number of child elements
  4228. representing the items in that menu. The XML portion of the configuration will
  4229. not provide any information on what these menu items do. The contents of the
  4230. {\tt <program>} element for the window will need to request the |QAction|
  4231. objects and connect a signal from that object to the desired functionality.
  4232. One special consideration is the Reports menu. This menu will populate itself
  4233. according to its own logic and will have a {\tt type} property of
  4234. {\tt "reports"} and a {\tt src} property indicating the directory where reports
  4235. can be found.
  4236. @<Process menus@>=
  4237. QMenuBar *bar = window->menuBar();
  4238. bar->setParent(window);
  4239. bar->setObjectName("menuBar");
  4240. if(element.hasAttribute("name"))
  4241. {
  4242. QMenu *menu = bar->addMenu(QCoreApplication::translate("configuration",
  4243. element.attribute("name").toUtf8().data()));
  4244. menu->setParent(bar);
  4245. if(element.hasAttribute("type"))
  4246. {
  4247. if(element.attribute("type") == "reports")
  4248. {
  4249. if(element.hasAttribute("src"))
  4250. {
  4251. @<Populate reports menu@>@;
  4252. }
  4253. }
  4254. }
  4255. if(element.hasChildNodes())
  4256. {
  4257. @<Process menu items@>@;
  4258. }
  4259. }
  4260. @ To add items to a menu, we check for {\tt <item>} elements under the
  4261. {\tt <menu>} element and create a |QAction| for each item.
  4262. @<Process menu items@>=
  4263. QDomNodeList menuItems = element.childNodes();
  4264. int j = 0;
  4265. while(j < menuItems.count())
  4266. {
  4267. QDomNode item = menuItems.at(j);
  4268. if(item.isElement())
  4269. {
  4270. QDomElement itemElement = item.toElement();
  4271. if(itemElement.tagName() == "item")
  4272. {
  4273. QAction *itemAction = new QAction(QCoreApplication::translate("configuration",
  4274. itemElement.text().toUtf8().data()), menu);
  4275. if(itemElement.hasAttribute("id"))
  4276. {
  4277. itemAction->setObjectName(itemElement.attribute("id"));
  4278. }
  4279. if(itemElement.hasAttribute("shortcut"))
  4280. {
  4281. itemAction->setShortcut(itemElement.attribute("shortcut"));
  4282. }
  4283. menu->addAction(itemAction);
  4284. }
  4285. else if(itemElement.tagName() == "separator")
  4286. {
  4287. menu->addSeparator();
  4288. }
  4289. else if(itemElement.tagName() == "plugins")
  4290. {
  4291. @<Process plugin item@>@;
  4292. }
  4293. }
  4294. j++;
  4295. }
  4296. @i helpmenu.w
  4297. @i licensewindow.w
  4298. @ A layout can contain a number of different elements including a variety of
  4299. widget types and other layouts. This function is responsible for applying any
  4300. layout class to the widget currently being populated and processing children of
  4301. the {\tt <layout>} element to populate that layout. External stacks are used to
  4302. keep track of which widgets and layouts are currently being populated. The
  4303. {\tt type} attribute is used to determine what sort of layout should be created.
  4304. Currently, {\tt horizontal}, {\tt vertical}, {\tt grid}, and {\tt stack} types
  4305. are supported. The first two resolve to |QBoxLayout| layouts, {\tt grid}
  4306. resolves to a |QGridLayout|, and {\tt stack} resolves to a |QStackedLayout|.
  4307. @<Functions for scripting@>=
  4308. void addLayoutToWidget(QDomElement element, QStack<QWidget*> *widgetStack,
  4309. QStack<QLayout*> *layoutStack)
  4310. {
  4311. if(element.hasAttribute("type"))
  4312. {
  4313. @<Create and populate layout@>@;
  4314. QWidget *widget = widgetStack->top();
  4315. if(layout)
  4316. {
  4317. widget->setLayout(layout);
  4318. }
  4319. layoutStack->pop();
  4320. }
  4321. }
  4322. @ As there are multiple places where a {\tt <layout>} element is parsed with
  4323. slightly different semantics, the code for creating and populating the layout is
  4324. broken out so that code written to support additional layout types only needs to
  4325. be written once.
  4326. @<Create and populate layout@>=
  4327. QLayout *layout;
  4328. QString layoutType = element.attribute("type");
  4329. if(layoutType == "horizontal")
  4330. {
  4331. layout = new QHBoxLayout;
  4332. layoutStack->push(layout);
  4333. populateBoxLayout(element, widgetStack, layoutStack);
  4334. }
  4335. else if(layoutType == "vertical")
  4336. {
  4337. layout = new QVBoxLayout;
  4338. layoutStack->push(layout);
  4339. populateBoxLayout(element, widgetStack, layoutStack);
  4340. }
  4341. else if(layoutType == "grid")
  4342. {
  4343. layout = new QGridLayout;
  4344. layoutStack->push(layout);
  4345. populateGridLayout(element, widgetStack, layoutStack);
  4346. }
  4347. else if(layoutType == "stack")
  4348. {
  4349. layout = new QStackedLayout;
  4350. layoutStack->push(layout);
  4351. populateStackedLayout(element, widgetStack, layoutStack);
  4352. }
  4353. if(element.hasAttribute("id"))
  4354. {
  4355. layout->setObjectName(element.attribute("id"));
  4356. }
  4357. if(element.hasAttribute("spacing"))
  4358. {
  4359. layout->setSpacing(element.attribute("spacing").toInt());
  4360. }
  4361. if(element.hasAttribute("margin"))
  4362. {
  4363. int m = element.attribute("margin").toInt();
  4364. layout->setContentsMargins(m, m, m, m);
  4365. }
  4366. @ Stacked layouts are a bit different from the other types. A stacked layout has
  4367. an arbitrary number of {\tt <page>} children which are just a |QWidget| which
  4368. can have the same child elements as {\tt <widget>} elements elsewhere. Only the
  4369. first page will be visible initially, however it is possible to use script code
  4370. to set the currently visible page provided that an ID is set for the layout.
  4371. @<Functions for scripting@>=
  4372. void populateStackedLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4373. QStack<QLayout *> *layoutStack)
  4374. {
  4375. QDomNodeList children = element.childNodes();
  4376. QStackedLayout *layout = qobject_cast<QStackedLayout *>(layoutStack->top());
  4377. for(int i = 0; i < children.count(); i++)
  4378. {
  4379. QDomNode current;
  4380. QDomElement currentElement;
  4381. current = children.at(i);
  4382. if(current.isElement())
  4383. {
  4384. currentElement = current.toElement();
  4385. if(currentElement.tagName() == "page")
  4386. {
  4387. QWidget *widget = new QWidget;
  4388. layout->addWidget(widget);
  4389. widgetStack->push(widget);
  4390. currentElement.setAttribute("trcontext", "configuration");
  4391. populateWidget(currentElement, widgetStack, layoutStack);
  4392. widgetStack->pop();
  4393. }
  4394. }
  4395. }
  4396. }
  4397. @ A common use of stacked layouts is in the creation of tabbed interfaces, but
  4398. there are also many uses in \pn{} where the tabs are not required. Therefore,
  4399. tab bar creation requires a separate XML element.
  4400. @<Additional box layout elements@>=
  4401. else if(currentElement.tagName() == "tabbar")
  4402. {
  4403. addTabBarToLayout(currentElement, widgetStack, layoutStack);
  4404. }
  4405. @ The function used to create this follows the usual pattern.
  4406. @<Functions for scripting@>=
  4407. void addTabBarToLayout(QDomElement element, QStack<QWidget*> *, QStack<QLayout*> *layoutStack)
  4408. {
  4409. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4410. QTabBar *widget = new QTabBar;
  4411. layout->addWidget(widget);
  4412. if(!element.attribute("id").isEmpty())
  4413. {
  4414. widget->setObjectName(element.attribute("id"));
  4415. }
  4416. }
  4417. @ Rather than define the tab set in XML, this is left to the host environment.
  4418. This means that some additional scripting support is required.
  4419. @<Set up the scripting engine@>=
  4420. constructor = engine->newFunction(constructQTabBar);
  4421. value = engine->newQMetaObject(&QTabBar::staticMetaObject, constructor);
  4422. engine->globalObject().setProperty("QTabBar", value);
  4423. @ The constructor is trivial.
  4424. @<Functions for scripting@>=
  4425. QScriptValue constructQTabBar(QScriptContext *, QScriptEngine *engine)
  4426. {
  4427. QScriptValue object = engine->newQObject(new QTabBar);
  4428. setQTabBarProperties(object, engine);
  4429. return object;
  4430. }
  4431. @ There are many functions that I might want to some day add support for, but
  4432. the immediate need is just creating the tabs in the first place.
  4433. @<Functions for scripting@>=
  4434. void setQTabBarProperties(QScriptValue value, QScriptEngine *engine)
  4435. {
  4436. setQWidgetProperties(value, engine);
  4437. value.setProperty("addTab", engine->newFunction(QTabBar_addTab));
  4438. }
  4439. QScriptValue QTabBar_addTab(QScriptContext *context, QScriptEngine *)
  4440. {
  4441. QTabBar *self = getself<QTabBar *>(context);
  4442. if(context->argumentCount() > 0)
  4443. {
  4444. self->addTab(argument<QString>(0, context));
  4445. }
  4446. else
  4447. {
  4448. context->throwError("Incorrect number of arguments passed to "@|
  4449. "QTabBar::addTab().");
  4450. }
  4451. return QScriptValue();
  4452. }
  4453. @ Function prototypes are needed.
  4454. @<Function prototypes for scripting@>=
  4455. QScriptValue constructQTabBar(QScriptContext *context, QScriptEngine *engine);
  4456. void setQTabBarProperties(QScriptValue value, QScriptEngine *engine);
  4457. QScriptValue QTabBar_addTab(QScriptContext *context, QScriptEngine *engine);
  4458. @ Using a grid layout is a bit different from using a box layout. Child elements
  4459. with various attributes are required to take full advantage of this layout type.
  4460. All direct children of a grid layout element should be {\tt <row>} elements
  4461. which may have optional {\tt height} and {\tt stretch} attributes which apply to
  4462. that row.
  4463. @<Functions for scripting@>=
  4464. void populateGridLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4465. QStack<QLayout *> *layoutStack)
  4466. {
  4467. QDomNodeList children = element.childNodes();
  4468. int row = -1;
  4469. QGridLayout *layout = qobject_cast<QGridLayout *>(layoutStack->top());
  4470. for(int i = 0; i < children.count(); i++)
  4471. {
  4472. QDomNode current;
  4473. QDomElement currentElement;
  4474. current = children.at(i);
  4475. if(current.isElement())
  4476. {
  4477. currentElement = current.toElement();
  4478. if(currentElement.tagName() == "row")
  4479. {
  4480. row++;
  4481. if(currentElement.hasAttribute("height"))
  4482. {
  4483. layout->setRowMinimumHeight(row,
  4484. currentElement.attribute("height").toInt());
  4485. }
  4486. if(currentElement.hasAttribute("stretch"))
  4487. {
  4488. layout->setRowStretch(row,
  4489. currentElement.attribute("stretch").toInt());
  4490. }
  4491. @<Populate grid layout row@>@;
  4492. }
  4493. }
  4494. }
  4495. }
  4496. @ Each {\tt <row>} may have arbitrarily many {\tt <column>} children. A row with
  4497. nothing in it or that is entirely populated by spanning cells from previous rows
  4498. might have no children.
  4499. The {\tt <column>} element supports several optional attributes. The
  4500. {\tt column} attribute can be used to specify which column the element refers
  4501. to. Sibling {\tt <column>} elements will refer to columns farther right unless
  4502. a lower column number is specified. This does mean that it is possible to
  4503. specify the same column more than once, however actually doing so is not
  4504. recommended. The {\tt width} attribute specifies the minimum width of the
  4505. column. If multiple cells in a column specify this attribute, the last one takes
  4506. priority. Similarly, the {\tt stretch} attribute specifies the column stretch.
  4507. The {\tt rowspan} and {\tt colspan} attributes can be used for cells that span
  4508. more than one row or column. A value of |-1| can be used to have the cell span
  4509. to the last row or column in the layout.
  4510. Once the attributes of the cell are known, a |QHBoxLayout| is added to the
  4511. layout at the appropriate location in the grid and it is this layout which is
  4512. further populated by child elements. Anything that can be placed under a
  4513. {\tt <layout>} element with {\tt "horizontal"} or {\tt "vertical"} {\tt type}
  4514. attribute can be a child of a {\tt <column>} element in this context.
  4515. @<Populate grid layout row@>=
  4516. int column = -1;
  4517. QDomNodeList rowChildren = currentElement.childNodes();
  4518. for(int j = 0; j < rowChildren.count(); j++)
  4519. {
  4520. QDomNode columnNode;
  4521. QDomElement columnElement;
  4522. columnNode = rowChildren.at(j);
  4523. if(columnNode.isElement())
  4524. {
  4525. columnElement = columnNode.toElement();
  4526. if(columnElement.tagName() == "column")
  4527. {
  4528. column++;
  4529. if(columnElement.hasAttribute("column"))
  4530. {
  4531. column = columnElement.attribute("column").toInt();
  4532. }
  4533. if(columnElement.hasAttribute("width"))
  4534. {
  4535. layout->setColumnMinimumWidth(column,
  4536. columnElement.attribute("width").toInt());
  4537. }
  4538. if(columnElement.hasAttribute("stretch"))
  4539. {
  4540. layout->setColumnStretch(column,
  4541. columnElement.attribute("stretch").toInt());
  4542. }
  4543. int hspan = 1;
  4544. int vspan = 1;
  4545. if(columnElement.hasAttribute("rowspan"))
  4546. {
  4547. vspan = columnElement.attribute("rowspan").toInt();
  4548. }
  4549. if(columnElement.hasAttribute("colspan"))
  4550. {
  4551. hspan = columnElement.attribute("colspan").toInt();
  4552. }
  4553. QHBoxLayout *cell = new QHBoxLayout;
  4554. layout->addLayout(cell, row, column, vspan, hspan);
  4555. layoutStack->push(cell);
  4556. columnElement.setAttribute("trcontext", "configuration");
  4557. populateBoxLayout(columnElement, widgetStack, layoutStack);
  4558. layoutStack->pop();
  4559. }
  4560. }
  4561. }
  4562. @ Box layouts are populated by checking for child elements representing
  4563. supported widget types and layouts and adding these to the current layout.
  4564. @<Functions for scripting@>=
  4565. void populateBoxLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4566. QStack<QLayout *> *layoutStack)
  4567. {
  4568. QDomNodeList children = element.childNodes();
  4569. for(int i = 0; i < children.count(); i++)
  4570. {
  4571. QDomNode current;
  4572. QDomElement currentElement;
  4573. current = children.at(i);
  4574. if(current.isElement())
  4575. {
  4576. currentElement = current.toElement();
  4577. currentElement.setAttribute("trcontext", "configuration");
  4578. if(currentElement.tagName() == "button")
  4579. {
  4580. addButtonToLayout(currentElement, widgetStack, layoutStack);
  4581. }
  4582. else if(currentElement.tagName() == "calendar")
  4583. {
  4584. addCalendarToLayout(currentElement, widgetStack, layoutStack);
  4585. }
  4586. else if(currentElement.tagName() == "timeedit")
  4587. {
  4588. addTimeEditToLayout(currentElement, widgetStack, layoutStack);
  4589. }
  4590. else if(currentElement.tagName() == "decoration")
  4591. {
  4592. addDecorationToLayout(currentElement, widgetStack,
  4593. layoutStack);
  4594. }
  4595. else if(currentElement.tagName() == "layout")
  4596. {
  4597. addLayoutToLayout(currentElement, widgetStack, layoutStack);
  4598. }
  4599. else if(currentElement.tagName() == "splitter")
  4600. {
  4601. addSplitterToLayout(currentElement, widgetStack, layoutStack);
  4602. }
  4603. else if(currentElement.tagName() == "label")
  4604. {
  4605. QBoxLayout *layout =
  4606. qobject_cast<QBoxLayout *>(layoutStack->top());
  4607. QLabel *label = new QLabel(QCoreApplication::translate(
  4608. "configuration",
  4609. currentElement.text().toUtf8().data()));
  4610. if(currentElement.hasAttribute("id"))
  4611. {
  4612. label->setObjectName(currentElement.attribute("id"));
  4613. }
  4614. layout->addWidget(label);
  4615. }
  4616. else if(currentElement.tagName() == "lcdtemperature")
  4617. {
  4618. addTemperatureDisplayToLayout(currentElement, widgetStack,
  4619. layoutStack);
  4620. }
  4621. else if(currentElement.tagName() == "lcdtimer")
  4622. {
  4623. addTimerDisplayToLayout(currentElement, widgetStack,
  4624. layoutStack);
  4625. }
  4626. else if(currentElement.tagName() == "line")
  4627. {
  4628. addLineToLayout(currentElement, widgetStack, layoutStack);
  4629. }
  4630. else if(currentElement.tagName() == "report")
  4631. {
  4632. addReportToLayout(currentElement, widgetStack, layoutStack);
  4633. }
  4634. else if(currentElement.tagName() == "sqldrop")
  4635. {
  4636. addSqlDropToLayout(currentElement, widgetStack, layoutStack);
  4637. }
  4638. else if(currentElement.tagName() == "sqltablearray")
  4639. {
  4640. addSaltToLayout(currentElement, widgetStack, layoutStack);
  4641. }
  4642. else if(currentElement.tagName() == "sqlview")
  4643. {
  4644. addSqlQueryViewToLayout(currentElement, widgetStack,
  4645. layoutStack);
  4646. }
  4647. else if(currentElement.tagName() == "textarea")
  4648. {
  4649. addTextToLayout(currentElement, widgetStack, layoutStack);
  4650. }
  4651. else if(currentElement.tagName() == "spinbox")
  4652. {
  4653. addSpinBoxToLayout(currentElement, widgetStack, layoutStack);
  4654. }
  4655. else if(currentElement.tagName() == "formarray")
  4656. {
  4657. addFormArrayToLayout(currentElement, widgetStack, layoutStack);
  4658. }
  4659. else if(currentElement.tagName() =="hscale")
  4660. {
  4661. addScaleControlToLayout(currentElement, widgetStack,
  4662. layoutStack);
  4663. }
  4664. else if(currentElement.tagName() == "vscale")
  4665. {
  4666. addIntensityControlToLayout(currentElement, widgetStack,
  4667. layoutStack);
  4668. }
  4669. else if(currentElement.tagName() == "webview")
  4670. {
  4671. addWebViewToLayout(currentElement, widgetStack, layoutStack);
  4672. }
  4673. else if(currentElement.tagName() == "stretch")
  4674. {
  4675. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4676. layout->addStretch();
  4677. }
  4678. @<Additional box layout elements@>@;
  4679. }
  4680. }
  4681. }
  4682. @ Box layouts support adding additional layouts to the layout. The form of the
  4683. function is very similar to |addLayoutToWidget()|.
  4684. @<Functions for scripting@>=
  4685. void addLayoutToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4686. QStack<QLayout *> *layoutStack)
  4687. {
  4688. QLayout *targetLayout = layoutStack->pop();
  4689. QBoxLayout *boxLayout = qobject_cast<QBoxLayout *>(targetLayout);
  4690. if(element.hasAttribute("type"))
  4691. {
  4692. @<Create and populate layout@>@;
  4693. boxLayout->addLayout(layout);
  4694. layoutStack->pop();
  4695. }
  4696. layoutStack->push(targetLayout);
  4697. }
  4698. @ A splitter is similar to a layout in that it manages the size and position of
  4699. one or more widgets, however it is not a layout and therefore needs to be
  4700. handled separately.
  4701. @<Functions for scripting@>=
  4702. void addSplitterToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4703. QStack<QLayout *> *layoutStack)
  4704. {
  4705. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4706. QSplitter *splitter = new(QSplitter);
  4707. layout->addWidget(splitter);
  4708. @<Set up splitter@>@;
  4709. }
  4710. @ As there are multiple places where a splitter element must be examined, the
  4711. common code is set aside.
  4712. @<Set up splitter@>=
  4713. QString orientation = element.attribute("type");
  4714. if(orientation == "horizontal")
  4715. {
  4716. splitter->setOrientation(Qt::Horizontal);
  4717. }
  4718. else if(orientation == "vertical")
  4719. {
  4720. splitter->setOrientation(Qt::Vertical);
  4721. }
  4722. QString id = element.attribute("id");
  4723. if(!id.isEmpty())
  4724. {
  4725. splitter->setObjectName(id);
  4726. }
  4727. if(element.hasChildNodes())
  4728. {
  4729. widgetStack->push(splitter);
  4730. populateSplitter(element, widgetStack, layoutStack);
  4731. widgetStack->pop();
  4732. }
  4733. @ When populating a splitter, it is important to note that only widgets can be
  4734. added. If a layout is needed, this can be handled by adding a |QWidget| and
  4735. applying the layout to that widget.
  4736. @<Functions for scripting@>=
  4737. void populateSplitter(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4738. QStack<QLayout *> *layoutStack)
  4739. {
  4740. QDomNodeList children = element.childNodes();
  4741. for(int i = 0; i < children.count(); i++)
  4742. {
  4743. QDomNode current;
  4744. QDomElement currentElement;
  4745. current = children.at(i);
  4746. if(current.isElement())
  4747. {
  4748. currentElement = current.toElement();
  4749. currentElement.setAttribute("trcontext", "configuration");
  4750. if(currentElement.tagName() == "decoration")
  4751. {
  4752. addDecorationToSplitter(currentElement, widgetStack,
  4753. layoutStack);
  4754. }
  4755. else if(currentElement.tagName() == "graph")
  4756. {
  4757. addGraphToSplitter(currentElement, widgetStack, layoutStack);
  4758. }
  4759. else if(currentElement.tagName() == "splitter")
  4760. {
  4761. addSplitterToSplitter(currentElement, widgetStack, layoutStack);
  4762. }
  4763. else if(currentElement.tagName() == "lcdtemperature")
  4764. {
  4765. addTemperatureDisplayToSplitter(currentElement, widgetStack,
  4766. layoutStack);
  4767. }
  4768. else if(currentElement.tagName() == "lcdtimer")
  4769. {
  4770. addTimerDisplayToSplitter(currentElement, widgetStack,
  4771. layoutStack);
  4772. }
  4773. else if(currentElement.tagName() == "measurementtable")
  4774. {
  4775. addZoomLogToSplitter(currentElement, widgetStack, layoutStack);
  4776. }
  4777. else if(currentElement.tagName() == "widget")
  4778. {
  4779. addWidgetToSplitter(currentElement, widgetStack, layoutStack);
  4780. }
  4781. }
  4782. }
  4783. }
  4784. @ Adding a splitter to a splitter is similar to adding it to a layout.
  4785. @<Functions for scripting@>=
  4786. void addSplitterToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4787. QStack<QLayout *> *layoutStack)
  4788. {
  4789. QSplitter *parent = qobject_cast<QSplitter *>(widgetStack->top());
  4790. QSplitter *splitter = new(QSplitter);
  4791. splitter->setParent(parent);
  4792. parent->addWidget(splitter);
  4793. @<Set up splitter@>@;
  4794. }
  4795. @ Temperature displays are useful to have in an application such as this. At
  4796. present, this code only supports the {\tt id} attribute. It may be useful in the
  4797. future to allow other attributes for changing default attributes of the
  4798. indicator rather than needing to pull the object from script code and set
  4799. changes there.
  4800. @<Functions for scripting@>=
  4801. void addTemperatureDisplayToSplitter(QDomElement element,@|
  4802. QStack<QWidget *> *widgetStack,
  4803. QStack<QLayout *> *)
  4804. {
  4805. TemperatureDisplay *display = new(TemperatureDisplay);
  4806. if(element.hasAttribute("id"))
  4807. {
  4808. display->setObjectName(element.attribute("id"));
  4809. }
  4810. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4811. splitter->addWidget(display);
  4812. }
  4813. void addTemperatureDisplayToLayout(QDomElement element,@|
  4814. QStack<QWidget *> *,
  4815. QStack<QLayout *> *layoutStack)
  4816. {
  4817. TemperatureDisplay *display = new(TemperatureDisplay);
  4818. if(element.hasAttribute("id"))
  4819. {
  4820. display->setObjectName(element.attribute("id"));
  4821. }
  4822. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4823. layout->addWidget(display);
  4824. }
  4825. @ Timer displays are similarly useful to have. The default format for a timer
  4826. display is {\tt hh:mm:ss}, but this can be changed through the {\tt format}
  4827. attribute of an {\tt <lcdtimer>} element.
  4828. @<Functions for scripting@>=
  4829. void addTimerDisplayToSplitter(QDomElement element,@|
  4830. QStack<QWidget *> *widgetStack,
  4831. QStack<QLayout *> *)
  4832. {
  4833. TimerDisplay *display = new(TimerDisplay);
  4834. if(element.hasAttribute("id"))
  4835. {
  4836. display->setObjectName(element.attribute("id"));
  4837. }
  4838. if(element.hasAttribute("format"))
  4839. {
  4840. display->setDisplayFormat(element.attribute("format"));
  4841. }
  4842. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4843. splitter->addWidget(display);
  4844. }
  4845. void addTimerDisplayToLayout(QDomElement element,@|
  4846. QStack<QWidget *> *,
  4847. QStack<QLayout *> *layoutStack)
  4848. {
  4849. TimerDisplay *display = new(TimerDisplay);
  4850. if(element.hasAttribute("id"))
  4851. {
  4852. display->setObjectName(element.attribute("id"));
  4853. }
  4854. if(element.hasAttribute("format"))
  4855. {
  4856. display->setDisplayFormat(element.attribute("format"));
  4857. }
  4858. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4859. layout->addWidget(display);
  4860. }
  4861. @ When multiple timer or temperature displays are required, it can be useful to
  4862. provide a label to indicate just what is being measured.
  4863. @<Functions for scripting@>=
  4864. void addDecorationToLayout(QDomElement element, QStack<QWidget *> *,@|
  4865. QStack<QLayout *> *layoutStack)
  4866. {
  4867. @<Set up decoration@>@;
  4868. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4869. layout->addWidget(decoration);
  4870. }
  4871. void addDecorationToSplitter(QDomElement element,
  4872. QStack<QWidget *> *widgetStack,
  4873. QStack<QLayout *> *)
  4874. {
  4875. @<Set up decoration@>@;
  4876. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4877. splitter->addWidget(decoration);
  4878. }
  4879. @ The decoration needs a label text, an orientation, and the widget to be
  4880. labeled.
  4881. @<Set up decoration@>=
  4882. QString labelText =
  4883. QCoreApplication::translate("configuration",
  4884. element.attribute("name").toUtf8().data());
  4885. Qt::Orientations@, orientation = Qt::Horizontal;
  4886. if(element.hasAttribute("type"))
  4887. {
  4888. if(element.attribute("type") == "horizontal")
  4889. {
  4890. orientation = Qt::Horizontal;
  4891. }
  4892. else if(element.attribute("type") == "vertical")
  4893. {
  4894. orientation = Qt::Vertical;
  4895. }
  4896. }
  4897. @<Find widget to decorate@>@;
  4898. WidgetDecorator *decoration = new WidgetDecorator(theWidget, labelText,
  4899. orientation);
  4900. if(element.hasAttribute("id"))
  4901. {
  4902. decoration->setObjectName(element.attribute("id"));
  4903. }
  4904. @ The widget to decorate should be found as a child of the {\tt <decoration>}
  4905. element.
  4906. @<Find widget to decorate@>=
  4907. QWidget *theWidget = NULL;
  4908. QDomNodeList children = element.childNodes();
  4909. for(int i = 0; i < children.count(); i++)
  4910. {
  4911. QDomNode item = children.at(i);
  4912. if(item.isElement())
  4913. {
  4914. QDomElement itemElement = item.toElement();
  4915. if(itemElement.tagName() == "lcdtemperature")
  4916. {
  4917. TemperatureDisplay *display = new TemperatureDisplay;
  4918. if(itemElement.hasAttribute("id"))
  4919. {
  4920. display->setObjectName(itemElement.attribute("id"));
  4921. }
  4922. theWidget = display;
  4923. }
  4924. else if(itemElement.tagName() == "lcdtimer")
  4925. {
  4926. TimerDisplay *display = new TimerDisplay;
  4927. if(itemElement.hasAttribute("id"))
  4928. {
  4929. display->setObjectName(itemElement.attribute("id"));
  4930. }
  4931. if(itemElement.hasAttribute("format"))
  4932. {
  4933. display->setDisplayFormat(itemElement.attribute("format"));
  4934. }
  4935. theWidget = display;
  4936. }
  4937. }
  4938. }
  4939. @ As splitters cannot contain layouts directly, there is a need to allow
  4940. otherwise empty widgets to be included in a splitter for cases where a splitter
  4941. should manage several widgets together as a group. A row of annotation buttons
  4942. is an example of such a layout.
  4943. When splitters are used as a way to hide optional features it sometimes has the
  4944. effect of forcing a window to stay larger than should be required. To fix this,
  4945. it is possible to set the \tt{ignoreSizePolicy} attribute to true. While this
  4946. does solve the window size issue, this technique is inconsistent with generally
  4947. expected behavior and its use should generally be discouraged.
  4948. @<Functions for scripting@>=
  4949. void addWidgetToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4950. QStack<QLayout *> *layoutStack)
  4951. {
  4952. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4953. QWidget *widget = new QWidget;
  4954. if(element.hasAttribute("id"))
  4955. {
  4956. widget->setObjectName(element.attribute("id"));
  4957. }
  4958. if(element.hasAttribute("ignoreSizePolicy"))
  4959. {
  4960. if(element.attribute("ignoreSizePolicy") == "true")
  4961. {
  4962. widget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
  4963. }
  4964. }
  4965. splitter->addWidget(widget);
  4966. if(element.hasChildNodes())
  4967. {
  4968. widgetStack->push(widget);
  4969. populateWidget(element, widgetStack, layoutStack);
  4970. widgetStack->pop();
  4971. }
  4972. }
  4973. void populateWidget(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4974. QStack<QLayout *> *layoutStack)
  4975. {
  4976. QDomNodeList children = element.childNodes();
  4977. for(int i = 0; i < children.count(); i++)
  4978. {
  4979. QDomNode current;
  4980. QDomElement currentElement;
  4981. current = children.at(i);
  4982. if(current.isElement())
  4983. {
  4984. currentElement = current.toElement();
  4985. if(currentElement.tagName() == "layout")
  4986. {
  4987. currentElement.setAttribute("trcontext", "configuration");
  4988. addLayoutToWidget(currentElement, widgetStack, layoutStack);
  4989. }
  4990. }
  4991. }
  4992. }
  4993. @ There are two types of buttons that can be added to a layout. There are normal
  4994. push buttons and there are annotation buttons. Other button types may be added
  4995. in the future.
  4996. @<Functions for scripting@>=
  4997. void addButtonToLayout(QDomElement element, QStack<QWidget *> *,@|
  4998. QStack<QLayout *> *layoutStack)
  4999. {
  5000. QAbstractButton *button = NULL;
  5001. QString text =
  5002. QCoreApplication::translate("configuration",
  5003. element.attribute("name").toUtf8().data());
  5004. if(element.hasAttribute("type"))
  5005. {
  5006. QString type = element.attribute("type");
  5007. if(type == "annotation")
  5008. {
  5009. AnnotationButton *abutton = new AnnotationButton(text);
  5010. if(element.hasAttribute("annotation"))
  5011. {
  5012. abutton->setAnnotation(element.attribute("annotation"));
  5013. }
  5014. if(element.hasAttribute("series"))
  5015. {
  5016. abutton->setTemperatureColumn(element.attribute("series").
  5017. toInt());
  5018. }
  5019. if(element.hasAttribute("column"))
  5020. {
  5021. abutton->setAnnotationColumn(element.attribute("column").
  5022. toInt());
  5023. }
  5024. button = abutton;
  5025. }
  5026. else if(type == "check")
  5027. {
  5028. button = new QCheckBox(text);
  5029. }
  5030. else if(type == "push")
  5031. {
  5032. button = new QPushButton(text);
  5033. }
  5034. }
  5035. if(element.hasAttribute("id"))
  5036. {
  5037. button->setObjectName(element.attribute("id"));
  5038. }
  5039. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5040. layout->addWidget(button);
  5041. }
  5042. @ While annotation buttons are useful for many batch notes, a spin box is
  5043. sometimes a better input choice. There are several attributes that can be set on
  5044. a spin box. These include text to be included in the annotation before and after
  5045. the value of the spin box, the temperature and annotation columns, the range of
  5046. values available in the spin box, the precision of allowed values, and the
  5047. amount by which increment and decrement operations change the value.
  5048. @<Functions for scripting@>=
  5049. void addSpinBoxToLayout(QDomElement element, QStack<QWidget *> *,@|
  5050. QStack<QLayout *> *layoutStack)
  5051. {
  5052. AnnotationSpinBox *box = new AnnotationSpinBox("", "", NULL);
  5053. if(element.hasAttribute("pretext"))
  5054. {
  5055. box->setPretext(QCoreApplication::translate(
  5056. "configuration",
  5057. element.attribute("pretext").toUtf8().data()));
  5058. }
  5059. if(element.hasAttribute("posttext"))
  5060. {
  5061. box->setPosttext(QCoreApplication::translate(
  5062. "configuration",
  5063. element.attribute("posttext").toUtf8().data()));
  5064. }
  5065. if(element.hasAttribute("series"))
  5066. {
  5067. box->setTemperatureColumn(element.attribute("series").toInt());
  5068. }
  5069. if(element.hasAttribute("column"))
  5070. {
  5071. box->setAnnotationColumn(element.attribute("column").toInt());
  5072. }
  5073. if(element.hasAttribute("min"))
  5074. {
  5075. box->setMinimum(element.attribute("min").toDouble());
  5076. }
  5077. if(element.hasAttribute("max"))
  5078. {
  5079. box->setMaximum(element.attribute("max").toDouble());
  5080. }
  5081. if(element.hasAttribute("decimals"))
  5082. {
  5083. box->setDecimals(element.attribute("decimals").toInt());
  5084. }
  5085. if(element.hasAttribute("step"))
  5086. {
  5087. box->setSingleStep(element.attribute("step").toDouble());
  5088. }
  5089. if(element.hasAttribute("id"))
  5090. {
  5091. box->setObjectName(element.attribute("id"));
  5092. }
  5093. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5094. layout->addWidget(box);
  5095. }
  5096. @ Previously, in order to change a |ZoomLog| from the default set of columns,
  5097. script code would need to alter the column set. While this works fine on a Mac,
  5098. this did not work very well under Windows. For the current version, I would like
  5099. to remove the need to deal with table columns from the host environment. The
  5100. first step for this is allowing column descriptions in XML. After this, I'@q'@>d like
  5101. to remove the default column set from the widget code and provide some better
  5102. functionality for dealing with additional data sets.
  5103. When creating the |ZoomLog| here, we check for {\tt <column>} child elements
  5104. which specify the names of the columns.
  5105. @<Functions for scripting@>=
  5106. void addZoomLogToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  5107. QStack<QLayout *> *)
  5108. {
  5109. ZoomLog *widget = new ZoomLog;
  5110. if(element.hasAttribute("id"))
  5111. {
  5112. widget->setObjectName(element.attribute("id"));
  5113. }
  5114. if(element.hasChildNodes())
  5115. {
  5116. QDomNodeList children = element.childNodes();
  5117. int column = 0;
  5118. for(int i = 0; i < children.count(); i++)
  5119. {
  5120. QDomNode current;
  5121. QDomElement currentElement;
  5122. current = children.at(i);
  5123. if(current.isElement())
  5124. {
  5125. currentElement = current.toElement();
  5126. if(currentElement.tagName() == "column")
  5127. {
  5128. QString text =
  5129. QCoreApplication::translate(
  5130. "configuration",
  5131. currentElement.text().toUtf8().data());
  5132. widget->setHeaderData(column, text);
  5133. column++;
  5134. }
  5135. }
  5136. }
  5137. }
  5138. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  5139. if(splitter)
  5140. {
  5141. splitter->addWidget(widget);
  5142. }
  5143. else
  5144. {
  5145. qDebug() << "Splitter not found at top of widget stack!";
  5146. }
  5147. }
  5148. @ The last of the widgets needed to duplicate the window provided in previous
  5149. versions of \pn{} is the |GraphView|.
  5150. @<Functions for scripting@>=
  5151. void addGraphToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  5152. QStack<QLayout *> *)
  5153. {
  5154. GraphView *view = new GraphView;
  5155. if(element.hasAttribute("id"))
  5156. {
  5157. view->setObjectName(element.attribute("id"));
  5158. }
  5159. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  5160. splitter->addWidget(view);
  5161. }
  5162. @ When interacting with a database, it can be useful to provide a combo box
  5163. populated by the results of a database query. One way to do this is through a
  5164. |SqlComboBox| widget.
  5165. @<Functions for scripting@>=
  5166. void addSqlDropToLayout(QDomElement element, QStack<QWidget *> *,@|
  5167. QStack<QLayout *> *layoutStack)
  5168. {
  5169. SqlComboBox *box = new SqlComboBox();
  5170. if(element.hasAttribute("data"))
  5171. {
  5172. box->setDataColumn(element.attribute("data").toInt());
  5173. }
  5174. if(element.hasAttribute("display"))
  5175. {
  5176. box->setDisplayColumn(element.attribute("display").toInt());
  5177. }
  5178. if(element.hasAttribute("showdata"))
  5179. {
  5180. if(element.attribute("showdata") == "true")
  5181. {
  5182. box->showData(true);
  5183. }
  5184. }
  5185. if(element.hasAttribute("editable"))
  5186. {
  5187. if(element.attribute("editable") == "true")
  5188. {
  5189. box->setEditable(true);
  5190. }
  5191. }
  5192. if(element.hasChildNodes())
  5193. {
  5194. QDomNodeList children = element.childNodes();
  5195. for(int i = 0; i < children.count(); i++)
  5196. {
  5197. QDomNode current;
  5198. QDomElement currentElement;
  5199. current = children.at(i);
  5200. if(current.isElement())
  5201. {
  5202. currentElement = current.toElement();
  5203. if(currentElement.tagName() == "null")
  5204. {
  5205. box->addNullOption();
  5206. }
  5207. else if(currentElement.tagName() == "query")
  5208. {
  5209. box->addSqlOptions(currentElement.text());
  5210. }
  5211. }
  5212. }
  5213. }
  5214. if(element.hasAttribute("id"))
  5215. {
  5216. box->setObjectName(element.attribute("id"));
  5217. }
  5218. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5219. layout->addWidget(box);
  5220. }
  5221. @ The next database aware widget that can be useful to have in \pn{} is a
  5222. {\bf S}QL {\bf A}rray {\bf L}iteral {\bf T}able. As might be apparent from the
  5223. name, this is a table view with an associated model and delegates appropriate
  5224. for creating ordered arrays to pass into a database. Each column represents an
  5225. array of values. The most common use of this is in cases where it is important
  5226. to produce multiple arrays of the same size in which each element of one array
  5227. is related to the element in the same position of another array. For example,
  5228. when roasting coffee there are times when some may want to add more than one
  5229. coffee to the roaster at a time. In order to correctly track the green coffee
  5230. inventory and so that the roasting log may have an accurate record of what is
  5231. really happening, insertions on the roasting log provide two arrays, one
  5232. representing all of the coffees being added to the roaster, the other the amount
  5233. of each of these coffees. The database can then use a trigger function to
  5234. examine these arrays and produce the necessary entries in the use table which in
  5235. turn update the record containing the amount of each green coffee currently in
  5236. stock.
  5237. While a generic |QTableView| is used here, there is a need to add functionality
  5238. specific to using this table with a |SaltModel| when obtaining this widget from
  5239. the host environment. In order to accomodate this, we add a dynamic property to
  5240. the view to identify the type of table in the absense of a unique class name.
  5241. @<Functions for scripting@>=
  5242. void addSaltToLayout(QDomElement element, QStack<QWidget *> *,@|
  5243. QStack<QLayout *> *layoutStack)
  5244. {
  5245. QTableView *view = new QTableView;
  5246. view->setProperty("tabletype", QVariant(QString("SaltTable")));
  5247. SaltModel *model = new SaltModel(element.childNodes().count());
  5248. if(element.hasAttribute("id"))
  5249. {
  5250. view->setObjectName(element.attribute("id"));
  5251. }
  5252. if(element.hasChildNodes())
  5253. {
  5254. QDomNodeList children = element.childNodes();
  5255. int currentColumn = 0;
  5256. for(int i = 0; i < children.count(); i++)
  5257. {
  5258. QDomNode current;
  5259. QDomElement currentElement;
  5260. current = children.at(i);
  5261. if(current.isElement())
  5262. {
  5263. currentElement = current.toElement();
  5264. if(currentElement.tagName() == "column")
  5265. {
  5266. if(currentElement.hasAttribute("name"))
  5267. {
  5268. model->setHeaderData(currentColumn,
  5269. Qt::Horizontal,
  5270. QCoreApplication::translate(
  5271. "configuration",
  5272. currentElement.attribute("name").toUtf8().data()));
  5273. }
  5274. if(currentElement.hasAttribute("delegate"))
  5275. {
  5276. @<Set column delegate from XML attribute@>@;
  5277. }
  5278. currentColumn++;
  5279. }
  5280. }
  5281. }
  5282. }
  5283. view->setModel(model);
  5284. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5285. layout->addWidget(view);
  5286. }
  5287. @ It is often desirable to restrict the allowed values in an entry to either a
  5288. set of specific values or to a particular type of value. Delegates can be set
  5289. on a column to enforce such restrictions.
  5290. @<Set column delegate from XML attribute@>=
  5291. if(currentElement.attribute("delegate") == "sql")
  5292. {
  5293. @<Assign column delegate from SQL@>@;
  5294. }
  5295. else if(currentElement.attribute("delegate") == "numeric")
  5296. {
  5297. @<Assign numeric column delegate@>@;
  5298. }
  5299. @ When using a |SaltModel|, there are times where the array values being
  5300. inserted are identification numbers representing some record that already exists
  5301. in the database. For example, the id number representing a green coffee in the
  5302. table of items. In such a case, it is beneficial to provide a delegate capable
  5303. of presenting a human readable list of choices.
  5304. @<Assign column delegate from SQL@>=
  5305. SqlComboBoxDelegate *delegate = new SqlComboBoxDelegate;
  5306. SqlComboBox *widget = new SqlComboBox();
  5307. if(currentElement.hasAttribute("nulltext"))
  5308. {
  5309. widget->setNullText(currentElement.attribute("nulltext"));
  5310. }
  5311. if(currentElement.hasAttribute("nulldata"))
  5312. {
  5313. widget->setNullData(QVariant(currentElement.attribute("nulldata")));
  5314. }
  5315. if(currentElement.hasAttribute("null"))
  5316. {
  5317. if(currentElement.attribute("null") == "true")
  5318. {
  5319. widget->addNullOption();
  5320. }
  5321. }
  5322. if(currentElement.hasAttribute("showdata"))
  5323. {
  5324. if(currentElement.attribute("showdata") == "true")
  5325. {
  5326. widget->showData(true);
  5327. }
  5328. }
  5329. if(currentElement.hasAttribute("data"))
  5330. {
  5331. widget->setDataColumn(currentElement.attribute("data").toInt());
  5332. }
  5333. if(currentElement.hasAttribute("display"))
  5334. {
  5335. widget->setDisplayColumn(currentElement.attribute("display").toInt());
  5336. }
  5337. widget->addSqlOptions(currentElement.text());
  5338. delegate->setWidget(widget);
  5339. view->setItemDelegateForColumn(currentColumn, delegate);
  5340. @ Another common use is allowing numeric values. At present this only
  5341. restricts input to numbers, however it may be useful to provide other options
  5342. such as restricting the range of allowed values in the future.
  5343. @<Assign numeric column delegate@>=
  5344. NumericDelegate *delegate = new NumericDelegate;
  5345. view->setItemDelegateForColumn(currentColumn, delegate);
  5346. @ The |NumericDelegate| will only set the display value to a number, but it
  5347. will perform mathematical calculations that are entered into the editor as
  5348. well. This allows a person to type something like $13.26+5.06$ with the result
  5349. of the expression ($18.32$) appearing in the table.
  5350. @<Class declarations@>=
  5351. class NumericDelegate : public QItemDelegate@/
  5352. {
  5353. @[Q_OBJECT@]@;
  5354. public:@/
  5355. NumericDelegate(QObject *parent = NULL);
  5356. QWidget *createEditor(QWidget *parent,
  5357. const QStyleOptionViewItem &option,@|
  5358. const QModelIndex &index) const;
  5359. void setEditorData(QWidget *editor, const QModelIndex &index) const;
  5360. void setModelData(QWidget *editor, QAbstractItemModel *model,@|
  5361. const QModelIndex &index) const;
  5362. void updateEditorGeometry(QWidget *editor,
  5363. const QStyleOptionViewItem &option,@|
  5364. const QModelIndex &index) const;
  5365. };
  5366. @ There is nothing special about the constructor.
  5367. @<NumericDelegate implementation@>=
  5368. NumericDelegate::NumericDelegate(QObject *parent) :
  5369. QItemDelegate(parent)
  5370. {
  5371. /* Nothing needs to be done here. */
  5372. }
  5373. @ Two roles are used by this delegate. The edit role should contain whatever
  5374. text has been entered in the editor while the display role contain the numeric
  5375. result of any expression that has been entered. Our editor only requires the
  5376. first of these.
  5377. @<NumericDelegate implementation@>=
  5378. void NumericDelegate::setEditorData(QWidget *editor,
  5379. const QModelIndex &index) const
  5380. {
  5381. QString value = index.model()->data(index, Qt::EditRole).toString();
  5382. QLineEdit *line = static_cast<QLineEdit*>(editor);
  5383. line->setText(value);
  5384. }
  5385. @ When editing is finished, the expression text must be saved back to the
  5386. model and the expression should be evaluated to set the display role. We make
  5387. use of the existing scripting engine to evaluate the expression, but only
  5388. preserve the result in the display role if the result of that expression is
  5389. numeric.
  5390. @<NumericDelegate implementation@>=
  5391. void NumericDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
  5392. const QModelIndex &index) const
  5393. {
  5394. QLineEdit *line = static_cast<QLineEdit*>(editor);
  5395. model->setData(index, line->text(), Qt::EditRole);
  5396. QScriptEngine *engine = AppInstance->engine;
  5397. engine->pushContext();
  5398. QString script = QString("Number(%1)").arg(line->text());
  5399. QScriptValue result = engine->evaluate(line->text());
  5400. if(result.isNumber())
  5401. {
  5402. model->setData(index, result.toVariant(), Qt::DisplayRole);
  5403. }
  5404. else
  5405. {
  5406. model->setData(index, QVariant(), Qt::DisplayRole);
  5407. }
  5408. engine->popContext();
  5409. }
  5410. @ There is nothing special about the line edit used for this.
  5411. @<NumericDelegate implementation@>=
  5412. QWidget* NumericDelegate::createEditor(QWidget *parent,
  5413. const QStyleOptionViewItem &,
  5414. const QModelIndex &) const
  5415. {
  5416. return (new QLineEdit(parent));
  5417. }
  5418. @ To ensure that the editor is displayed appropriately, we must pass the
  5419. geometry data to our editor.
  5420. @<NumericDelegate implementation@>=
  5421. void NumericDelegate::updateEditorGeometry(QWidget *editor,
  5422. const QStyleOptionViewItem &option,
  5423. const QModelIndex &) const
  5424. {
  5425. editor->setGeometry(option.rect);
  5426. }
  5427. @ The same general technique is useful for input to a |QLineEdit|, but there is
  5428. no model backing that widget to preserve multiple data roles. One way to get
  5429. this functionality without too much effort is to abuse |QValidator| to evaluate
  5430. expressions.
  5431. @<Class declarations@>=
  5432. class ScriptValidator : public QValidator
  5433. {
  5434. Q_OBJECT
  5435. public:
  5436. ScriptValidator(QValidator *validator, QObject *parent = NULL);
  5437. void fixup(QString &input) const;
  5438. QValidator::State validate(QString &input, int &pos) const;
  5439. private:
  5440. QValidator *v;
  5441. };
  5442. @ The key to this is in the |fixup()| method. Here we over-write input with the
  5443. result of the script evaluation.
  5444. @<ScriptValidator implementation@>=
  5445. void ScriptValidator::fixup(QString &input) const
  5446. {
  5447. QScriptEngine *engine = AppInstance->engine;
  5448. engine->pushContext();
  5449. input = engine->evaluate(input).toString();
  5450. engine->popContext();
  5451. }
  5452. @ This validator is intended to be used in conjunction with another one which
  5453. determines if the result of the expression is acceptable. In this case
  5454. |Invalid| is never returned.
  5455. @<ScriptValidator implementation@>=
  5456. QValidator::State ScriptValidator::validate(QString &input, int &pos) const
  5457. {
  5458. if(v)
  5459. {
  5460. if(v->validate(input, pos) == QValidator::Acceptable)
  5461. {
  5462. return QValidator::Acceptable;
  5463. }
  5464. }
  5465. return QValidator::Intermediate;
  5466. }
  5467. @ The constructor is trivial.
  5468. @<ScriptValidator implementation@>=
  5469. ScriptValidator::ScriptValidator(QValidator *validator, QObject *parent)
  5470. : QValidator(parent), v(validator)
  5471. {
  5472. /* Nothing needs to be done here. */
  5473. }
  5474. @ This is included in typica.cpp.
  5475. @<Class implementations@>=
  5476. @<ScriptValidator implementation@>
  5477. @ Line edits are useful when the user is expected to enter text without a
  5478. predetermined set of values.
  5479. Several attributes are supported on line edits. In addition to the usual
  5480. {\tt id} attribute, there is also a {\tt writable} attribute which, if
  5481. {\tt false}, can be used to create read only text areas which can only be edited
  5482. from script code. A {\tt validator} attribute allows entered text to be
  5483. restricted. This can take one of three values. If the value is {\tt "numeric"},
  5484. input is restricted to numeric values. If the value is {\tt "integer"}, input is
  5485. restricted to integer values. Finally, if the value is {\tt "expression"}, input
  5486. is restricted to text which matches a regular expression specified as the value
  5487. of the {\tt expression} attribute.
  5488. Note that when integer and numeric validators are specified, these are set for
  5489. a |ScriptValidator| to enable some basic expression evaluation.
  5490. @<Functions for scripting@>=
  5491. void addLineToLayout(QDomElement element, QStack<QWidget *> *,@|
  5492. QStack<QLayout *> *layoutStack)
  5493. {
  5494. QLineEdit *widget = new QLineEdit(element.text());
  5495. if(element.hasAttribute("id"))
  5496. {
  5497. widget->setObjectName(element.attribute("id"));
  5498. }
  5499. if(element.hasAttribute("writable"))
  5500. {
  5501. if(element.attribute("writable") == "false")
  5502. {
  5503. widget->setReadOnly(true);
  5504. }
  5505. }
  5506. if(element.hasAttribute("validator"))
  5507. {
  5508. if(element.attribute("validator") == "numeric")
  5509. {
  5510. widget->setValidator(new ScriptValidator(new QDoubleValidator));
  5511. }
  5512. else if(element.attribute("validator") == "integer")
  5513. {
  5514. widget->setValidator(new ScriptValidator(new QIntValidator));
  5515. }
  5516. else if(element.attribute("validator") == "expression" &&
  5517. element.hasAttribute("expression"))
  5518. {
  5519. widget->setValidator(new QRegExpValidator(
  5520. QRegExp(element.attribute("expression")),
  5521. NULL));
  5522. }
  5523. }
  5524. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5525. layout->addWidget(widget);
  5526. }
  5527. @ It is natural for certain database fields to enter potentially large amounts
  5528. of free form text, for example, notes and annotations.
  5529. @<Functions for scripting@>=
  5530. void addTextToLayout(QDomElement element, QStack<QWidget *> *,@|
  5531. QStack<QLayout *> *layoutStack)
  5532. {
  5533. QTextEdit *widget = new QTextEdit;
  5534. if(element.hasAttribute("id"))
  5535. {
  5536. widget->setObjectName(element.attribute("id"));
  5537. }
  5538. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5539. layout->addWidget(widget);
  5540. }
  5541. @ The common use of |SqlQueryView| calls for the possibility of changing the
  5542. query during use. As such, there is little reason to accept attributes other
  5543. than an id for obtaining the view in a script.
  5544. @<Functions for scripting@>=
  5545. void addSqlQueryViewToLayout(QDomElement element,
  5546. QStack<QWidget *> *,@|
  5547. QStack<QLayout *> *layoutStack)
  5548. {
  5549. SqlQueryView *view = new SqlQueryView;
  5550. if(element.hasAttribute("id"))
  5551. {
  5552. view->setObjectName(element.attribute("id"));
  5553. }
  5554. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5555. layout->addWidget(view);
  5556. }
  5557. @ When the user is expected to enter a date, it is appropriate to use a date
  5558. editor. This one provides a calendar.
  5559. @<Functions for scripting@>=
  5560. void addCalendarToLayout(QDomElement element, QStack<QWidget *> *,@|
  5561. QStack<QLayout *> *layoutStack)
  5562. {
  5563. QWidget *widget;
  5564. if(element.hasAttribute("time"))
  5565. {
  5566. if(element.attribute("time") == "true")
  5567. {
  5568. QDateTimeEdit *edit = new QDateTimeEdit;
  5569. edit->setDateTime(QDateTime::currentDateTime());
  5570. edit->setCalendarPopup(true);
  5571. edit->setDisplayFormat("yyyy-MM-dd hh:mm:ss");
  5572. widget = qobject_cast<QWidget *>(edit);
  5573. }
  5574. else
  5575. {
  5576. QDateEdit *edit = new QDateEdit;
  5577. edit->setDate(QDate::currentDate());
  5578. edit->setCalendarPopup(true);
  5579. edit->setDisplayFormat("yyyy-MM-dd");
  5580. widget = qobject_cast<QWidget *>(edit);
  5581. }
  5582. }
  5583. else
  5584. {
  5585. QDateEdit *edit = new QDateEdit;
  5586. edit->setDate(QDate::currentDate());
  5587. edit->setCalendarPopup(true);
  5588. edit->setDisplayFormat("yyyy-MM-dd");
  5589. widget = qobject_cast<QWidget *>(edit);
  5590. }
  5591. if(element.hasAttribute("id"))
  5592. {
  5593. widget->setObjectName(element.attribute("id"));
  5594. }
  5595. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5596. layout->addWidget(widget);
  5597. }
  5598. @ Some additional properties are added to this object when it is retrieved by
  5599. the host environment.
  5600. @<Functions for scripting@>=
  5601. void setQDateEditProperties(QScriptValue value, QScriptEngine *engine)
  5602. {
  5603. setQDateTimeEditProperties(value, engine);
  5604. }
  5605. void setQDateTimeEditProperties(QScriptValue value, QScriptEngine *engine)
  5606. {
  5607. setQAbstractSpinBoxProperties(value, engine);
  5608. value.setProperty("setDate", engine->newFunction(QDateTimeEdit_setDate));
  5609. value.setProperty("day", engine->newFunction(QDateTimeEdit_day));
  5610. value.setProperty("month", engine->newFunction(QDateTimeEdit_month));
  5611. value.setProperty("year", engine->newFunction(QDateTimeEdit_year));
  5612. value.setProperty("setToCurrentTime",
  5613. engine->newFunction(QDateTimeEdit_setToCurrentTime));
  5614. }
  5615. @ Certain operations on a |QDateEdit| are easier with a few convenience
  5616. properties that bypass the need to use the built in |date| property. For
  5617. example, an editor that should be set to 1 January of the current year can
  5618. obtain the year and set the date without directly using a |QDate| object.
  5619. @<Functions for scripting@>=
  5620. QScriptValue QDateTimeEdit_setDate(QScriptContext *context, QScriptEngine *)
  5621. {
  5622. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5623. if(context->argumentCount() == 3)
  5624. {
  5625. self->setDate(QDate(argument<int>(0, context),
  5626. argument<int>(1, context),
  5627. argument<int>(2, context)));
  5628. }
  5629. else
  5630. {
  5631. context->throwError("Incorrect number of arguments passed to "
  5632. "QDateTimeEdit::setDate(). This method takes three integer arguments "
  5633. "specifying the year, month, and day.");
  5634. }
  5635. return QScriptValue();
  5636. }
  5637. QScriptValue QDateTimeEdit_day(QScriptContext *context, QScriptEngine *)
  5638. {
  5639. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5640. return QScriptValue(self->date().day());
  5641. }
  5642. QScriptValue QDateTimeEdit_month(QScriptContext *context, QScriptEngine *)
  5643. {
  5644. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5645. return QScriptValue(self->date().month());
  5646. }
  5647. QScriptValue QDateTimeEdit_year(QScriptContext *context, QScriptEngine *)
  5648. {
  5649. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5650. return QScriptValue(self->date().year());
  5651. }
  5652. QScriptValue QDateTimeEdit_setToCurrentTime(QScriptContext *context, QScriptEngine *)
  5653. {
  5654. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5655. self->setDateTime(QDateTime::currentDateTime());
  5656. return QScriptValue();
  5657. }
  5658. @ A few function prototypes are needed for this.
  5659. @<Function prototypes for scripting@>=
  5660. void setQDateEditProperties(QScriptValue value, QScriptEngine *engine);
  5661. void setQDateTimeEditProperties(QScriptValue value, QScriptEngine *engine);
  5662. QScriptValue QDateTimeEdit_setDate(QScriptContext *context,
  5663. QScriptEngine *engine);
  5664. QScriptValue QDateTimeEdit_day(QScriptContext *context, QScriptEngine *engine);
  5665. QScriptValue QDateTimeEdit_month(QScriptContext *context,
  5666. QScriptEngine *engine);
  5667. QScriptValue QDateTimeEdit_year(QScriptContext *context, QScriptEngine *engine);
  5668. QScriptValue QDateTimeEdit_setToCurrentTime(QScriptContext *context, QScriptEngine *engine);
  5669. @ Sometimes it can be useful to allow editing a time or duration value without
  5670. a date field. For this, a |QTimeEdit| can be used.
  5671. @<Functions for scripting@>=
  5672. void addTimeEditToLayout(QDomElement element, QStack<QWidget *> *,@|
  5673. QStack<QLayout *> *layoutStack)
  5674. {
  5675. QTimeEdit *edit = new QTimeEdit;
  5676. if(element.hasAttribute("displayFormat"))
  5677. {
  5678. edit->setDisplayFormat(element.attribute("displayFormat"));
  5679. }
  5680. else
  5681. {
  5682. edit->setDisplayFormat("mm:ss.zzz");
  5683. }
  5684. if(element.hasAttribute("id"))
  5685. {
  5686. edit->setObjectName(element.attribute("id"));
  5687. }
  5688. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5689. layout->addWidget(edit);
  5690. }
  5691. @ Additional properties are added as a |QTimeEdit| is a |QDateTimeEdit|.
  5692. @<Functions for scripting@>=
  5693. void setQTimeEditProperties(QScriptValue value, QScriptEngine *engine)
  5694. {
  5695. setQDateTimeEditProperties(value, engine);
  5696. }
  5697. @ A function prototype is needed.
  5698. @<Function prototypes for scripting@>=
  5699. void setQTimeEditProperties(QScriptValue value, QScriptEngine *engine);
  5700. @ In order to get to objects created from the XML description, it is necessary
  5701. to provide a function that can be called to retrieve children of a given widget.
  5702. When providing such an object to the script, it is necessary to determine the
  5703. type of that object and add the appropriate properties.
  5704. @<Function prototypes for scripting@>=
  5705. QScriptValue findChildObject(QScriptContext *context, QScriptEngine *engine);
  5706. @ This function must be made available to the scripting engine.
  5707. @<Set up the scripting engine@>=
  5708. engine->globalObject().setProperty("findChildObject",
  5709. engine->newFunction(findChildObject));
  5710. @ This function takes a script value representing some object which may have
  5711. been created from an XML description and a string containing the name of the
  5712. requested child element.
  5713. @<Functions for scripting@>=
  5714. QScriptValue findChildObject(QScriptContext *context, QScriptEngine *engine)
  5715. {
  5716. QObject *parent = argument<QObject *>(0, context);
  5717. QString name = argument<QString>(1, context);
  5718. QObject *object = parent->findChild<QObject *>(name);
  5719. QScriptValue value;
  5720. if(object)
  5721. {
  5722. value = engine->newQObject(object);
  5723. QString className = object->metaObject()->className();
  5724. @<Set object properties based on class name@>@;
  5725. }
  5726. return value;
  5727. }
  5728. @ Properties are added for a large number of class types.
  5729. @<Set object properties based on class name@>=
  5730. if(className == "TemperatureDisplay")
  5731. {
  5732. setTemperatureDisplayProperties(value, engine);
  5733. }
  5734. else if(className == "TimerDisplay")
  5735. {
  5736. setTimerDisplayProperties(value, engine);
  5737. }
  5738. else if(className == "QAction")
  5739. {
  5740. setQActionProperties(value, engine);
  5741. }
  5742. else if(className == "QBoxLayout")
  5743. {
  5744. setQBoxLayoutProperties(value, engine);
  5745. }
  5746. else if(className == "QDateEdit")
  5747. {
  5748. setQDateEditProperties(value, engine);
  5749. }
  5750. else if(className == "QDateTimeEdit")
  5751. {
  5752. setQDateTimeEditProperties(value, engine);
  5753. }
  5754. else if(className == "QFrame")
  5755. {
  5756. setQFrameProperties(value, engine);
  5757. }
  5758. else if(className == "QHBoxLayout")
  5759. {
  5760. setQBoxLayoutProperties(value, engine);
  5761. }
  5762. else if(className == "QLCDNumber")
  5763. {
  5764. setQLCDNumberProperties(value, engine);
  5765. }
  5766. else if(className == "QMenu")
  5767. {
  5768. setQMenuProperties(value, engine);
  5769. }
  5770. else if(className == "QMenuBar")
  5771. {
  5772. setQMenuBarProperties(value, engine);
  5773. }
  5774. else if(className == "QPushButton")
  5775. {
  5776. setQPushButtonProperties(value, engine);
  5777. }
  5778. else if(className == "QSplitter")
  5779. {
  5780. setQSplitterProperties(value, engine);
  5781. }
  5782. else if(className == "QTableView")
  5783. {
  5784. if(object->property("tabletype").isValid())
  5785. {
  5786. if(object->property("tabletype").toString() == "SaltTable")
  5787. {
  5788. setSaltTableProperties(value, engine);
  5789. }
  5790. }
  5791. }
  5792. else if(className == "QVBoxLayout")
  5793. {
  5794. setQBoxLayoutProperties(value, engine);
  5795. }
  5796. else if(className == "QWidget")
  5797. {
  5798. setQWidgetProperties(value, engine);
  5799. }
  5800. else if(className == "ScriptQMainWindow")
  5801. {
  5802. setQMainWindowProperties(value, engine);
  5803. }
  5804. else if(className == "SqlComboBox")
  5805. {
  5806. setSqlComboBoxProperties(value, engine);
  5807. }
  5808. else if(className == "SqlQueryView")
  5809. {
  5810. setSqlQueryViewProperties(value, engine);
  5811. }
  5812. else if(className == "ZoomLog")
  5813. {
  5814. setZoomLogProperties(value, engine);
  5815. }
  5816. else if(className == "QTextEdit")
  5817. {
  5818. setQTextEditProperties(value, engine);
  5819. }
  5820. else if(className == "QWebView")
  5821. {
  5822. setQWebViewProperties(value, engine);
  5823. }
  5824. else if(className == "QLineEdit")
  5825. {
  5826. setQLineEditProperties(value, engine);
  5827. }
  5828. else if(className == "QSvgWidget")
  5829. {
  5830. setQSvgWidgetProperties(value, engine);
  5831. }
  5832. else if(className == "QTabBar")
  5833. {
  5834. setQTabBarProperties(value, engine);
  5835. }
  5836. else if(className == "PrinterSelector")
  5837. {
  5838. setQComboBoxProperties(value, engine);
  5839. }
  5840. @ In the list of classes, the SaltTable entry is for a class which does not
  5841. strictly exist on its own. It is, however, useful to provide some custom
  5842. properties when passing such an object to the host environment.
  5843. @<Function prototypes for scripting@>=
  5844. void setSaltTableProperties(QScriptValue value, QScriptEngine *engine);
  5845. QScriptValue SaltTable_bindableColumnArray(QScriptContext *context,
  5846. QScriptEngine *engine);
  5847. QScriptValue SaltTable_bindableQuotedColumnArray(QScriptContext *context,
  5848. QScriptEngine *engine);
  5849. QScriptValue SaltTable_columnSum(QScriptContext *context,
  5850. QScriptEngine *engine);
  5851. QScriptValue SaltTable_columnArray(QScriptContext *context,
  5852. QScriptEngine *engine);
  5853. QScriptValue SaltTable_data(QScriptContext *context, QScriptEngine *engine);
  5854. QScriptValue SaltTable_model(QScriptContext *context, QScriptEngine *engine);
  5855. QScriptValue SaltTable_quotedColumnArray(QScriptContext *context,
  5856. QScriptEngine *engine);
  5857. QScriptValue SaltTable_setData(QScriptContext *context, QScriptEngine *engine);
  5858. QScriptValue SaltTable_clear(QScriptContext *context, QScriptEngine *engine);
  5859. QScriptValue SaltTable_removeRow(QScriptContext *context, QScriptEngine *engine);
  5860. QScriptValue SaltTable_findData(QScriptContext *context, QScriptEngine *engine);
  5861. @ There are times when it is useful to obtain the sum of values in a column of
  5862. a SaltTable object. For example, when a column represents the weight of the
  5863. green coffee used in a batch, a sum of that column provides the total weight of
  5864. the batch which, when presented to the user, can be used to catch errors in
  5865. measuring batches or entering data.
  5866. @<Functions for scripting@>=
  5867. QScriptValue SaltTable_columnSum(QScriptContext *context, QScriptEngine *engine)
  5868. {
  5869. QTableView *self = getself<QTableView *>(context);
  5870. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5871. QString datum;
  5872. double total = 0.0;
  5873. int column = argument<int>(0, context);
  5874. int role = argument<int>(1, context);
  5875. for(int i = 0; i < model->rowCount(); i++)
  5876. {
  5877. datum = model->data(model->index(i, column), role).toString();
  5878. if(!datum.isEmpty())
  5879. {
  5880. total += datum.toDouble();
  5881. }
  5882. }
  5883. return QScriptValue(engine, total);
  5884. }
  5885. @ Another common use of the SaltTable is producing the text for an array literal
  5886. to pass into a SQL query. The |SaltModel| used by this table makes this simple.
  5887. There are four functions for this functionality for different use cases.
  5888. @<Functions for scripting@>=
  5889. QScriptValue SaltTable_columnArray(QScriptContext *context,
  5890. QScriptEngine *engine)
  5891. {
  5892. QTableView *self = getself<QTableView *>(context);
  5893. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5894. int column = argument<int>(0, context);
  5895. int role = argument<int>(1, context);
  5896. QString literal = model->arrayLiteral(column, role);
  5897. return QScriptValue(engine, literal);
  5898. }
  5899. QScriptValue SaltTable_quotedColumnArray(QScriptContext *context,
  5900. QScriptEngine *engine)
  5901. {
  5902. QTableView *self = getself<QTableView *>(context);
  5903. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5904. int column = argument<int>(0, context);
  5905. int role = argument<int>(1, context);
  5906. QString literal = model->quotedArrayLiteral(column, role);
  5907. return QScriptValue(engine, literal);
  5908. }
  5909. QScriptValue SaltTable_bindableColumnArray(QScriptContext *context,
  5910. QScriptEngine *engine)
  5911. {
  5912. QTableView *self = getself<QTableView *>(context);
  5913. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5914. int column = argument<int>(0, context);
  5915. int role = argument<int>(1, context);
  5916. QString literal = model->arrayLiteral(column, role);
  5917. literal.chop(1);
  5918. literal = literal.remove(0, 1);
  5919. return QScriptValue(engine, literal);
  5920. }
  5921. QScriptValue SaltTable_bindableQuotedColumnArray(QScriptContext *context,
  5922. QScriptEngine *engine)
  5923. {
  5924. QTableView *self = getself<QTableView *>(context);
  5925. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5926. int column = argument<int>(0, context);
  5927. int role = argument<int>(1, context);
  5928. QString literal = model->quotedArrayLiteral(column, role);
  5929. literal.chop(1);
  5930. literal = literal.remove(0, 1);
  5931. return QScriptValue(engine, literal);
  5932. }
  5933. @ In order to obtain signals related to changes in the model, we need a way to
  5934. get to the model from the host environment.
  5935. @<Functions for scripting@>=
  5936. QScriptValue SaltTable_model(QScriptContext *context, QScriptEngine *engine)
  5937. {
  5938. QTableView *self = getself<QTableView *>(context);
  5939. QScriptValue value = engine->newQObject(self->model());
  5940. return value;
  5941. }
  5942. @ While this table was originally intended strictly for user input, there are a
  5943. few use cases in which it is useful to allow scripts to set the values in the
  5944. table. This can be done with |setData|. This method takes four arguments: the
  5945. row and column of the table being set, the value to set, and the role of the
  5946. data being set.
  5947. @<Functions for scripting@>=
  5948. QScriptValue SaltTable_setData(QScriptContext *context, QScriptEngine *)
  5949. {
  5950. QTableView *self = getself<QTableView *>(context);
  5951. int row = argument<int>(0, context);
  5952. int column = argument<int>(1, context);
  5953. QVariant value = argument<QVariant>(2, context);
  5954. int role = argument<int>(3, context);
  5955. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5956. QModelIndex cell = model->index(row, column);
  5957. model->setData(cell, value, role);
  5958. self->update(cell);
  5959. return QScriptValue();
  5960. }
  5961. @ It is sometimes useful to obtain the data from a single cell of the table.
  5962. This can be done with the |data()| property.
  5963. @<Functions for scripting@>=
  5964. QScriptValue SaltTable_data(QScriptContext *context, QScriptEngine *engine)
  5965. {
  5966. QTableView *self = getself<QTableView *>(context);
  5967. int row = argument<int>(0, context);
  5968. int column = argument<int>(1, context);
  5969. int role = argument<int>(2, context);
  5970. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5971. QModelIndex cell = model->index(row, column);
  5972. QVariant value = model->data(cell, role);
  5973. QScriptValue retval = engine->newVariant(value);
  5974. retval.setProperty("value", QScriptValue(value.toString()));
  5975. return retval;
  5976. }
  5977. @ There are times when it is useful to clear the content of a table. This is
  5978. used, for example, in the green coffees table after changing the roasted coffee
  5979. item to eliminate excess rows in the case where the previously selected item
  5980. was a pre-roast blend.
  5981. @<Functions for scripting@>=
  5982. QScriptValue SaltTable_clear(QScriptContext *context, QScriptEngine *)
  5983. {
  5984. QTableView *self = getself<QTableView *>(context);
  5985. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5986. model->clear();
  5987. return QScriptValue();
  5988. }
  5989. @ It is sometimes useful to remove a row from a table. This is done in the new
  5990. batch window when the coffee for a row is set to a NULL item.
  5991. @<Functions for scripting@>=
  5992. QScriptValue SaltTable_removeRow(QScriptContext *context, QScriptEngine *engine)
  5993. {
  5994. QTableView *self = getself<QTableView *>(context);
  5995. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5996. int row = argument<int>(0, context);
  5997. return engine->newVariant(model->removeRow(row));
  5998. }
  5999. @ To remove the correct row, it is sometimes useful to query the table for
  6000. special values. This is done with the |findData()| method on the underlying
  6001. model.
  6002. @<Functions for scripting@>=
  6003. QScriptValue SaltTable_findData(QScriptContext *context, QScriptEngine *engine)
  6004. {
  6005. QTableView *self = getself<QTableView *>(context);
  6006. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  6007. QVariant value = argument<QVariant>(0, context);
  6008. int column = argument<int>(1, context);
  6009. return engine->newVariant(model->findData(value, column));
  6010. }
  6011. @ These functions need to be added as properties of the table when it is passed
  6012. to the host environment.
  6013. @<Functions for scripting@>=
  6014. void setSaltTableProperties(QScriptValue value, QScriptEngine *engine)
  6015. {
  6016. setQWidgetProperties(value, engine);
  6017. value.setProperty("columnArray",
  6018. engine->newFunction(SaltTable_columnArray));
  6019. value.setProperty("quotedColumnArray",
  6020. engine->newFunction(SaltTable_quotedColumnArray));
  6021. value.setProperty("bindableColumnArray",
  6022. engine->newFunction(SaltTable_bindableColumnArray));
  6023. value.setProperty("bindableQuotedColumnArray",
  6024. engine->newFunction(SaltTable_bindableQuotedColumnArray));
  6025. value.setProperty("columnSum", engine->newFunction(SaltTable_columnSum));
  6026. value.setProperty("data", engine->newFunction(SaltTable_data));
  6027. value.setProperty("model", engine->newFunction(SaltTable_model));
  6028. value.setProperty("setData", engine->newFunction(SaltTable_setData));
  6029. value.setProperty("clear", engine->newFunction(SaltTable_clear));
  6030. value.setProperty("removeRow", engine->newFunction(SaltTable_removeRow));
  6031. value.setProperty("findData", engine->newFunction(SaltTable_findData));
  6032. }
  6033. @ The |SqlComboBox| is another class that is not constructed from scripts but is
  6034. useful to access from them. A property is added to obtain the current user data
  6035. from the widget.
  6036. @<Function prototypes for scripting@>=
  6037. void setSqlComboBoxProperties(QScriptValue value, QScriptEngine *engine);
  6038. void setQComboBoxProperties(QScriptValue value, QScriptEngine *engine);
  6039. QScriptValue QComboBox_currentData(QScriptContext *context,
  6040. QScriptEngine *engine);
  6041. QScriptValue QComboBox_addItem(QScriptContext *context, QScriptEngine *engine);
  6042. QScriptValue QComboBox_setModel(QScriptContext *context, QScriptEngine *engine);
  6043. QScriptValue QComboBox_findText(QScriptContext *context, QScriptEngine *engine);
  6044. QScriptValue QComboBox_findData(QScriptContext *context, QScriptEngine *engine);
  6045. @ These functions should seem familiar by now.
  6046. @<Functions for scripting@>=
  6047. void setSqlComboBoxProperties(QScriptValue value, QScriptEngine *engine)
  6048. {
  6049. setQComboBoxProperties(value, engine);
  6050. }
  6051. void setQComboBoxProperties(QScriptValue value, QScriptEngine *engine)
  6052. {
  6053. setQWidgetProperties(value, engine);
  6054. value.setProperty("currentData",
  6055. engine->newFunction(QComboBox_currentData));
  6056. value.setProperty("addItem", engine->newFunction(QComboBox_addItem));
  6057. value.setProperty("setModel", engine->newFunction(QComboBox_setModel));
  6058. value.setProperty("findText", engine->newFunction(QComboBox_findText));
  6059. value.setProperty("findData", engine->newFunction(QComboBox_findData));
  6060. }
  6061. QScriptValue QComboBox_currentData(QScriptContext *context,
  6062. QScriptEngine *engine)
  6063. {
  6064. QComboBox *self = getself<QComboBox *>(context);
  6065. return QScriptValue(engine,
  6066. self->itemData(self->currentIndex()).toString());
  6067. }
  6068. QScriptValue QComboBox_addItem(QScriptContext *context, QScriptEngine *)
  6069. {
  6070. QComboBox *self = getself<QComboBox *>(context);
  6071. self->addItem(argument<QString>(0, context));
  6072. return QScriptValue();
  6073. }
  6074. QScriptValue QComboBox_setModel(QScriptContext *context, QScriptEngine *)
  6075. {
  6076. QComboBox *self = getself<QComboBox *>(context);
  6077. self->setModel(argument<QAbstractItemModel *>(0, context));
  6078. return QScriptValue();
  6079. }
  6080. QScriptValue QComboBox_findText(QScriptContext *context, QScriptEngine *engine)
  6081. {
  6082. QComboBox *self = getself<QComboBox *>(context);
  6083. return QScriptValue(engine, self->findText(argument<QString>(0, context)));
  6084. }
  6085. QScriptValue QComboBox_findData(QScriptContext *context, QScriptEngine *engine)
  6086. {
  6087. QComboBox *self = getself<QComboBox *>(context);
  6088. return QScriptValue(engine, self->findData(argument<QVariant>(0, context)));
  6089. }
  6090. @i abouttypica.w
  6091. @** A representation of temperature measurements.
  6092. \noindent Most of the information in a roast log will be temperature
  6093. measurements. These measurements are made of two components: the measured
  6094. temperature and the time at which that measurement was taken.
  6095. Measurement times are represented as instances of |QTime|.
  6096. @i units.w
  6097. @ We will require the |units.h| header.
  6098. @<Header files to include@>=
  6099. #include "units.h"
  6100. @i measurement.w
  6101. @** The Main Measurement Pipeline.
  6102. \noindent Measurements are sent through \pn{} in a way similar to liquid moving
  6103. through a series of connected pipes. \pn{} is not something that you just dump
  6104. measurements on. It'@q'@>s not a big truck\nfnote{Senator Ted Stevens (R-Alaska) on
  6105. network neutrality, June 28, 2006\par
  6106. \hbox{\indent\pdfURL{http://media.publicknowledge.org/stevens-on-nn.mp3}%
  6107. {http://media.publicknowledge.org/stevens-on-nn.mp3}}}. In most cases the
  6108. connections between classes (represented by arrows in Figure \secno) are made
  6109. with Qt'@q'@>s signals and slots mechanism\nfnote{Qt 4.4.3: Signals and Slots\par
  6110. \hbox{\indent\pdfURL{http://doc.trolltech.com/4.4/signalsandslots.html}%
  6111. {http://doc.trolltech.com/4.4/signalsandslots.html}}}, but
  6112. these
  6113. connections can
  6114. also be made through direct function calls as is the case with the connection
  6115. between |ZoomLog| and |MeasurementModel|.
  6116. \medskip
  6117. \includegraphics{pipes}
  6118. \smallskip
  6119. \centerline{Figure \secno: Example Flow of Measurement objects in \pn}
  6120. \medskip
  6121. Please note that Figure \secno~is representative of a typical configuration. Now
  6122. that the flow of measurements through \pn{} is determined by a script specified
  6123. by the user, whatever pipeline is needed can be specified at run time.
  6124. @* The DAQ class.
  6125. \noindent The |DAQ| class represents a piece of hardware that allows the
  6126. computer to read measurements from one or more thermocouples. Presently this
  6127. class is only handles continuous sampling on devices from National Instruments.
  6128. It should be simple to modify this class to handle similar devices from other
  6129. vendors.
  6130. Each device is represented by a single instance of this class. Multiple channels
  6131. can be used on a device if the device supports it.
  6132. Two enumerations are declared in this class to be used as arguments to
  6133. |newChannel()|. The first is used to set the measurement unit for the channel.
  6134. As the measurements themselves do not carry this information, it is important to
  6135. keep track of this information. The values come from {\tt nidaqmxbase.h} and can
  6136. be used to select among Fahrenheit, Celsius, Kelvin, and Rankine. The
  6137. second enumeration, |ThermocoupleType|, should be used to specify the type of
  6138. thermocouple connected to the device. If this does not match reality, the
  6139. measurements will not be correct. The meanings of the values should be obvious
  6140. from the names.
  6141. \danger When this class was originally written the method of thread handling
  6142. used was considered appropriate. New functionality in |QThread| has made this
  6143. no longer the case. This class is currently planned for depreciation once a
  6144. replacement class hierarchy more suited to multiple hardware types is available
  6145. however if this is not ready soon it may be beneficial to rewrite this class to
  6146. conform to current best practices.\endanger
  6147. @<Class declarations@>=
  6148. class Channel;
  6149. class DAQImplementation;@/
  6150. class DAQ : public QObject@;@/
  6151. {@t\1@>@/
  6152. Q_OBJECT@/
  6153. Q_ENUMS(ThermocoupleType)@;@/
  6154. DAQImplementation *imp;@/
  6155. @t\4@>private slots@t\kern-3pt@>:@/
  6156. void threadFinished();
  6157. public:@;
  6158. DAQ(QString device, const QString &driver = QString("nidaqmxbase"));
  6159. ~DAQ();@/
  6160. Channel* newChannel(int units, int thermocouple);@/
  6161. @[Q_INVOKABLE@,@, void@]@, setClockRate(double Hz);@t\2\2@>@/
  6162. @[Q_INVOKABLE@,@, void@]@, start();@t\2\2@>@/
  6163. @[Q_INVOKABLE@,@, void@]@, stop();@t\2\2@>@/
  6164. enum ThermocoupleType@/
  6165. {
  6166. @!TypeJ = 10072,
  6167. @!TypeK = 10073,
  6168. @!TypeN = 10077,
  6169. @!TypeR = 10082,
  6170. @!TypeS = 10085,
  6171. @!TypeT = 10086,
  6172. @!TypeB = 10047,
  6173. @!TypeE = 10055
  6174. };@t\2@>@/
  6175. }@t\kern-3pt@>;
  6176. @ The |DAQ| class has as a private member an instance of a class called
  6177. |DAQImplementation|. The two classes together create and run a new thread of
  6178. execution. This thread spends most of its time blocking while waiting for a new
  6179. measurement to become available. When a new measurement is available, that
  6180. measurement is passed to the appropriate channel which in turn passes it to any
  6181. interested object.
  6182. @<Class declarations@>=
  6183. class DAQImplementation : public QThread@;@/
  6184. {@;
  6185. Q_OBJECT@;@/
  6186. public:@;
  6187. DAQImplementation(const QString &driverinfo);
  6188. ~DAQImplementation();
  6189. void run();
  6190. void measure();
  6191. @<Library function pointers@>@;
  6192. @<DAQImplementation member data@>@;
  6193. }@+@t\kern-3pt@>;
  6194. @ In order to solve some minor problems, NI-DAQmxBase is no longer linked at
  6195. compile time. Rather, this is now linked at runtime through a |QLibrary| object.
  6196. In order to use functions from this library, these functions must be stored in
  6197. function pointers. Fortunately, all of these functions can be expressed with the
  6198. same pointer type. Unfortunately, this way of doing things offers very little
  6199. debugging information in the event that something is not quite right.
  6200. @<Library function pointers@>=
  6201. typedef int (*daqfp)(...);
  6202. daqfp read;
  6203. daqfp errorInfo;
  6204. daqfp startTask;
  6205. daqfp createTask;
  6206. daqfp createChannel;
  6207. daqfp setClock;
  6208. daqfp stopTask;
  6209. daqfp clearTask;
  6210. daqfp resetDevice;
  6211. daqfp waitForMeasurement;
  6212. @ |DAQImplementation| also maintains information about the device and the
  6213. channels the measurements are sent to.
  6214. @<DAQImplementation member data@>=
  6215. bool useBase;
  6216. QString device;
  6217. QVector<Channel*> channelMap;
  6218. unsigned int handle;@/
  6219. int error;
  6220. int channels;
  6221. bool ready;
  6222. QLibrary driver;
  6223. QVector<Units::Unit> unitMap;
  6224. @ Most of the interesting work associated with the |DAQ| class is handled in
  6225. the |measure()| method of |DAQImplementation|. This function will block until a
  6226. measurement is available. Once |buffer| is filled by |DAQmxBaseReadAnalogF64()|
  6227. that function returns and new |Measurement| objects are created based on the
  6228. information in the buffer. These measurements are sent to |Channel| objects
  6229. tracked by |channelMap|.
  6230. Up until version 1.0.7 there was a bug in this code that would prevent the code
  6231. from working when more than one channel is requested. This has been corrected.
  6232. With version 1.0.9, time measurement is moved out of the loop, reducing the
  6233. number of calls in cases of more than 1 measurement and ensuring that all
  6234. simultaneously obtained measurements have the same time stamp.
  6235. @<DAQ Implementation@>=
  6236. void DAQImplementation::measure()@t\2@>@/
  6237. @t\4@>{@/
  6238. int samplesRead = 0;
  6239. double buffer[channels];
  6240. error = read((unsigned int)(handle), (signed long)(1), (double)(10.0),@|
  6241. (unsigned long)(0), buffer, (unsigned long)(channels),@|
  6242. &samplesRead, (signed long)(0));@/
  6243. if(error)@/
  6244. @t\1@>{@/
  6245. ready = false;@t\2@>@/
  6246. }
  6247. else@/
  6248. {
  6249. if(samplesRead)@/
  6250. {
  6251. QTime time = QTime::currentTime();@/
  6252. for(int i = 0; i < samplesRead; i++)@/
  6253. {
  6254. for(int j = 0; j < channels; j++)@/
  6255. {
  6256. double measuredValue = buffer[j+(i*channels)];
  6257. Measurement measure(measuredValue, time,
  6258. unitMap[j]);
  6259. channelMap[@,j]->input(measure);
  6260. }
  6261. }
  6262. }
  6263. }
  6264. @t\4@>}
  6265. @ It was noted that |DAQmxBaseReadAnalogF64()| blocks until it is able to fill
  6266. the |buffer| passed to it. To prevent this behavior from having adverse effects
  6267. on the rest of the program, measure is called from a loop running in its own
  6268. thread of execution. When the thread is started, it begins its execution from
  6269. the |run()| method of |DAQImplementation| which overrides the |run()| method of
  6270. |QThread|. Here the priority of the thread is set in an attempt to cut down on
  6271. the variation in time between recorded measurements.
  6272. The while loop is controlled by |ready| which is set to |false| when there is an
  6273. error in collecting a measurement or when the user wants to exit the program. It
  6274. could also be set to |false| when the |DAQ| is reconfigured.
  6275. @<DAQ Implementation@>=
  6276. void DAQImplementation::run()
  6277. {
  6278. setPriority(QThread::TimeCriticalPriority);
  6279. while(ready)
  6280. {
  6281. measure();
  6282. }
  6283. }
  6284. @ When this loop exits, |DAQImplementation| emits a finished signal to indicate
  6285. that the thread is no longer running. This could be due to perfectly normal
  6286. conditions, but there could also be a problem that the user must be informed of.
  6287. That signal is connected to a function that checks for error conditions and
  6288. reports them if needed.
  6289. @<DAQ Implementation@>=
  6290. void DAQ::threadFinished()
  6291. {
  6292. if(imp->error)
  6293. {
  6294. @<Display DAQ Error@>@;
  6295. }
  6296. }
  6297. @ Errors are displayed with a |QMessageBox|. NIDAQmxBase provides the message
  6298. strings for these errors, but this should probably change as these error strings
  6299. are generally completely unrelated to what the problem really is. For example,
  6300. ``Error: -1'' usually means that the device is not plugged in.
  6301. ``Error: -200170'' usually means that \pn{} or another program using the device
  6302. did not exit cleanly. A table of replacement warning messages should be added to
  6303. this program.
  6304. \bigskip
  6305. \settabs 5 \columns
  6306. \+Error Code & NIDAQmxBase Text & & Likely Cause\cr
  6307. \+\hrulefill & \hrulefill & \hrulefill & \hrulefill & \hrulefill & \hrulefill\cr
  6308. \+ -1 & Not implemented for this device & & The device is not plugged in.\cr
  6309. \+ & type. & \cr
  6310. \+ -200170 & Physical channel specified & & The program did not exit cleanly\cr
  6311. \+ & does not exist on this device. & & or another program is using the\cr
  6312. \+ & Refer to the documentation for & & device.\cr
  6313. \+ & channels available on this device.\cr
  6314. \+ -1073807194 & {\it{(No text)}} & & The device has been unplugged.\cr
  6315. \medskip
  6316. \centerline{Table \secno: Error codes, text, and what they really mean.}
  6317. \bigskip
  6318. There are two calls to |DAQmxBaseGetExtendedErrorInfo()| to obtain the error
  6319. messages. The first is used just to obtain the length of the error string. That
  6320. length is then used to allocate space for the error message. The second call
  6321. fills that string. This isn'@q'@>t allowed by ISO \CPLUSPLUS/\nfnote{%
  6322. \CPLUSPLUS/Dynamic Arrays (Crowl and Austern, May 16, 2008)\par
  6323. \hbox{\indent\pdfURL{%
  6324. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2648.html}{%
  6325. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2648.html}}} but it
  6326. works with gcc. If this is a problem, the first call can be
  6327. removed and the buffer can be set large enough to fit the largest error message
  6328. that will be produced. Heap allocation could be used, but then we need to
  6329. remember to free the memory allocated to the string. Alternately, we can get rid
  6330. of \CEE/ style strings and write our own error messages. This would be the
  6331. preferred correction.
  6332. @<Display DAQ Error@>=
  6333. imp->ready = false;
  6334. QMessageBox warning;
  6335. warning.setStandardButtons(QMessageBox::Cancel);
  6336. warning.setIcon(QMessageBox::Warning);
  6337. warning.setText(QString(tr("Error: %1")).arg(imp->error));
  6338. unsigned long bytes = imp->errorInfo(NULL, 0);
  6339. char string[bytes];
  6340. imp->errorInfo(string, bytes);
  6341. warning.setInformativeText(QString(string));
  6342. warning.setWindowTitle(QString(PROGRAM_NAME));
  6343. warning.exec();
  6344. @ Starting the thread is almost as simple as ending it. The hardware is
  6345. instructed to begin taking measurements. If there is an error, this is handled.
  6346. Otherwise, the finished signal from |DAQImplementation| is connected to
  6347. |threadFinished()| and the new thread is started. The call to |imp->start()|
  6348. starts a new thread and passes control of that thread to |imp->run()|. The main
  6349. thread of execution returns without waiting for the new thread to do anything.
  6350. The call to |DAQmxBaseStartTask()| requires some time before the first
  6351. measurement is available. This is one of the reasons we start gathering
  6352. measurements before we really need them and continue to collect them until it is
  6353. time to exit the program.
  6354. @<DAQ Implementation@>=
  6355. void DAQ::start()
  6356. {
  6357. if(imp->ready)
  6358. {
  6359. imp->error = imp->startTask(imp->handle);
  6360. if(imp->error)
  6361. {
  6362. @<Display DAQ Error@>@;
  6363. }
  6364. else
  6365. {
  6366. connect(imp, SIGNAL(finished()), this, SLOT(threadFinished()));
  6367. imp->start();
  6368. }
  6369. }
  6370. }
  6371. void DAQ::stop()
  6372. {
  6373. if(imp->useBase)
  6374. {
  6375. imp->ready = @[false@];
  6376. imp->wait(ULONG_MAX);
  6377. imp->stopTask(imp->handle);
  6378. }
  6379. else
  6380. {
  6381. imp->ready = @[false@];
  6382. imp->error = imp->stopTask(imp->handle);
  6383. if(imp->error)
  6384. {
  6385. @<Display DAQ Error@>@;
  6386. }
  6387. imp->error = imp->clearTask(imp->handle);
  6388. if(imp->error)
  6389. {
  6390. @<Display DAQ Error@>@;
  6391. }
  6392. }
  6393. }
  6394. @ Setting up the DAQ begins by constructing a new |DAQ| object. The constructor
  6395. takes as its argument a string indicating the name of the device and will
  6396. typically be something like |"Dev1"|. This creates a new task which is required
  6397. for the setup that follows once a new |DAQ| is created.
  6398. @<DAQ Implementation@>=
  6399. DAQ::DAQ(QString device, const QString &driver) : imp(new DAQImplementation(driver))@/
  6400. @t\4\4@>{@/
  6401. imp->device = device;
  6402. imp->error = imp->createTask(device.toAscii().data(), &(imp->handle));
  6403. if(imp->error)@/
  6404. {
  6405. @<Display DAQ Error@>@;
  6406. }
  6407. else@/
  6408. @t\1@>{@/
  6409. imp->ready = true;@t\2@>@/
  6410. }@/
  6411. @t\4\4@>}
  6412. @ Once the |DAQ| is created, one or more channels can be added to that |DAQ|.
  6413. All |Channel| objects are created by the |DAQ| class and are managed by the
  6414. |DAQ| class. When a new channel is created, a pointer is passed back allowing
  6415. other classes to connect to the channel. Measurements cannot be read from the
  6416. |DAQ| directly. They must at some point pass through a channel.
  6417. @<DAQ Implementation@>=
  6418. Channel* DAQ::newChannel(int units, int thermocouple)
  6419. {
  6420. Channel *retval = new Channel();
  6421. imp->channelMap[imp->channels] = retval;
  6422. imp->unitMap[imp->channels] = (Units::Unit)units;
  6423. imp->channels++;
  6424. if(imp->ready)
  6425. {
  6426. if(imp->useBase)
  6427. {
  6428. imp->error = imp->createChannel(imp->handle,
  6429. QString("%1/ai%2").arg(imp->device).
  6430. arg(imp->channels - 1).
  6431. toAscii().data(),
  6432. "", (double)(-1.0), (double)(100.0),
  6433. (signed long)(units),
  6434. (signed long)(thermocouple),
  6435. (signed long)(10200), (double)(0),
  6436. "");
  6437. }
  6438. else
  6439. {
  6440. imp->error = imp->createChannel(imp->handle,
  6441. QString("%1/ai%2").arg(imp->device).
  6442. arg(imp->channels - 1).
  6443. toAscii().data(),
  6444. "", (double)(50.0), (double)(500.0),
  6445. (signed long)(units),
  6446. (signed long)(thermocouple),
  6447. (signed long)(10200), (double)(0),
  6448. "");
  6449. }
  6450. if(imp->error)
  6451. {
  6452. @<Display DAQ Error@>@;
  6453. }
  6454. }
  6455. return retval;
  6456. }
  6457. @ Once the channels are created, it is necessary to set the clock rate of the
  6458. DAQ. The clock rate chosen must be supported by the hardware. The clock rates
  6459. supported by the hardware may be altered by the number of channels in use.
  6460. The amount of time between measurements may vary slightly. A test configuration
  6461. at Wilson's Coffee \char'046~Tea used a 4Hz clock rate and provides measurements
  6462. every 251$\pm$1ms with 80\% of measurements spaced 251ms apart.
  6463. @<DAQ Implementation@>=
  6464. void DAQ::setClockRate(double Hz)
  6465. {
  6466. if(imp->ready)
  6467. {
  6468. imp->error = imp->setClock(imp->handle, "OnboardClock", Hz,
  6469. (signed long)(10280), (signed long)(10123),
  6470. (unsigned long long)(1));
  6471. if(imp->error)
  6472. {
  6473. @<Display DAQ Error@>@;
  6474. }
  6475. }
  6476. }
  6477. @ Before the program exits, the |DAQ| should be deleted. The destructor
  6478. instructs the measurement thread to stop, waits for it to finish, and resets the
  6479. device. If this is not done, an error would be issued the next time a program
  6480. attempted to use the device.
  6481. @<DAQ Implementation@>=
  6482. DAQ::~DAQ()@/
  6483. {
  6484. if(imp->useBase)
  6485. {
  6486. imp->resetDevice(imp->device.toAscii().data());
  6487. imp->clearTask(imp->handle);
  6488. }
  6489. else
  6490. {
  6491. if(imp->ready)
  6492. {
  6493. imp->ready = @[false@];
  6494. imp->wait(ULONG_MAX);
  6495. imp->stopTask(imp->handle);
  6496. imp->resetDevice(imp->device.toAscii().data());
  6497. imp->clearTask(imp->handle);
  6498. }
  6499. }
  6500. delete imp;
  6501. }
  6502. @ This just leaves the constructor and destructor for |DAQImplementation|. The
  6503. way the program is currently written, the number of channels available on the
  6504. |DAQ| is limited to 4. If a known larger number is required, the value here can
  6505. simply be set larger, however the best long term solution would be to modify
  6506. |newChannel()| to resize |channelMap| as more channels are added.
  6507. The constructor handles loading NI-DAQmxBase and preparing function pointers for
  6508. the symbols used in \pn{}.
  6509. @<DAQ Implementation@>=
  6510. DAQImplementation::DAQImplementation(const QString &driverinfo)
  6511. : QThread(NULL), channelMap(4), handle(0), error(0), channels(0), ready(false),
  6512. unitMap(4)@/
  6513. {
  6514. if(driverinfo == "nidaqmxbase")
  6515. {
  6516. useBase = true;
  6517. }
  6518. else
  6519. {
  6520. useBase = false;
  6521. }
  6522. if(useBase)
  6523. {
  6524. driver.setFileName("nidaqmxbase.framework/nidaqmxbase");
  6525. if(!driver.load())
  6526. {
  6527. driver.setFileName("nidaqmxbase");
  6528. if(!driver.load())
  6529. {
  6530. QMessageBox::critical(NULL, tr("Typica: Driver not found"),
  6531. tr("Failed to find nidaqmxbase. Please install it."));
  6532. QApplication::quit();
  6533. }
  6534. }
  6535. }
  6536. else
  6537. {
  6538. driver.setFileName("nicaiu");
  6539. if(!driver.load())
  6540. {
  6541. QMessageBox::critical(NULL, tr("Typica: Driver not found"),
  6542. tr("Failed to find nidaqmx. Please install it."));
  6543. QApplication::quit();
  6544. }
  6545. }
  6546. if(useBase)
  6547. {
  6548. if((createTask = (daqfp) driver.resolve("DAQmxBaseCreateTask")) == 0 || @|
  6549. (startTask = (daqfp) driver.resolve("DAQmxBaseStartTask")) == 0 || @|
  6550. (stopTask = (daqfp) driver.resolve("DAQmxBaseStopTask")) == 0 || @|
  6551. (clearTask = (daqfp) driver.resolve("DAQmxBaseClearTask")) == 0 || @|
  6552. (createChannel = (daqfp) driver.resolve("DAQmxBaseCreateAIThrmcplChan"))
  6553. == 0 || @|
  6554. (setClock = (daqfp) driver.resolve("DAQmxBaseCfgSampClkTiming")) ==
  6555. 0 || @|
  6556. (read = (daqfp) driver.resolve("DAQmxBaseReadAnalogF64")) == 0 || @|
  6557. (errorInfo = (daqfp) driver.resolve("DAQmxBaseGetExtendedErrorInfo")) ==
  6558. 0 || @|
  6559. (resetDevice = (daqfp) driver.resolve("DAQmxBaseResetDevice")) == 0)@/
  6560. {
  6561. waitForMeasurement = NULL;
  6562. QMessageBox::critical(NULL, tr("Typica: Link error"),
  6563. tr("Failed to link a required symbol in NI-DAQmxBase."));
  6564. QApplication::quit();
  6565. }
  6566. }
  6567. else
  6568. {
  6569. if((createTask = (daqfp)driver.resolve("DAQmxCreateTask")) == 0 || @|
  6570. (startTask = (daqfp)driver.resolve("DAQmxStartTask")) == 0 || @|
  6571. (stopTask = (daqfp)driver.resolve("DAQmxStopTask")) == 0 || @|
  6572. (clearTask = (daqfp)driver.resolve("DAQmxClearTask")) == 0 || @|
  6573. (createChannel = (daqfp)driver.resolve("DAQmxCreateAIThrmcplChan"))
  6574. == 0 || @|
  6575. (setClock = (daqfp)driver.resolve("DAQmxCfgSampClkTiming")) == 0 || @|
  6576. (read = (daqfp)driver.resolve("DAQmxReadAnalogF64")) == 0 || @|
  6577. (errorInfo = (daqfp)driver.resolve("DAQmxGetExtendedErrorInfo")) ==
  6578. 0 || @|
  6579. (resetDevice = (daqfp)driver.resolve("DAQmxResetDevice")) == 0 ||
  6580. (waitForMeasurement = (daqfp)driver.resolve("DAQmxWaitUntilTaskDone")) == 0)
  6581. {
  6582. QMessageBox::critical(NULL, tr("Typica: Link error"),
  6583. tr("Failed to link a required symbol in NI-DAQmx."));
  6584. QApplication::quit();
  6585. }
  6586. }
  6587. }
  6588. DAQImplementation::~DAQImplementation()
  6589. {
  6590. driver.unload();
  6591. }
  6592. @ When exposing the |DAQ| class to the scripting engine, we need to provide a
  6593. constructor that can be called from a script and we need a way to call
  6594. |DAQ::newChannel()|. Other methods that are useful when called from a script are
  6595. made available automatically with the |Q_INVOKABLE| macro, however this does not
  6596. work for methods such as |newChannel()| which return a pointer to a |Channel|
  6597. object.
  6598. @<Function prototypes for scripting@>=
  6599. QScriptValue constructDAQ(QScriptContext *context, QScriptEngine *engine);
  6600. QScriptValue DAQ_newChannel(QScriptContext *context, QScriptEngine *engine);
  6601. void setDAQProperties(QScriptValue value, QScriptEngine *engine);
  6602. @ These functions and the values from |Units::Unit| must be made available to
  6603. the host environment. The latter because this was widely used in configurations
  6604. before this enumeration was removed from the |DAQ| class. As these properties
  6605. must be available without an instance, the properties must be added here.
  6606. @<Set up the scripting engine@>=
  6607. constructor = engine->newFunction(constructDAQ);
  6608. value = engine->newQMetaObject(&DAQ::staticMetaObject, constructor);
  6609. value.setProperty("Fahrenheit", Units::Fahrenheit);
  6610. value.setProperty("Celsius", Units::Celsius);
  6611. value.setProperty("Kelvin", Units::Kelvin);
  6612. value.setProperty("Rankine", Units::Rankine);
  6613. engine->globalObject().setProperty("DAQ", value);
  6614. @ When creating a new |DAQ|, we make sure that it is owned by the script engine.
  6615. This is necessary to ensure that the destructor is called before \pn{} exits.
  6616. Just as the constructor requires an argument that specifies the device name, the
  6617. constructor available from a script also requires this argument.
  6618. @<Functions for scripting@>=
  6619. QScriptValue constructDAQ(QScriptContext *context, QScriptEngine *engine)
  6620. {
  6621. QScriptValue object;
  6622. if(context->argumentCount() == 1)
  6623. {
  6624. object = engine->newQObject(new DAQ(argument<QString>(0, context)),
  6625. QScriptEngine::ScriptOwnership);
  6626. setDAQProperties(object, engine);
  6627. }
  6628. else if(context->argumentCount() == 2)
  6629. {
  6630. object = engine->newQObject(new DAQ(argument<QString>(0, context),
  6631. argument<QString>(1, context)),
  6632. QScriptEngine::ScriptOwnership);
  6633. setDAQProperties(object, engine);
  6634. }
  6635. else
  6636. {
  6637. context->throwError("Incorrect number of arguments passed to DAQ"@|
  6638. "constructor. The DAQ constructor takes one"@|
  6639. "string as an argument specifying a device name."@|
  6640. "Example: Dev1");
  6641. }
  6642. return object;
  6643. }
  6644. @ As |DAQ| inherits |QObject|, we add the |newChannel()| property after adding
  6645. any |QObject| properties.
  6646. @<Functions for scripting@>=
  6647. void setDAQProperties(QScriptValue value, QScriptEngine *engine)
  6648. {
  6649. setQObjectProperties(value, engine);
  6650. value.setProperty("newChannel", engine->newFunction(DAQ_newChannel));
  6651. }
  6652. @ The |newChannel()| method method also requires that two arguments are provided
  6653. by the script.
  6654. @<Functions for scripting@>=
  6655. QScriptValue DAQ_newChannel(QScriptContext *context, QScriptEngine *engine)
  6656. {
  6657. DAQ *self = getself<@[DAQ *@]>(context);
  6658. QScriptValue object;
  6659. if(self)
  6660. {
  6661. object =
  6662. engine->newQObject(self->newChannel(argument<int>(0, context),@|
  6663. argument<int>(1, context)));
  6664. setChannelProperties(object, engine);
  6665. }
  6666. return object;
  6667. }
  6668. @ Sometimes it can be useful to test other parts of the program (for example,
  6669. when developing new scripts) when the DAQ hardware is not available. In these
  6670. cases, it is possible to temporarily use the |FakeDAQ| class. This class mimics
  6671. the |DAQ| class, but just makes up the measurements sent to the rest of the
  6672. program.
  6673. @<Class declarations@>=
  6674. class FakeDAQImplementation : public QThread@/
  6675. {@/
  6676. Q_OBJECT@;
  6677. public:@/
  6678. FakeDAQImplementation();
  6679. ~FakeDAQImplementation();
  6680. void run();
  6681. void measure();
  6682. QVector<Channel *> channelMap;
  6683. int channels;
  6684. bool ready;
  6685. double clockRate;
  6686. };@/
  6687. class FakeDAQ : public QObject@/
  6688. {@/
  6689. Q_OBJECT@;
  6690. FakeDAQImplementation *imp;
  6691. public:@/
  6692. FakeDAQ(QString device);
  6693. ~FakeDAQ();
  6694. Channel *newChannel(int units, int thermocouple);@/
  6695. @[Q_INVOKABLE@,@, void@]@, setClockRate(double Hz);@t\2\2@>@/
  6696. @[Q_INVOKABLE@,@, void@]@, start();@t\2\2@>@/
  6697. };
  6698. @ Just as in the |DAQ| class, most of the interesting stuff happens in
  6699. |measure()|. For each invokation of the method, we sleep for some amount of time
  6700. based on the clock rate then create a |Measurement| object at random for each
  6701. |Channel| that has been created.
  6702. @<FakeDAQ Implementation@>=
  6703. void FakeDAQImplementation::measure()
  6704. {
  6705. msleep((int)(1000/clockRate));
  6706. QTime time = QTime::currentTime();
  6707. for(int i = 0; i < channels; i++)
  6708. {
  6709. Measurement measure(qrand() % 500, time);
  6710. channelMap[i]->input(measure);
  6711. }
  6712. }
  6713. @ To call |measure|, we need to flesh out the rest of |FakeDAQImplementation|.
  6714. @<FakeDAQ Implementation@>=
  6715. void FakeDAQImplementation::run()
  6716. {
  6717. setPriority(QThread::TimeCriticalPriority);
  6718. while(ready)
  6719. {
  6720. measure();
  6721. }
  6722. }
  6723. FakeDAQImplementation::FakeDAQImplementation() : QThread(NULL), channelMap(4),
  6724. channels(0), ready(false), clockRate(1)@/
  6725. {
  6726. /* Nothing has to be done here. */
  6727. }
  6728. FakeDAQImplementation::~FakeDAQImplementation()
  6729. {
  6730. /* Nothing has to be done here. */
  6731. }
  6732. @ Next we need an implementation for the |FakeDAQ| class. This is simplified by
  6733. the fact that we are just using a random number generator to generate
  6734. measurements rather than special hardware for obtaining measurements.
  6735. @<FakeDAQ Implementation@>=
  6736. void FakeDAQ::start()
  6737. {
  6738. if(imp->ready)
  6739. {
  6740. imp->start();
  6741. }
  6742. }@#
  6743. FakeDAQ::FakeDAQ(QString) : imp(new FakeDAQImplementation())@t\2\2@>@/
  6744. {@t\1@>@/
  6745. imp->ready = true;@t\2@>@/
  6746. }@#
  6747. Channel* FakeDAQ::newChannel(int, int)
  6748. {
  6749. Channel *retval;
  6750. if(imp->ready)
  6751. {
  6752. retval = new Channel();
  6753. imp->channelMap[imp->channels] = retval;
  6754. imp->channels++;
  6755. }
  6756. else
  6757. {
  6758. return NULL;
  6759. }
  6760. return retval;
  6761. }
  6762. void FakeDAQ::setClockRate(double Hz)
  6763. {
  6764. if(imp->ready)
  6765. {
  6766. imp->clockRate = Hz;
  6767. }
  6768. }@#
  6769. FakeDAQ::~FakeDAQ()@t\2\2@>@/
  6770. {@t\1@>@/
  6771. imp->ready = false;
  6772. imp->wait(ULONG_MAX);
  6773. delete imp;@t\2@>@/
  6774. }
  6775. @ As the entire purpose of the |FakeDAQ| class is for testing purposes from
  6776. within the scripting engine, we need to make it available to the scripting
  6777. engine. This is done in a manner very similar to how the |DAQ| class is handled.
  6778. @<Function prototypes for scripting@>=
  6779. QScriptValue constructFakeDAQ(QScriptContext *context, QScriptEngine *engine);
  6780. QScriptValue FakeDAQ_newChannel(QScriptContext *context, QScriptEngine *engine);
  6781. void setFakeDAQProperties(QScriptValue value, QScriptEngine *engine);
  6782. @ The scripting engine is informed of the constructor.
  6783. @<Set up the scripting engine@>=
  6784. constructor = engine->newFunction(constructFakeDAQ);
  6785. value = engine->newQMetaObject(&FakeDAQ::staticMetaObject, constructor);
  6786. engine->globalObject().setProperty("FakeDAQ", value);
  6787. @ The constructor sets a property to allow calling |newChannel()| on a |FakeDAQ|
  6788. created from a script.
  6789. @<Functions for scripting@>=
  6790. QScriptValue constructFakeDAQ(QScriptContext *context,
  6791. QScriptEngine *engine)
  6792. {
  6793. QScriptValue object;
  6794. if(context->argumentCount() == 1)
  6795. {
  6796. object =
  6797. engine->newQObject(new FakeDAQ(argument<QString>(0, context)),
  6798. QScriptEngine::ScriptOwnership);
  6799. setFakeDAQProperties(object, engine);
  6800. }
  6801. else
  6802. {
  6803. context->throwError("Incorrect number of arguments passed to DAQ"@|
  6804. "constructor. The DAQ constructor takes one"@|
  6805. "string as an argument specifying a device name."@|
  6806. "Example: Dev1");
  6807. }
  6808. return object;
  6809. }
  6810. void setFakeDAQProperties(QScriptValue value, QScriptEngine *engine)
  6811. {
  6812. setQObjectProperties(value, engine);
  6813. value.setProperty("newChannel", engine->newFunction(FakeDAQ_newChannel));
  6814. }
  6815. QScriptValue FakeDAQ_newChannel(QScriptContext *context, QScriptEngine *engine)
  6816. {
  6817. FakeDAQ *self = getself<@[FakeDAQ *@]>(context);
  6818. QScriptValue object;
  6819. if(self)
  6820. {
  6821. object =
  6822. engine->newQObject(self->newChannel(argument<int>(0, context),@|
  6823. argument<int>(1, context)));
  6824. setChannelProperties(object, engine);
  6825. }
  6826. return object;
  6827. }
  6828. @* The Channel class.
  6829. \noindent |Channel| is a simple class. It is a subclass of |QObject| so it can
  6830. use Qt'@q'@>s signals and slots mechanism. Any object that is interested in
  6831. measurements from a channel can connect to the |newData| signal the channel
  6832. emits. Any number of objects can make this connection and each will receive a
  6833. copy of the measurement.
  6834. |Channel| objects should only be created by the |DAQ| class.
  6835. @<Class declarations@>=
  6836. class Channel : public QObject@;@/
  6837. {@t\1@>@/
  6838. Q_OBJECT@/
  6839. public:@;
  6840. Channel();
  6841. ~Channel();@/
  6842. @t\4@>public slots@t\kern-3pt@>:@;
  6843. void input(Measurement measurement);@/
  6844. signals:@;
  6845. void newData(Measurement);@t\2@>@/
  6846. };
  6847. @ The implementation of this class is trivial.
  6848. @<Channel Implementation@>=
  6849. Channel::Channel() : QObject(NULL)@/
  6850. {
  6851. /* Nothing has to be done here. */
  6852. }
  6853. Channel::~Channel()
  6854. {
  6855. /* Nothing has to be done here. */
  6856. }
  6857. void Channel::input(Measurement measurement)
  6858. {
  6859. emit newData(measurement);
  6860. }
  6861. @ A function is provided for use when a channel is created by a DAQ from a
  6862. script.
  6863. @<Function prototypes for scripting@>=
  6864. void setChannelProperties(QScriptValue value, QScriptEngine *engine);
  6865. @ The implementation is trivial.
  6866. @<Functions for scripting@>=
  6867. void setChannelProperties(QScriptValue value, QScriptEngine *engine)
  6868. {
  6869. setQObjectProperties(value, engine);
  6870. }
  6871. @* Calibration and Unit Conversion.
  6872. \noindent One of the planned features for \pn{} is support for hardware that
  6873. collects non-temperature measurements. This is frequently handled with analog
  6874. voltage signals which are proportional to some range in a meaningful unit. Some
  6875. hardware also requires calibration in software. In many cases both of these can
  6876. be handled at the same time with a single mapping in the form:
  6877. $$f(x) = L_1 + (x - L_2){U_1 - L_1\over{U_2 - L_2}}$$
  6878. \noindent where $L_1$ is the logical lower bound, $L_2$ is the measured lower
  6879. bound, $U_1$ is the logical upper bound, $U_2$ is the measured upper bound, and
  6880. $x$ is the value we wish to map from the range $\lbrack L_2, U_2 \rbrack$ to
  6881. the range $\lbrack L_1, U_1 \rbrack$.
  6882. Some use cases require a closed range but others require that this constraint
  6883. is loosened to allow extrapolation. Both are provided by this class.
  6884. Starting in \pn{} 1.6 this class has both the |measurement| and the
  6885. |newData| signals. This allows a |LinearCalibrator| to be treated like a
  6886. |Channel| when used with a |DataqSdkDevice|.
  6887. @<Class declarations@>=
  6888. class LinearCalibrator : public QObject@/
  6889. {@/
  6890. @[Q_OBJECT@]@;
  6891. @[Q_PROPERTY(double measuredLower READ measuredLower
  6892. WRITE setMeasuredLower)@]@;
  6893. @[Q_PROPERTY(double measuredUpper READ measuredUpper
  6894. WRITE setMeasuredUpper)@]@;
  6895. @[Q_PROPERTY(double mappedLower READ mappedLower WRITE setMappedLower)@]@;
  6896. @[Q_PROPERTY(double mappedUpper READ mappedUpper WRITE setMappedUpper)@]@;
  6897. @[Q_PROPERTY(bool closedRange READ isClosedRange WRITE setClosedRange)@]@;
  6898. @[Q_PROPERTY(double sensitivity READ sensitivity WRITE setSensitivity)@]@;
  6899. public:@/
  6900. LinearCalibrator(QObject *parent = NULL);
  6901. double measuredLower();
  6902. double measuredUpper();
  6903. double mappedLower();
  6904. double mappedUpper();
  6905. bool isClosedRange();
  6906. double sensitivity();
  6907. @t\4@>@[public slots@t\kern-3pt@>:@]@;
  6908. void setMeasuredLower(double lower);
  6909. void setMeasuredUpper(double upper);
  6910. void setMappedLower(double lower);
  6911. void setMappedUpper(double upper);
  6912. void setClosedRange(bool closed);
  6913. void setSensitivity(double sensitivity);
  6914. Measurement newMeasurement(Measurement measure);
  6915. @t\4@>@[signals:@]@;
  6916. void measurement(Measurement measure);
  6917. void newData(Measurement measure);
  6918. private:@/
  6919. double Lo1;
  6920. double Lo2;
  6921. double Up1;
  6922. double Up2;
  6923. double sensitivitySetting;
  6924. bool clamp;
  6925. };
  6926. @ When the measured range and the mapped range are identical and the range is
  6927. open, we have an identity mapping. This is the default state in a newly
  6928. constructed |LinearCalibrator| which should quickly be changed.
  6929. @<LinearCalibrator Implementation@>=
  6930. LinearCalibrator::LinearCalibrator(QObject *parent) :
  6931. QObject(parent), Lo1(0), Lo2(0), Up1(1), Up2(1), sensitivitySetting(0.0), clamp(false)@/
  6932. {
  6933. connect(this, SIGNAL(measurement(Measurement)), this, SIGNAL(newData(Measurement)));
  6934. }
  6935. @ The functional portion of the class is in the |newMeasurement()| slot. This
  6936. will receive measurements as they come in and emit a |measurement()| signal for
  6937. each with the calibration and unit adjustment performed.
  6938. This method also handles any rounding needed if there has been a call to
  6939. |setSensitivity()|.
  6940. @<LinearCalibrator Implementation@>=
  6941. Measurement LinearCalibrator::newMeasurement(Measurement measure)
  6942. {
  6943. double outval = Lo1 + (measure.temperature() - Lo2) * (Up1 - Lo1)/(Up2 - Lo2);
  6944. if(clamp)
  6945. {
  6946. if(outval < Lo1)
  6947. {
  6948. outval = Lo1;
  6949. }
  6950. else if(outval > Up1)
  6951. {
  6952. outval = Up1;
  6953. }
  6954. }
  6955. if(sensitivitySetting >= 0.05)
  6956. {
  6957. int temp = qRound(outval/sensitivitySetting);
  6958. outval = temp * sensitivitySetting;
  6959. }
  6960. Measurement adjusted(outval, measure.time(), measure.scale());
  6961. emit measurement(adjusted);
  6962. return adjusted;
  6963. }
  6964. @ The rest of the class consists of trivial accessor methods.
  6965. @<LinearCalibrator Implementation@>=
  6966. double LinearCalibrator::measuredLower()
  6967. {
  6968. return Lo2;
  6969. }
  6970. double LinearCalibrator::measuredUpper()
  6971. {
  6972. return Up2;
  6973. }
  6974. double LinearCalibrator::mappedLower()
  6975. {
  6976. return Lo1;
  6977. }
  6978. double LinearCalibrator::mappedUpper()
  6979. {
  6980. return Up1;
  6981. }
  6982. bool LinearCalibrator::isClosedRange()
  6983. {
  6984. return clamp;
  6985. }
  6986. void LinearCalibrator::setMeasuredLower(double lower)
  6987. {
  6988. Lo2 = lower;
  6989. }
  6990. void LinearCalibrator::setMeasuredUpper(double upper)
  6991. {
  6992. Up2 = upper;
  6993. }
  6994. void LinearCalibrator::setMappedLower(double lower)
  6995. {
  6996. Lo1 = lower;
  6997. }
  6998. void LinearCalibrator::setMappedUpper(double upper)
  6999. {
  7000. Up1 = upper;
  7001. }
  7002. void LinearCalibrator::setClosedRange(bool closed)
  7003. {
  7004. clamp = closed;
  7005. }
  7006. void LinearCalibrator::setSensitivity(double sensitivity)
  7007. {
  7008. sensitivitySetting = sensitivity;
  7009. }
  7010. double LinearCalibrator::sensitivity()
  7011. {
  7012. return sensitivitySetting;
  7013. }
  7014. @ Finally, we make this class available to the scripting engine. Two functions
  7015. are required for this.
  7016. @<Function prototypes for scripting@>=
  7017. QScriptValue constructLinearCalibrator(QScriptContext *context,
  7018. QScriptEngine *engine);
  7019. void setLinearCalibratorProperties(QScriptValue value, QScriptEngine *engine);
  7020. @ The scripting engine is informed of the constructor.
  7021. @<Set up the scripting engine@>=
  7022. constructor = engine->newFunction(constructLinearCalibrator);
  7023. value = engine->newQMetaObject(&LinearCalibrator::staticMetaObject,
  7024. constructor);
  7025. engine->globalObject().setProperty("LinearCalibrator", value);
  7026. @ The implementation of these functions is typical for this application.
  7027. @<Functions for scripting@>=
  7028. QScriptValue constructLinearCalibrator(QScriptContext *, QScriptEngine *engine)
  7029. {
  7030. QScriptValue object = engine->newQObject(new LinearCalibrator(NULL));
  7031. setLinearCalibratorProperties(object, engine);
  7032. return object;
  7033. }
  7034. void setLinearCalibratorProperties(QScriptValue value, QScriptEngine *engine)
  7035. {
  7036. setQObjectProperties(value, engine);
  7037. }
  7038. @* Linear Spline Interpolation.
  7039. \noindent While linear interpolation is adequate for many purposes, it fails
  7040. when a nonlinear mapping is required. The primary use case is to calibrate
  7041. multiple coffee roasters so that roast profiles can be shared among coffee
  7042. roasters with sufficiently similar heat transfer characteristics even if
  7043. differences in the measurement hardware result in different measured values.
  7044. By recording measured values at several points known to be equivalent due to
  7045. easily observable physical changes in the coffee it is possible to use linear
  7046. spline interpolation to produce a data series that approximates on one machine
  7047. the measurements that would have been produced at another. Acceptable results
  7048. may be available with surprisingly few data points.
  7049. It was originally suspected that cubic spline interpolation would produce a
  7050. more accurate mapping, but testing with linear spline interpolation produced
  7051. results good enough that more complex mappings were not needed. Cubic spline
  7052. interpolation may still be implemented in the future, but it is a low
  7053. priority.
  7054. @<Class declarations@>=
  7055. class LinearSplineInterpolator : public QObject@/
  7056. {@/
  7057. @[Q_OBJECT@]@;@/
  7058. public:@/
  7059. LinearSplineInterpolator(QObject *parent = NULL);
  7060. @[Q_INVOKABLE@,@, void@]@, add_pair(double source, double destination);@t\2\2@>@/
  7061. @[public slots@]:@/
  7062. Measurement newMeasurement(Measurement measure);
  7063. @[signals@]:@/
  7064. void newData(Measurement measure);
  7065. private:@/
  7066. void make_interpolators();
  7067. QMap<double, double> *pairs;
  7068. QList<LinearCalibrator *> *interpolators;@/
  7069. };
  7070. @ We take advantage of the fact that iterating over a QMap always returns
  7071. entries in key order. When new measurement pairs are specified, the
  7072. interpolators are regenerated. There is significant room for performance
  7073. improvement.
  7074. @<LinearSplineInterpolator Implementation@>=
  7075. void LinearSplineInterpolator::add_pair(double source, double destination)
  7076. {
  7077. pairs->insert(source, destination);
  7078. make_interpolators();
  7079. }
  7080. void LinearSplineInterpolator::make_interpolators()
  7081. {
  7082. if(pairs->size() > 1)
  7083. {
  7084. while(interpolators->size() > 0)
  7085. {
  7086. LinearCalibrator *removed = interpolators->takeFirst();
  7087. removed->deleteLater();
  7088. }
  7089. QMap<double, double>::const_iterator i = pairs->constBegin();
  7090. QMap<double, double>::const_iterator j = i + 1;
  7091. while(j != pairs->constEnd())
  7092. {
  7093. LinearCalibrator *segment = new LinearCalibrator();
  7094. segment->setMeasuredLower(i.key());
  7095. segment->setMappedLower(i.value());
  7096. segment->setMeasuredUpper(j.key());
  7097. segment->setMappedUpper(j.value());
  7098. segment->setClosedRange(false);
  7099. interpolators->append(segment);
  7100. connect(segment, SIGNAL(measurement(Measurement)), this, SIGNAL(newData(Measurement)));
  7101. i++;
  7102. j++;
  7103. }
  7104. }
  7105. }
  7106. LinearSplineInterpolator::LinearSplineInterpolator(QObject *parent) :
  7107. QObject(parent), pairs(new QMap<double, double>),
  7108. interpolators(new QList<LinearCalibrator *>)
  7109. {
  7110. /* Nothing needs to be done here. */
  7111. }
  7112. Measurement LinearSplineInterpolator::newMeasurement(Measurement measure)
  7113. {
  7114. QMap<double, double>::const_iterator i = pairs->constBegin();
  7115. int index = -1;
  7116. while(i != pairs->constEnd())
  7117. {
  7118. if(measure.temperature() <= i.key())
  7119. {
  7120. break;
  7121. }
  7122. i++;
  7123. index++;
  7124. }
  7125. if(index < 0)
  7126. {
  7127. index = 0;
  7128. }
  7129. if(index >= interpolators->size())
  7130. {
  7131. index = interpolators->size() - 1;
  7132. }
  7133. if(interpolators->at(index) != NULL)
  7134. {
  7135. return interpolators->at(index)->newMeasurement(measure);
  7136. }
  7137. return Measurement();
  7138. }
  7139. @ This is exposed to the scripting environment as usual.
  7140. @<Function prototypes for scripting@>=
  7141. QScriptValue constructLinearSplineInterpolator(QScriptContext *context, QScriptEngine *engine);
  7142. void setLinearSplineInterpolatorProperties(QScriptValue value, QScriptEngine *engine);
  7143. @ As usual.
  7144. @<Set up the scripting engine@>=
  7145. constructor = engine->newFunction(constructLinearSplineInterpolator);
  7146. value = engine->newQMetaObject(&LinearSplineInterpolator::staticMetaObject, constructor);
  7147. engine->globalObject().setProperty("LinearSplineInterpolator", value);
  7148. @ And again as usual.
  7149. @<Functions for scripting@>=
  7150. QScriptValue constructLinearSplineInterpolator(QScriptContext *, QScriptEngine *engine)
  7151. {
  7152. QScriptValue object = engine->newQObject(new LinearSplineInterpolator(NULL));
  7153. setLinearSplineInterpolatorProperties(object, engine);
  7154. return object;
  7155. }
  7156. void setLinearSplineInterpolatorProperties(QScriptValue value, QScriptEngine *engine)
  7157. {
  7158. setQObjectProperties(value, engine);
  7159. }
  7160. @* The TemperatureDisplay class.
  7161. Now that measurements have been generated by the |DAQ| and passed to a
  7162. |Channel|, any object that is interested in these measurements can connect to
  7163. the channel and use the measurements it sends out. So far, the time on each
  7164. measurement is the time at which it was collected. Unfortunately, this is often
  7165. not what we want. It is more useful to have the time relative to some other
  7166. point in time such as the start of the batch.
  7167. Until the measurement time is adjusted, the measurements are really only useful
  7168. to classes that do not care about the measurement time. The |TemperatureDisplay|
  7169. class is such a class. It receives measurements and displays the most recently
  7170. measured temperature.
  7171. This is a specialization of |QLCDNumber|.
  7172. @<Class declarations@>=
  7173. class TemperatureDisplay : public QLCDNumber@/
  7174. {@t\1@>@/
  7175. Q_OBJECT@;
  7176. int unit;
  7177. bool r;
  7178. public:@/
  7179. TemperatureDisplay(QWidget *parent = NULL);
  7180. ~TemperatureDisplay();@/
  7181. @t\4@>public slots@t\kern-3pt@>:@/
  7182. void setValue(Measurement temperature);
  7183. void invalidate();
  7184. void setDisplayUnits(Units::Unit scale);
  7185. void setRelativeMode(bool relative);@t\2@>@/
  7186. };
  7187. @ Starting in version 1.6 this widget is also used for displaying a relative
  7188. temperature value in the form of the rate of change indicator. To calculate
  7189. this correctly in Celsius or Kelvin we must have a way to bypass the
  7190. conversions for absolute measures.
  7191. @<TemperatureDisplay Implementation@>=
  7192. void TemperatureDisplay::setRelativeMode(bool relative)
  7193. {
  7194. r = relative;
  7195. }
  7196. @ Displaying a temperature is a simple matter of taking the temperature
  7197. component from the measurement and converting it to a string. Presently, this
  7198. code assumes that the measurements are in degrees Fahrenheit. If the code
  7199. becomes smarter about measurement units it might be a good idea to change this.
  7200. |QLCDNumber| is capable of displaying more than just numbers, so the call to
  7201. display takes a string which in this case consists of the temperature to the
  7202. $1\over100$th of a degree and might be followed by '@q'@> which will be
  7203. converted to $^\circ$ and the letter F, C, or r to indicate the unit. This
  7204. class should be mofified to allow a user specified precision.
  7205. @<TemperatureDisplay Implementation@>=
  7206. void TemperatureDisplay::setValue(Measurement temperature)
  7207. {
  7208. QString number;
  7209. switch(unit)
  7210. {
  7211. case Units::Fahrenheit:
  7212. display(QString("%1'F").
  7213. arg(number.setNum(temperature.toFahrenheit().temperature(), 'f',
  7214. 2)));
  7215. break;
  7216. case Units::Celsius:
  7217. if(!r) {
  7218. display(QString("%1'C").
  7219. arg(number.setNum(temperature.toCelsius().temperature(), 'f',
  7220. 2)));
  7221. } else {
  7222. number.setNum(temperature.temperature() * (5.0/9.0), 'f', 2);
  7223. display(QString("%1'C").arg(number));
  7224. }
  7225. break;
  7226. case Units::Kelvin:
  7227. if(!r) {
  7228. display(QString("%1").
  7229. arg(number.setNum(temperature.toKelvin().temperature(), 'f',
  7230. 2)));
  7231. } else {
  7232. number.setNum(temperature.temperature() * (5.0/9.0), 'f', 2);
  7233. display(QString("%1").arg(number));
  7234. }
  7235. break;
  7236. case Units::Rankine:
  7237. display(QString("%1'r").
  7238. arg(number.setNum(temperature.toRankine().temperature(), 'f',
  7239. 2)));
  7240. break;
  7241. case Units::Unitless:
  7242. display(QString("%1").arg(number.setNum(temperature.temperature(), 'f', 0)));
  7243. break;
  7244. default:
  7245. switch(temperature.scale())
  7246. {
  7247. case Units::Fahrenheit:
  7248. display(QString("%1'F").
  7249. arg(number.setNum(temperature.temperature(), 'f', 2)));
  7250. break;
  7251. case Units::Celsius:
  7252. display(QString("%1'C").
  7253. arg(number.setNum(temperature.temperature(), 'f', 2)));
  7254. break;
  7255. case Units::Kelvin:
  7256. display(QString("%1").
  7257. arg(number.setNum(temperature.temperature(), 'f', 2)));
  7258. break;
  7259. case Units::Rankine:
  7260. display(QString("%1'r").
  7261. arg(number.setNum(temperature.temperature(), 'f', 2)));
  7262. break;
  7263. case Units::Unitless:
  7264. display(QString("%1").arg(number.setNum(temperature.temperature(), 'f', 0)));
  7265. break;
  7266. default:
  7267. qDebug() << "Warning: Attempting to convert a non-temperature unit to a temperature unit";
  7268. break;
  7269. }
  7270. break;
  7271. }
  7272. }
  7273. @ Before measurements are displayed, we set a more sensible default display
  7274. style and an initial string. These defaults can all be overridden with calls to
  7275. the usual |QLCDNumber| methods.
  7276. \medskip
  7277. \resizebox*{6.3in}{!}{\includegraphics{QLCDNumber.png}}
  7278. \smallskip
  7279. \centerline{Figure \secno: Outline (Qt default) and Filled |QLCDNumber| Example}
  7280. \medskip
  7281. @<TemperatureDisplay Implementation@>=
  7282. TemperatureDisplay::TemperatureDisplay(QWidget *parent) :
  7283. QLCDNumber(8, parent), unit(Units::Fahrenheit), r(false)@/
  7284. {
  7285. setSegmentStyle(Filled);
  7286. display("---.--'F");
  7287. }
  7288. @ While it is not currently used, it would be good to allow an error state to
  7289. be easily discernible from a very stable temperature. Currently, if an error
  7290. occurs that results in the measurement thread exiting, no new measurements will
  7291. be generated and the temperature display will continue to read the most recent
  7292. measured value. If an error signal were emitted, it could be connected to the
  7293. following code to change the display to reflect the fact that the current
  7294. temperature is unknown.
  7295. @<TemperatureDisplay Implementation@>=
  7296. void TemperatureDisplay::invalidate()
  7297. {
  7298. display("---.--'F");
  7299. }
  7300. @ \pn{} supports the display of multiple types of unit. Typically, we use the
  7301. Auto scale which will cause |TemperatureDisplay| objects to display measurements
  7302. in whichever scale the measurement is associated with. Alternately, we can fix
  7303. the scale to a different supported scale and convert measurements to that scale
  7304. prior to display.
  7305. @<TemperatureDisplay Implementation@>=
  7306. void TemperatureDisplay::setDisplayUnits(Units::Unit scale)
  7307. {
  7308. unit = scale;
  7309. }
  7310. @ All that is left to deal with is the empty destructor.
  7311. @<TemperatureDisplay Implementation@>=
  7312. TemperatureDisplay::~TemperatureDisplay()
  7313. {
  7314. /* Nothing has to be done here. */
  7315. }
  7316. @ To use a |TemperatureDisplay| from a script, we need a function to pass a new
  7317. object to the scripting engine.
  7318. @<Function prototypes for scripting@>=
  7319. QScriptValue constructTemperatureDisplay(QScriptContext *context,
  7320. QScriptEngine *engine);
  7321. void setTemperatureDisplayProperties(QScriptValue value, QScriptEngine *engine);
  7322. QScriptValue TemperatureDisplay_setDisplayUnits(QScriptContext *context,
  7323. QScriptEngine *engine);
  7324. @ The scripting engine must be informed of this function.
  7325. @<Set up the scripting engine@>=
  7326. constructor = engine->newFunction(constructTemperatureDisplay);
  7327. value = engine->newQMetaObject(&TemperatureDisplay::staticMetaObject,
  7328. constructor);
  7329. engine->globalObject().setProperty("TemperatureDisplay", value);
  7330. @ The constructor is trivial.
  7331. @<Functions for scripting@>=
  7332. QScriptValue constructTemperatureDisplay(QScriptContext *,
  7333. QScriptEngine *engine)
  7334. {
  7335. QScriptValue object = engine->newQObject(new TemperatureDisplay);
  7336. setTemperatureDisplayProperties(object, engine);
  7337. return object;
  7338. }
  7339. void setTemperatureDisplayProperties(QScriptValue value, QScriptEngine *engine)
  7340. {
  7341. setQLCDNumberProperties(value, engine);
  7342. value.setProperty("setDisplayUnits",
  7343. engine->newFunction(TemperatureDisplay_setDisplayUnits));
  7344. }
  7345. @ There seems to be a bad interaction when enumerated value types as used as
  7346. the argument to slot methods called through QtScript. Script code that attempts
  7347. to make use of the enumeration appears to get the value without any type
  7348. information. When attempting to use that value as an argument the meta-object
  7349. system cannot find an appropriate match and the script just hangs silently.
  7350. The solution is to wrap such methods in the script bindings and explicitly cast
  7351. the argument value to the enumerated type. This looks stupid but it works.
  7352. @<Functions for scripting@>=
  7353. QScriptValue TemperatureDisplay_setDisplayUnits(QScriptContext *context, QScriptEngine *)
  7354. {
  7355. TemperatureDisplay *self = getself<@[TemperatureDisplay *@]>(context);
  7356. self->setDisplayUnits((Units::Unit)argument<int>(0, context));
  7357. return QScriptValue();
  7358. }
  7359. @* The MeasurementTimeOffset class.
  7360. When a |DAQ| object creates a |Measurement| object, the time component is a
  7361. system time. In most cases, the system time is not interesting and a more useful
  7362. time would be relative to the start of a process. This class should be used as a
  7363. filter, taking measurements with a system time stamp and producing measurements
  7364. with a relative time.
  7365. @<Class declarations@>=
  7366. class MeasurementTimeOffset : public QObject@/
  7367. {@t\1@>@/
  7368. Q_OBJECT@;
  7369. QTime epoch;
  7370. QTime previous;
  7371. bool hasPrevious;@/
  7372. public:@;
  7373. MeasurementTimeOffset(QTime zero);
  7374. QTime zeroTime();@/
  7375. @t\4@>public slots@t\kern-3pt@>:@;
  7376. void newMeasurement(Measurement measure);
  7377. void setZeroTime(QTime zero);
  7378. signals:@;
  7379. void measurement(Measurement measure);@t\2@>@/
  7380. }@t\kern-3pt@>;
  7381. @ The interesting part of this class is the function which takes a measurement
  7382. with a system time and produces a new measurement with a time relative to some
  7383. start time.
  7384. When using this class, it is possible that a measurement will arrive with a time
  7385. slightly before a newly chosen epoch. In such a case we do not want to simply
  7386. subtract the epoch from the measurement time as other classes will interpret
  7387. this incorrectly as a measurement time slightly less than 1 hour. This means
  7388. that we need to check if the measurement time is before the epoch. If it is, we
  7389. consider it to have been generated at the epoch rather than before. Aren't race
  7390. conditions fun?
  7391. Additionally, since we're only getting time of day information, some special
  7392. handling must be done for time series that cross the boundary between days. We
  7393. should never get measurements out of order, so keeping a record of the previous
  7394. measurement and verifying that the new measurement comes after it is sufficient.
  7395. @<MeasurementTimeOffset Implementation@>=
  7396. void MeasurementTimeOffset::newMeasurement(Measurement measure)@t\2\2@>@/
  7397. {@t\1@>@/
  7398. if(measure.time() < epoch)@/
  7399. {
  7400. if(hasPrevious)@/
  7401. {
  7402. QTime jitBase(epoch.hour() - 1, epoch.minute(), epoch.second(),
  7403. epoch.msec());
  7404. QTime jitComp(epoch.hour(), measure.time().minute(),
  7405. measure.time().second(), measure.time().msec());
  7406. int relTime = jitBase.msecsTo(jitComp);
  7407. @<Produce and emit relative time@>@;
  7408. }
  7409. else@/
  7410. {
  7411. Measurement rel = measure;
  7412. rel.setTime(QTime(0, 0, 0, 0));
  7413. emit measurement(rel);
  7414. }
  7415. }
  7416. else@/
  7417. {
  7418. int relTime = epoch.msecsTo(measure.time());
  7419. @<Produce and emit relative time@>@;
  7420. }
  7421. hasPrevious = true;
  7422. previous = measure.time();@t\2@>@/
  7423. }
  7424. @ The measurement emitted has a time with the number of minutes, seconds, and
  7425. milliseconds since the start of the batch. We never generate a time greater
  7426. than 1 hour.
  7427. @<Produce and emit relative time@>=
  7428. QTime newTime(0, 0, 0, 0);
  7429. newTime = newTime.addMSecs(relTime);
  7430. if(newTime.hour() > 0)
  7431. {
  7432. newTime.setHMS(0, newTime.minute(), newTime.second(), newTime.msec());
  7433. }
  7434. Measurement rel = measure;
  7435. rel.setTime(newTime);
  7436. emit measurement(rel);
  7437. @ The rest of the code handles updating and reporting the reference time.
  7438. @<MeasurementTimeOffset Implementation@>=
  7439. MeasurementTimeOffset::MeasurementTimeOffset(QTime zero) : epoch(zero),
  7440. previous(0, 0, 0, 0), hasPrevious(false)
  7441. {
  7442. /* Nothing has to be done here. */
  7443. }
  7444. QTime MeasurementTimeOffset::zeroTime()
  7445. {
  7446. return epoch;
  7447. }
  7448. void MeasurementTimeOffset::setZeroTime(QTime zero)
  7449. {
  7450. epoch = zero;
  7451. hasPrevious = false;
  7452. }
  7453. @ Two functions are required to make this class available to the scripting
  7454. engine.
  7455. @<Function prototypes for scripting@>=
  7456. QScriptValue constructMeasurementTimeOffset(QScriptContext *context,@|
  7457. QScriptEngine *engine);
  7458. void setMeasurementTimeOffsetProperties(QScriptValue value,
  7459. QScriptEngine *engine);
  7460. @ The scripting engine must be informed of the constructor.
  7461. @<Set up the scripting engine@>=
  7462. constructor = engine->newFunction(constructMeasurementTimeOffset);
  7463. value = engine->newQMetaObject(&MeasurementTimeOffset::staticMetaObject,
  7464. constructor);
  7465. engine->globalObject().setProperty("MeasurementTimeOffset", value);
  7466. @ Previously, another property was added to the newly created object. That
  7467. method is believed to be obsolete and has been removed. Careful testing will
  7468. need to be done to verify that this decision was sane. I was very hungry when
  7469. that change was made.
  7470. @<Functions for scripting@>=
  7471. QScriptValue constructMeasurementTimeOffset(QScriptContext *,
  7472. QScriptEngine *engine)
  7473. {
  7474. QScriptValue object =@|
  7475. engine->newQObject(new MeasurementTimeOffset(QTime::currentTime()));
  7476. setMeasurementTimeOffsetProperties(object, engine);
  7477. return object;
  7478. }
  7479. void setMeasurementTimeOffsetProperties(QScriptValue value,
  7480. QScriptEngine *engine)
  7481. {
  7482. setQObjectProperties(value, engine);
  7483. }
  7484. @* Measured value threshold detection.
  7485. \noindent There are times when one might want to detect when a measured value
  7486. from a data series has passed a given value, with the limitation that we are
  7487. only interested in the ascending or descending edge. This can be used, for
  7488. example, to translate roast profile data in a graph along the time axis such
  7489. that the bean temperature series are aligned at a given
  7490. temperature.\nfnote{More details on the reasoning behind why one might want
  7491. to do this are provided at:\par\indent\pdfURL{http://youtu.be/hS0SfzypyFQ}
  7492. {http://youtu.be/hS0SfzypyFQ}} For this we can use a |ThresholdDetector|.
  7493. If we would like to catch changes on both the ascending and descending edge, we
  7494. can use two objects, however it may be a good idea to use more than two to
  7495. allow for sane behavior in the face of hysteresis.
  7496. @<Class declarations@>=
  7497. class ThresholdDetector : public QObject@/
  7498. {
  7499. @[Q_OBJECT@]@;
  7500. @[Q_ENUMS(EdgeDirection)@]@;
  7501. public:@/
  7502. enum EdgeDirection {
  7503. Ascending, Descending
  7504. };
  7505. ThresholdDetector(double value);
  7506. @[public slots@]:@/
  7507. void newMeasurement(Measurement measure);
  7508. void setThreshold(double value);
  7509. void setEdgeDirection(EdgeDirection direction);
  7510. signals:@/
  7511. void timeForValue(double);
  7512. private:@/
  7513. bool previousValueValid;
  7514. double previousValue;
  7515. double threshold;
  7516. EdgeDirection currentDirection;
  7517. };
  7518. @ This class emits the time in seconds when a given measurement crosses the
  7519. threshold value in the appropriate direction.
  7520. This was previously written with |previousValue| initialized negative and a
  7521. check that |previousValue| was non-negative. When the |ThresholdDetector| is
  7522. connected to a data source representing temperature measurements this is a
  7523. reasonable choice, however it breaks when connected to a rate of change series.
  7524. To make this more generally correct, a boolean is checked to determine if a
  7525. previous value has been set.
  7526. @<ThresholdDetector Implementation@>=
  7527. void ThresholdDetector::newMeasurement(Measurement measure)
  7528. {
  7529. if((currentDirection == Ascending && previousValue < threshold &&
  7530. previousValueValid) || (currentDirection == Descending &&
  7531. previousValue > threshold && previousValueValid))
  7532. {
  7533. if((currentDirection == Ascending && measure.temperature() >= threshold) ||
  7534. (currentDirection == Descending && measure.temperature() <= threshold))
  7535. {
  7536. double offset = measure.time().hour() * 60 * 60;
  7537. offset += measure.time().minute() * 60;
  7538. offset += measure.time().second();
  7539. offset += measure.time().msec()/1000;
  7540. emit timeForValue(offset);
  7541. }
  7542. }
  7543. previousValue = measure.temperature();
  7544. previousValueValid = true;
  7545. }
  7546. ThresholdDetector::ThresholdDetector(double value) : QObject(NULL),
  7547. previousValueValid(false),
  7548. previousValue(-1), threshold(value), currentDirection(Ascending)
  7549. {
  7550. /* Nothing needs to be done here. */
  7551. }
  7552. void ThresholdDetector::setThreshold(double value)
  7553. {
  7554. threshold = value;
  7555. }
  7556. void ThresholdDetector::setEdgeDirection(EdgeDirection direction)
  7557. {
  7558. currentDirection = direction;
  7559. }
  7560. @ This is exposed to the host environment.
  7561. @<Function prototypes for scripting@>=
  7562. QScriptValue constructThresholdDetector(QScriptContext *context, QScriptEngine *engine);
  7563. void setThresholdDetectorProperties(QScriptValue value, QScriptEngine *engine);
  7564. @ Inform the engine of the constructor.
  7565. @<Set up the scripting engine@>=
  7566. constructor = engine->newFunction(constructThresholdDetector);
  7567. value = engine->newQMetaObject(&ThresholdDetector::staticMetaObject, constructor);
  7568. engine->globalObject().setProperty("ThresholdDetector", value);
  7569. @ Implementation. At present I'@q'@>m not bothering to implement constructor
  7570. arguments here and am aligning on a fixed point. Another slot method was added
  7571. to restore adjustability.
  7572. @<Functions for scripting@>=
  7573. QScriptValue constructThresholdDetector(QScriptContext *, QScriptEngine *engine)
  7574. {
  7575. QScriptValue object = engine->newQObject(new ThresholdDetector(300));
  7576. return object;
  7577. }
  7578. void setThresholdDetectorProperties(QScriptValue value, QScriptEngine *engine)
  7579. {
  7580. setQObjectProperties(value, engine);
  7581. }
  7582. @* The ZeroEmitter class.
  7583. \noindent Now that it is possible to record the time a measurement was taken
  7584. relative to an arbitrary start time, there is a minor problem left for logging.
  7585. It is extremely unlikely that a measurement will be passed through at the epoch.
  7586. For this, what we want to do is save the previous measurement and make it
  7587. available at time 0 whenever the start time is reset. This is the role of the
  7588. |ZeroEmitter| class.
  7589. Another problem is that most classes that are interested in a relative time are
  7590. also interested in logging multiple sets of temperature data. To facilitate this
  7591. an integer is emitted. Different temperature measurement sources should be set
  7592. to emit different numbers. A table view would place measurements in the
  7593. indicated column. A graph view would use different colors to plot different sets
  7594. of data.
  7595. @<Class declarations@>=
  7596. class ZeroEmitter : public QObject@/
  7597. {@t\1@>@/
  7598. @[Q_OBJECT@]@;
  7599. @[Q_PROPERTY(int column READ column WRITE setColumn)@]@;
  7600. Measurement cache;
  7601. int col;
  7602. public:@/
  7603. ZeroEmitter(int tempcolumn = 1);
  7604. int column();
  7605. double lastTemperature();@/
  7606. @t\4@>public slots@t\kern-3pt@>:@;
  7607. void newMeasurement(Measurement measure);
  7608. void setColumn(int column);
  7609. void emitZero();
  7610. signals:@;
  7611. void measurement(Measurement measure, int tempcolumn);@t\2@>@/
  7612. }@t\kern-3pt@>;
  7613. @ The implementation of the class is trivial.
  7614. @<ZeroEmitter Implementation@>=
  7615. ZeroEmitter::ZeroEmitter(int tempcolumn) : QObject(NULL), col(tempcolumn)@;
  7616. {
  7617. /* Nothing has to be done here. */
  7618. }
  7619. int ZeroEmitter::column()
  7620. {
  7621. return col;
  7622. }
  7623. double ZeroEmitter::lastTemperature()
  7624. {
  7625. return cache.temperature();
  7626. }
  7627. void ZeroEmitter::newMeasurement(Measurement measure)
  7628. {
  7629. cache = measure;
  7630. }
  7631. void ZeroEmitter::setColumn(int column)
  7632. {
  7633. col = column;
  7634. }
  7635. void ZeroEmitter::emitZero()
  7636. {
  7637. cache.setTime(QTime(0, 0, 0, 0));
  7638. emit measurement(cache, col);
  7639. }
  7640. @ Making this class available to scripts requires only two functions.
  7641. @<Function prototypes for scripting@>=
  7642. QScriptValue constructZeroEmitter(QScriptContext *context,
  7643. QScriptEngine *engine);
  7644. void setZeroEmitterProperties(QScriptValue value, QScriptEngine *engine);
  7645. @ To use it, we must inform the engine of the constructor.
  7646. @<Set up the scripting engine@>=
  7647. constructor = engine->newFunction(constructZeroEmitter);
  7648. value = engine->newQMetaObject(&ZeroEmitter::staticMetaObject, constructor);
  7649. engine->globalObject().setProperty("ZeroEmitter", value);
  7650. @ The implementation of the constructor is trivial.
  7651. @<Functions for scripting@>=
  7652. QScriptValue constructZeroEmitter(QScriptContext *context,
  7653. QScriptEngine *engine)
  7654. {
  7655. QScriptValue object =
  7656. engine->newQObject(new ZeroEmitter(argument<int>(0, context)));
  7657. setZeroEmitterProperties(object, engine);
  7658. return object;
  7659. }
  7660. void setZeroEmitterProperties(QScriptValue value, QScriptEngine *engine)
  7661. {
  7662. setQObjectProperties(value, engine);
  7663. }
  7664. @* The MeasurementAdapter class.
  7665. \noindent The last of the measurement filter classes is the |MeasurementAdapter|
  7666. class. This takes measurements, typically from a |MeasurementTimeOffset|, and
  7667. sends the measurement out with a number to indicate which data series the
  7668. measurement belongs to.
  7669. The measurement pipeline could probably be made simpler by introducing a series
  7670. identifier into the measurement class.
  7671. @<Class declarations@>=
  7672. class MeasurementAdapter : public QObject@/
  7673. {@t\1@>@/
  7674. Q_OBJECT@;
  7675. int col;
  7676. public:@/
  7677. MeasurementAdapter(int tempcolumn);
  7678. int column();@/
  7679. @t\4@>public slots@t\kern-3pt@>:@/
  7680. void newMeasurement(Measurement measure);
  7681. void setColumn(int column);
  7682. signals:@/
  7683. void measurement(Measurement measure, int tempcolumn);@t\2@>@/
  7684. }@t\kern-3pt@>;
  7685. @ The implementation of this filter class is trivial.
  7686. @<MeasurementAdapter Implementation@>=
  7687. MeasurementAdapter::MeasurementAdapter(int tempcolumn) : col(tempcolumn)@;
  7688. {
  7689. /* Nothing has to be done here. */
  7690. }
  7691. int MeasurementAdapter::column()
  7692. {
  7693. return col;
  7694. }
  7695. void MeasurementAdapter::newMeasurement(Measurement measure)
  7696. {
  7697. emit measurement(measure, col);
  7698. }
  7699. void MeasurementAdapter::setColumn(int column)
  7700. {
  7701. col = column;
  7702. }
  7703. @ This filter class is also available from the host environment.
  7704. @<Function prototypes for scripting@>=
  7705. QScriptValue constructMeasurementAdapter(QScriptContext *context,
  7706. QScriptEngine *engine);
  7707. void setMeasurementAdapterProperties(QScriptValue value, QScriptEngine *engine);
  7708. @ As usual, the engine must be informed of the constructor.
  7709. @<Set up the scripting engine@>=
  7710. constructor = engine->newFunction(constructMeasurementAdapter);
  7711. value = engine->newQMetaObject(&MeasurementAdapter::staticMetaObject,
  7712. constructor);
  7713. engine->globalObject().setProperty("MeasurementAdapter", value);
  7714. @ The implementation is trivial.
  7715. @<Functions for scripting@>=
  7716. QScriptValue constructMeasurementAdapter(QScriptContext *context,
  7717. QScriptEngine *engine)
  7718. {
  7719. QScriptValue object =
  7720. engine->newQObject(new MeasurementAdapter(argument<int>(0, context)));
  7721. setMeasurementAdapterProperties(object, engine);
  7722. return object;
  7723. }
  7724. void setMeasurementAdapterProperties(QScriptValue value, QScriptEngine *engine)
  7725. {
  7726. setQObjectProperties(value, engine);
  7727. }
  7728. @* A graph of temperature over time.
  7729. \noindent A useful tool when roasting is a visual depiction of the current batch
  7730. as it happens, possibly laid over a previously recorded target profile. The
  7731. |GraphView| class can take multiple sets of temperature data and produce such a
  7732. visualization.
  7733. \medskip
  7734. \centerline{\includegraphics{roast}}
  7735. \smallskip
  7736. \centerline{Figure \secno: A Typical Roast}
  7737. \medskip
  7738. This class assumes that temperature data will be passed in the correct order.
  7739. @<Class declarations@>=
  7740. class GraphView : public QGraphicsView@/
  7741. {@t\1@>@/
  7742. Q_OBJECT@;
  7743. QGraphicsScene *theScene;@/
  7744. QMap<int, QList<QGraphicsLineItem * > * > *graphLines;@/
  7745. QMap<int, QPointF> *prevPoints;
  7746. QMap<int, double> *translations;
  7747. QList<QGraphicsItem *> *gridLinesF;
  7748. QList<QGraphicsItem *> *gridLinesC;
  7749. QList<QGraphicsItem *> *relativeGridLines;
  7750. bool relativeEnabled;
  7751. bool timeIndicatorEnabled;
  7752. QGraphicsLineItem *timeLine;
  7753. LinearSplineInterpolator *relativeAdjuster;@/
  7754. public:@/
  7755. GraphView(QWidget *parent = NULL);
  7756. void removeSeries(int column);@/
  7757. protected:@/
  7758. void resizeEvent(QResizeEvent *event);@/
  7759. @t\4@>public slots@t\kern-3pt@>:@/
  7760. void newMeasurement(Measurement measure, int tempcolumn);
  7761. void setSeriesTranslation(int column, double offset);
  7762. void setTimeIndicatorEnabled(bool enabled);
  7763. void clear();
  7764. void showF();
  7765. void showC();@t\2@>@/
  7766. }@t\kern-3pt@>;
  7767. @ I decided that it would probably be best to keep the graph area the same even
  7768. with different roast lengths over different temperature ranges so that similar
  7769. portions between these graphs would continue to look similar rather than
  7770. constantly attempting to select the best way to display the data currently in
  7771. the view.
  7772. I have chosen to represent roasting times of up to 20 minutes and temperatures
  7773. between 0 and 500$^\circ$ Fahrenheit. This should certainly be configurable at
  7774. run time, but until that is implemented, roasters who routinely roast batches
  7775. for longer periods of time will want to change the constructor. This class
  7776. should probably be modified to allow the user to specify several characteristics
  7777. of the display.
  7778. This class must also deal with the fact that coordinates in a |QGraphicsScene|
  7779. are not quite the same as coordinates in a cartesian plane. The easiest way to
  7780. deal with this is to negate the y coordinate and translate the viewport to the
  7781. area we draw in.
  7782. A small margin area left around the edges of the graph. This should probably be
  7783. configurable for those with particularly small displays.
  7784. @<GraphView Implementation@>=
  7785. GraphView::GraphView(QWidget *parent) : QGraphicsView(parent),
  7786. theScene(new QGraphicsScene),@/
  7787. graphLines(new QMap<int, QList<QGraphicsLineItem *> *>),@/
  7788. prevPoints(new QMap<int, QPointF>),
  7789. translations(new QMap<int, double>),
  7790. gridLinesF(new QList<QGraphicsItem *>),
  7791. gridLinesC(new QList<QGraphicsItem *>),
  7792. relativeGridLines(new QList<QGraphicsItem *>),
  7793. relativeEnabled(false),
  7794. timeIndicatorEnabled(false),
  7795. timeLine(new QGraphicsLineItem),
  7796. relativeAdjuster(new LinearSplineInterpolator)@/
  7797. {
  7798. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  7799. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  7800. setScene(theScene);
  7801. setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
  7802. QPen timePen;
  7803. timePen.setColor(QColor(160, 160, 164, 127)); //gray, half opacity
  7804. timeLine->setPen(timePen);
  7805. timeLine->setLine(0, 0, 0, -500);
  7806. timeLine->hide();
  7807. theScene->addItem(timeLine);
  7808. @<Draw temperature axis and grid lines@>;
  7809. @<Draw secondary axes@>@;
  7810. @<Draw time axis and ticks@>;
  7811. fitInView(theScene->sceneRect().adjusted(-50,-50,50,50));
  7812. }
  7813. @ Grid lines are drawn every 100 degrees. These lines are labeled with
  7814. |setHtml()| for convenient access to the $^\circ$ symbol. If \pn{} is modified
  7815. to allow different units, this code should also be modified.
  7816. As of version 1.3.3 it is possible to switch the graph between degrees
  7817. Fahrenheit and degrees Celcius. Celcius grid lines are drawn but initially
  7818. hidden. Both the grid lines and the labels are added to a list depending on the
  7819. unit so that when changing from one view to another all that needs to happen is
  7820. hide one list of items and show another.
  7821. @<Draw temperature axis and grid lines@>=
  7822. QGraphicsLineItem *tempaxis = new QGraphicsLineItem;
  7823. tempaxis->setLine(-10, -500, -10, 0);
  7824. theScene->addItem(tempaxis);
  7825. QGraphicsLineItem *gridLine;
  7826. QGraphicsTextItem *label;
  7827. for(int y = -100; y > -600; y -= 100)@/
  7828. {@/
  7829. gridLine = new QGraphicsLineItem;
  7830. gridLine->setLine(0, y, 1200, y);
  7831. theScene->addItem(gridLine);
  7832. label = new QGraphicsTextItem;
  7833. label->setHtml(QString("%1&deg;F").arg(-y));
  7834. label->setPos(-55, y - (label->boundingRect().height() / 2));
  7835. theScene->addItem(label);
  7836. gridLinesF->append(gridLine);
  7837. gridLinesF->append(label);
  7838. }
  7839. for(int degC = 50; degC <= 250; degC += 50)
  7840. {
  7841. gridLine = new QGraphicsLineItem;
  7842. int y = -(degC * (9.0/5.0) + 32);
  7843. gridLine->setLine(0, y, 1200, y);
  7844. gridLine->hide();
  7845. theScene->addItem(gridLine);
  7846. gridLinesC->append(gridLine);
  7847. label = new QGraphicsTextItem;
  7848. label->setHtml(QString("%1&deg;C").arg(degC));
  7849. label->setPos(-55, y - (label->boundingRect().height() / 2));
  7850. label->hide();
  7851. theScene->addItem(label);
  7852. gridLinesC->append(label);
  7853. }
  7854. @ If we are going to plot relative temperature measurements, we must obtain
  7855. information on how we wish to do that from settings. We take advantage of the
  7856. fact that iterating over the keys in a |QMap| produces results in sorted order.
  7857. While drawing the grid lines we also set up the |relativeAdjuster| that will be
  7858. used to transform incoming measurements to our coordinate system.
  7859. @<Draw secondary axes@>=
  7860. QSettings settings;
  7861. if(settings.contains("settings/graph/relative/enable"))
  7862. {
  7863. if(settings.value("settings/graph/relative/enable").toBool())
  7864. {
  7865. relativeEnabled = @[true@];
  7866. QColor relativeColor = QColor(settings.value("settings/graph/relative/color").toString());
  7867. QString unit = QString(settings.value(@|"settings/graph/relative/unit").toInt() == 0 ? "F" : "C");
  7868. QMap<double, QString> relativeAxisPairs;
  7869. QStringList relativeAxisLabels = settings.value(@|"settings/graph/relative/grid").toString().split(QRegExp("[\\s,]+"), QString::SkipEmptyParts);
  7870. foreach(QString item, relativeAxisLabels)
  7871. {
  7872. relativeAxisPairs.insert(item.toDouble(), item);
  7873. }
  7874. if(relativeAxisPairs.size() > 1)
  7875. {
  7876. double skip = 500.0 / (relativeAxisPairs.size() - 1);
  7877. double y = 0;
  7878. foreach(double key, relativeAxisPairs.keys())
  7879. {
  7880. gridLine = new QGraphicsLineItem;
  7881. gridLine->setLine(0, y, 1205, y);
  7882. gridLine->setPen(QPen(relativeColor));
  7883. theScene->addItem(gridLine);
  7884. relativeGridLines->append(gridLine);
  7885. label = new QGraphicsTextItem;
  7886. label->setHtml(QString("%1&deg;%2").arg(relativeAxisPairs.value(key)).arg(unit));
  7887. label->setPos(1210, y - (label->boundingRect().height() / 2));
  7888. theScene->addItem(label);
  7889. relativeGridLines->append(label);
  7890. if(unit == "F")
  7891. {
  7892. relativeAdjuster->add_pair(key, -y);
  7893. }
  7894. else
  7895. {
  7896. relativeAdjuster->add_pair(key * (9.0/5.0), -y);
  7897. }
  7898. y -= skip;
  7899. }
  7900. }
  7901. }
  7902. }
  7903. @ Two slots are used to switch between the different sets of grid lines.
  7904. @<GraphView Implementation@>=
  7905. void GraphView::showF()
  7906. {
  7907. for(int i = 0; i < gridLinesF->size(); i++)
  7908. {
  7909. gridLinesF->at(i)->show();
  7910. }
  7911. for(int i = 0; i < gridLinesC->size(); i++)
  7912. {
  7913. gridLinesC->at(i)->hide();
  7914. }
  7915. }
  7916. void GraphView::showC()
  7917. {
  7918. for(int i = 0; i < gridLinesF->size(); i++)
  7919. {
  7920. gridLinesF->at(i)->hide();
  7921. }
  7922. for(int i = 0; i < gridLinesC->size(); i++)
  7923. {
  7924. gridLinesC->at(i)->show();
  7925. }
  7926. }
  7927. @ The time axis has a tick every two minutes. The use of the |?| tertiary
  7928. operator shifts the labels with two digits a little more than labels with only
  7929. one digit. If it worked, a more resilient approach would be to take the width of
  7930. the label and center it under the tick.
  7931. @<Draw time axis and ticks@>=
  7932. QGraphicsLineItem *timeaxis = new QGraphicsLineItem;
  7933. timeaxis->setLine(0, 10, 1200, 10);
  7934. theScene->addItem(timeaxis);
  7935. for(int x = 0; x < 1201; x += 120)@/
  7936. {@/
  7937. QGraphicsLineItem *tick = new QGraphicsLineItem;
  7938. tick->setLine(x, 0, x, 20);
  7939. theScene->addItem(tick);
  7940. QGraphicsTextItem *label = new QGraphicsTextItem;
  7941. label->setPlainText(QString("%1").arg(x/60));
  7942. label->setPos(x - (label->boundingRect().width() / 2), 20);
  7943. theScene->addItem(label);
  7944. }
  7945. @ Typically, the user will be able to resize the graph. When the widget is
  7946. resized, we should fit the graph to the new size of the widget. This is safe to
  7947. do as we have already turned off the scroll bars.
  7948. @<GraphView Implementation@>=
  7949. void GraphView::resizeEvent(QResizeEvent *)
  7950. {
  7951. fitInView(theScene->sceneRect().adjusted(-50,-50,50,50));
  7952. }
  7953. @ When adding a new measurement, there are three cases that should be
  7954. considered. In the case of the first measurement, no drawing occurs. A |QList|
  7955. of line items is initialized when the second measurement is taken. Subsequent
  7956. measurements are able to simply append new line segments to the list.
  7957. Relative measurements are first converted to the coordinate system of the
  7958. appropriate secondary axis.
  7959. @<GraphView Implementation@>=
  7960. #define FULLTIMETOINT(t) (t.msec() + (t.second() * 1000) + (t.minute() * 60 * 1000))
  7961. void GraphView::newMeasurement(Measurement measure, int tempcolumn)@/
  7962. {@/
  7963. double offset = 0;
  7964. if(measure.contains("relative"))
  7965. {
  7966. if(measure.value("relative").toBool())
  7967. {
  7968. if(relativeEnabled)
  7969. {
  7970. measure.setTemperature(relativeAdjuster->newMeasurement(measure).temperature());
  7971. }
  7972. else
  7973. {
  7974. return;
  7975. }
  7976. }
  7977. }
  7978. if(translations->contains(tempcolumn))
  7979. {
  7980. offset = translations->value(tempcolumn);
  7981. }
  7982. if(prevPoints->contains(tempcolumn))@/
  7983. @t\1@>{@/
  7984. @<At least one measurement exists@>@;
  7985. if(graphLines->contains(tempcolumn))@/
  7986. {@t\1@>
  7987. /* More than one measurement existed. */
  7988. graphLines->value(tempcolumn)->append(segment);@t\2@>@/
  7989. }@/
  7990. else@/
  7991. {@/
  7992. /* This is the second measurement. */
  7993. QList<QGraphicsLineItem *> *newLine =
  7994. new QList<QGraphicsLineItem *>;@/
  7995. newLine->append(segment);
  7996. graphLines->insert(tempcolumn, newLine);
  7997. }@t\2@>@/
  7998. }@/
  7999. else@/
  8000. {@/
  8001. @<Handle the first measurement@>@;
  8002. }
  8003. }
  8004. @ There are some parts of the code that are correct, but seem somewhat goofy.
  8005. This is especially true surrounding the graphics view architecture as this was
  8006. not working correctly when I wrote the code that uses it. The code as it is
  8007. written works for me, but when these workarounds are no longer needed it would
  8008. be better to remove them. Handling values on the time axis is one example of
  8009. this.
  8010. Some might question the use of an integer data type, particularly when storing
  8011. the result of a division operation. While this could be a concern if high
  8012. resolution wall sized displays become common, is is expected that in most cases
  8013. with sufficiently high sample rates, many data points will map to the same pixel
  8014. even with the minor data loss below.
  8015. In the case of the first measurement,
  8016. @<Handle the first measurement@>=
  8017. int x = FULLTIMETOINT(measure.time())/1000;
  8018. prevPoints->insert(tempcolumn, QPointF(x, measure.temperature()));
  8019. if(timeIndicatorEnabled)
  8020. {
  8021. timeLine->setLine(x, 0, x, -500);
  8022. }
  8023. @ When at least one measurement already exists, we need to handle drawing the
  8024. line between the new measurement and the previous measurement.
  8025. \danger At present, the color chosen for these lines is based on the temperature
  8026. column passed to the graph. It would be better if colors could be passed to the
  8027. view for a specified series rather than have this hard coded. \endanger
  8028. @<At least one measurement exists@>=
  8029. QGraphicsLineItem *segment = new QGraphicsLineItem;
  8030. QPointF nextPoint(FULLTIMETOINT(measure.time())/1000, measure.temperature());
  8031. segment->setLine(prevPoints->value(tempcolumn).x() + offset,
  8032. -(prevPoints->value(tempcolumn).y()),
  8033. nextPoint.x() + offset, -(nextPoint.y()));
  8034. static QColor p[12] = {Qt::yellow, Qt::blue, Qt::cyan, Qt::red, Qt::magenta,
  8035. Qt::green, Qt::darkGreen, Qt::darkMagenta,
  8036. Qt::darkRed, Qt::darkCyan, Qt::darkBlue,
  8037. Qt::darkYellow};
  8038. segment->setPen(p[tempcolumn % 12]);
  8039. theScene->addItem(segment);
  8040. prevPoints->insert(tempcolumn, nextPoint);
  8041. if(timeIndicatorEnabled)
  8042. {
  8043. timeLine->setLine(nextPoint.x() + offset, 0, nextPoint.x() + offset, -500);
  8044. }
  8045. @ In addition to adding data to the view, we also sometimes want to clear the
  8046. view of data.
  8047. @<GraphView Implementation@>=
  8048. void GraphView::clear()
  8049. {
  8050. int i;
  8051. foreach(i, prevPoints->keys())
  8052. {
  8053. removeSeries(i);
  8054. }
  8055. translations->clear();
  8056. }
  8057. @ Removing a set of data from the view involves removing the lines from the
  8058. scene and removing the column from a couple data structures.
  8059. @<GraphView Implementation@>=
  8060. void GraphView::removeSeries(int column)
  8061. {
  8062. if(graphLines->contains(column))
  8063. {
  8064. QList<QGraphicsLineItem *> *series = graphLines->value(column);
  8065. QGraphicsLineItem *segment;
  8066. foreach(segment, *series)
  8067. {
  8068. theScene->removeItem(segment);
  8069. }
  8070. qDeleteAll(*series);
  8071. }
  8072. graphLines->remove(column);
  8073. prevPoints->remove(column);
  8074. }
  8075. @ Second prototype for data series translation.
  8076. @<GraphView Implementation@>=
  8077. void GraphView::setSeriesTranslation(int column, double offset)
  8078. {
  8079. if(graphLines->contains(column))
  8080. {
  8081. QList<QGraphicsLineItem *> *series = graphLines->value(column);
  8082. QGraphicsLineItem *segment;
  8083. foreach(segment, *series)
  8084. {
  8085. segment->setPos(segment->pos().x()+offset, segment->pos().y());
  8086. }
  8087. }
  8088. if(translations->contains(column))
  8089. {
  8090. translations->insert(column, offset + translations->value(column));
  8091. }
  8092. else
  8093. {
  8094. translations->insert(column, offset);
  8095. }
  8096. }
  8097. @ Starting in \pn{} 1.6 it is possible to add a vertical line indicating the
  8098. time position of the most recent measurement. This should be hidden for loading
  8099. target roast profiles and shown depending on preference. A new method controls
  8100. this.
  8101. @<GraphView Implementation@>=
  8102. void GraphView::setTimeIndicatorEnabled(bool enabled)
  8103. {
  8104. timeIndicatorEnabled = enabled;
  8105. if(enabled)
  8106. {
  8107. timeLine->show();
  8108. }
  8109. else
  8110. {
  8111. timeLine->hide();
  8112. }
  8113. }
  8114. @ These functions are required to create a |GraphView| object from a script.
  8115. @<Function prototypes for scripting@>=
  8116. void setGraphViewProperties(QScriptValue value, QScriptEngine *engine);
  8117. QScriptValue constructGraphView(QScriptContext *context, QScriptEngine *engine);
  8118. @ The scripting engine must be informed of the constructor.
  8119. @<Set up the scripting engine@>=
  8120. constructor = engine->newFunction(constructGraphView);
  8121. value = engine->newQMetaObject(&GraphView::staticMetaObject, constructor);
  8122. engine->globalObject().setProperty("GraphView", value);
  8123. @ The function implementation is trivial.
  8124. @<Functions for scripting@>=
  8125. QScriptValue constructGraphView(QScriptContext *, QScriptEngine *engine)
  8126. {
  8127. QScriptValue object = engine->newQObject(new GraphView);
  8128. setGraphViewProperties(object, engine);
  8129. return object;
  8130. }
  8131. void setGraphViewProperties(QScriptValue value, QScriptEngine *engine)
  8132. {
  8133. setQGraphicsViewProperties(value, engine);
  8134. }
  8135. @* A table of roasting data.
  8136. \noindent A typical roast log is a table listing temperature measurements taken
  8137. at regular intervals. The introduction of a computer brings several advantages.
  8138. A human does not need to record the measurements. Every measurement taken can be
  8139. logged, but the measurements do not all need to be displayed. The |ZoomLog|
  8140. class presents a table with time, temperature, and annotation for one or more
  8141. sets of roasting data and allows the user to select from a few different levels
  8142. of detail.
  8143. Experience has shown that one measurement every 30 or 15 seconds is most useful,
  8144. but it is also possible to view one measurement every 1, 5, 10, or 60 seconds
  8145. and there is an option to view every measurement collected. This last is what is
  8146. saved to a file.
  8147. The zooming log is implemented by keeping a measurement model with every level
  8148. of detail of interest and making sure that new measurements get to the models
  8149. they belong in. Switching the level of detail of the view then becomes a matter
  8150. of changing which model the view is using. This is very inefficient in terms of
  8151. space, but it is very fast and simple to code.
  8152. Starting in version 1.4, column sizes are persisted automatically using the
  8153. same method as described in the section on |SqlQueryView|.
  8154. Starting in version 1.8, |rowCount()| is |Q_INVOKABLE|. This allows the manual
  8155. log entry interface to easily determine if any roasting data exists to save.
  8156. @<Class declarations@>=
  8157. class MeasurementModel;@/
  8158. class ZoomLog : public QTableView@/
  8159. {@/
  8160. @[Q_OBJECT@]@;
  8161. @<ZoomLog private member data@>@;
  8162. void switchLOD(MeasurementModel *m);@/
  8163. @[private slots@]:@/
  8164. void centerOn(int row);
  8165. void persistColumnResize(int column, int oldsize, int newsize);
  8166. void restoreColumnWidths();
  8167. public:@/
  8168. ZoomLog();
  8169. QVariant data(int row, int column) const;
  8170. @[Q_INVOKABLE@,@, int rowCount();
  8171. bool saveXML(QIODevice *device);
  8172. bool saveCSV(QIODevice *device);
  8173. QString lastTime(int series);
  8174. @[Q_INVOKABLE@,@, Units::Unit displayUnits()@];@t\2\2@>@/
  8175. @[public slots@]:@/
  8176. void setVisible(bool visibility);
  8177. void setHeaderData(int section, QString text);
  8178. void LOD_ms();
  8179. void LOD_1s();
  8180. void LOD_5s();
  8181. void LOD_10s();
  8182. void LOD_15s();
  8183. void LOD_30s();
  8184. void LOD_1m();
  8185. void newMeasurement(Measurement measure, int tempcolumn);
  8186. void newAnnotation(QString annotation, int tempcolumn,
  8187. int annotationcolumn);
  8188. void clear();
  8189. void addOutputTemperatureColumn(int column);
  8190. void addOutputControlColumn(int column);
  8191. void addOutputAnnotationColumn(int column);
  8192. void clearOutputColumns();
  8193. void setDisplayUnits(Units::Unit scale);
  8194. void addToCurrentColumnSet(int column);
  8195. void clearCurrentColumnSet();@/
  8196. protected:@/
  8197. virtual void showEvent(QShowEvent *event);
  8198. };
  8199. @ This class uses a different model for each level of detail and provides logic
  8200. for placing measurements and annotations in the appropriate models. A list of
  8201. each model is provided for conveniently performing operations that apply to
  8202. every model.
  8203. @<ZoomLog private member data@>=
  8204. MeasurementModel *model_ms;
  8205. MeasurementModel *model_1s;
  8206. MeasurementModel *model_5s;
  8207. MeasurementModel *model_10s;
  8208. MeasurementModel *model_15s;
  8209. MeasurementModel *model_30s;
  8210. MeasurementModel *model_1m;
  8211. QList<MeasurementModel *> modelSet;
  8212. QHash<int, Measurement> lastMeasurement;
  8213. MeasurementModel *currentModel;
  8214. QList<int> saveTempCols;
  8215. QList<int> saveControlCols;
  8216. QList<int> saveNoteCols;
  8217. QList<int> currentColumnSet;
  8218. @ Most of the functionality this class provides is in getting measurements to
  8219. the right models. Every measurement goes to the full detail model. We also keep
  8220. track of the most recent measurement to detect the first measurement in a new
  8221. second and pass all of these on to the 1 second level of detail model. Some of
  8222. these are also passed to other models. Additionally, the models that store
  8223. coarser data strip the millisecond portion of the time.
  8224. A decision was made to present data promptly. With a high sample rate, some
  8225. might prefer an average of a few measurements near the reported time, but such
  8226. a feature does not exist in \pn{} currently.
  8227. The first measurement is always added to each model.
  8228. @<ZoomLog Implementation@>=
  8229. void ZoomLog::newMeasurement(Measurement measure, int tempcolumn)
  8230. {
  8231. if(measure.time() != QTime(0, 0, 0, 0))
  8232. {
  8233. @<Synthesize measurements for slow hardware@>@;
  8234. }
  8235. model_ms->newMeasurement(measure, tempcolumn);
  8236. if(lastMeasurement.contains(tempcolumn))
  8237. {
  8238. if(measure.time().second() !=
  8239. lastMeasurement.value(tempcolumn).time().second())
  8240. {
  8241. Measurement adjusted = measure;
  8242. QTime adjtime(0, measure.time().minute(), measure.time().second(), 0);
  8243. adjusted.setTime(adjtime);
  8244. model_1s->newMeasurement(adjusted, tempcolumn);
  8245. if(adjusted.time().second() % 5 == 0)
  8246. {
  8247. model_5s->newMeasurement(adjusted, tempcolumn);
  8248. if(adjusted.time().second() % 10 == 0)
  8249. {
  8250. model_10s->newMeasurement(adjusted, tempcolumn);
  8251. }
  8252. if(adjusted.time().second() % 15 == 0)
  8253. {
  8254. model_15s->newMeasurement(adjusted, tempcolumn);
  8255. if(adjusted.time().second() % 30 == 0)
  8256. {
  8257. model_30s->newMeasurement(adjusted, tempcolumn);
  8258. if(adjusted.time().second() == 0)
  8259. {
  8260. model_1m->newMeasurement(adjusted, tempcolumn);
  8261. }
  8262. }
  8263. }
  8264. }
  8265. }
  8266. @<Synthesize measurements for columns in set@>@;
  8267. }
  8268. else
  8269. {
  8270. @<Add the first measurement to every model@>@;
  8271. }
  8272. lastMeasurement.insert(tempcolumn, measure);
  8273. }
  8274. @ The first measurement in a series should be the epoch measurement. This
  8275. should exist in every level of detail.
  8276. @<Add the first measurement to every model@>=
  8277. MeasurementModel *m;
  8278. foreach(m, modelSet)
  8279. {
  8280. m->newMeasurement(measure, tempcolumn);
  8281. }
  8282. @ Some measurement hardware in use cannot guarantee delivery of at least one
  8283. measurement per second. This causes problems for the current |ZoomLog|
  8284. implementation as, for example, if there is no measurement at a time where
  8285. the seconds are divisible by 5, there will be no entry in that view. This can
  8286. result in situations where the |ZoomLog| at its default view of one measurement
  8287. every 30 seconds might not display any data at all aside from the first
  8288. measurement, the last measurement, and any measurement that happens to have an
  8289. annotation associated with it. The solution in this case is to synthesize
  8290. measurements so that the |ZoomLog| thinks it gets at least one measurement
  8291. every second.
  8292. Prior to version 1.8 this simply replicated the last measurement every second
  8293. until the time for the most recent measurement was reached, however this yields
  8294. problematic results when loading saved data or attempting to use this view for
  8295. manual data entry. The current behavior performs a linear interpolation which
  8296. will match the graph.
  8297. @<Synthesize measurements for slow hardware@>=
  8298. if(lastMeasurement.contains(tempcolumn))
  8299. {
  8300. if(lastMeasurement[tempcolumn].time() < measure.time())
  8301. {
  8302. QList<QTime> timelist;
  8303. QList<double> templist;
  8304. QTime z = QTime(0, 0, 0, 0);
  8305. double ptime = (double)(z.secsTo(lastMeasurement[tempcolumn].time()));
  8306. double ptemp = lastMeasurement[tempcolumn].temperature();
  8307. double ctime = (double)(z.secsTo(measure.time()));
  8308. double ctemp = measure.temperature();
  8309. for(QTime i = lastMeasurement.value(tempcolumn).time().addSecs(1); i < measure.time(); i = i.addSecs(1))
  8310. {
  8311. timelist.append(i);
  8312. double v = ((ptemp * (ctime - z.secsTo(i))) + (ctemp * (z.secsTo(i) - ptime))) / (ctime - ptime);
  8313. templist.append(v);
  8314. }
  8315. for(int i = 0; i < timelist.size(); i++)
  8316. {
  8317. Measurement synthesized = measure;
  8318. synthesized.setTime(timelist[i]);
  8319. synthesized.setTemperature(templist[i]);
  8320. newMeasurement(synthesized, tempcolumn);
  8321. }
  8322. }
  8323. }
  8324. @ New to \pn{} 1.4 is the concept of a current column set. This was added to
  8325. improve support for devices where measurements on different data series may not
  8326. arrive at exactly the same time and for multi-device configurations where
  8327. measurements from different devices are unlikely to arrive at the same time.
  8328. This can cause issues with log annotations and serialization. The solution is
  8329. to group all columns that are logically part of the same data acquisition
  8330. process and as measurements come in, the most recent measurement from other
  8331. columns can be duplicated at the new time. Two methods are responsible for
  8332. managing this measurement set. One adds a column to the set and the other
  8333. removes all columns from the set.
  8334. @<ZoomLog Implementation@>=
  8335. void ZoomLog::addToCurrentColumnSet(int column)
  8336. {
  8337. currentColumnSet.append(column);
  8338. }
  8339. void ZoomLog::clearCurrentColumnSet()
  8340. {
  8341. currentColumnSet.clear();
  8342. }
  8343. @ Replicating the measurements occurs as measurements are delivered. Note
  8344. that this code will not be called for the first measurement in each column.
  8345. @<Synthesize measurements for columns in set@>=
  8346. if(currentColumnSet.contains(tempcolumn))
  8347. {
  8348. int replicationcolumn;
  8349. foreach(replicationcolumn, currentColumnSet)
  8350. {
  8351. if(replicationcolumn != tempcolumn)
  8352. {
  8353. if(lastMeasurement.contains(replicationcolumn))
  8354. {
  8355. if(measure.time() > lastMeasurement.value(replicationcolumn).time())
  8356. {
  8357. Measurement synthetic = lastMeasurement.value(replicationcolumn);
  8358. synthetic.setTime(measure.time());
  8359. model_ms->newMeasurement(synthetic, replicationcolumn);
  8360. if(synthetic.time().second() != lastMeasurement.value(replicationcolumn).time().second())@/
  8361. {
  8362. Measurement adjusted = synthetic;
  8363. adjusted.setTime(QTime(0, synthetic.time().minute(), synthetic.time().second(), 0));
  8364. model_1s->newMeasurement(adjusted, replicationcolumn);
  8365. if(adjusted.time().second() % 5 == 0)
  8366. {
  8367. model_5s->newMeasurement(adjusted, replicationcolumn);
  8368. if(adjusted.time().second() % 10 == 0)
  8369. {
  8370. model_10s->newMeasurement(adjusted, replicationcolumn);
  8371. }
  8372. if(adjusted.time().second() % 15 == 0)
  8373. {
  8374. model_15s->newMeasurement(adjusted, replicationcolumn);
  8375. if(adjusted.time().second() % 30 == 0)
  8376. {
  8377. model_30s->newMeasurement(adjusted, replicationcolumn);
  8378. if(adjusted.time().second() == 0)
  8379. {
  8380. model_1m->newMeasurement(adjusted, replicationcolumn);
  8381. }
  8382. }
  8383. }
  8384. }
  8385. }
  8386. lastMeasurement[replicationcolumn] = synthetic;
  8387. }
  8388. }
  8389. }
  8390. }
  8391. }
  8392. @ Just as the first measurement should exist at every level of detail, so should
  8393. any annotations. The measurement models will, when presented with an annotation,
  8394. apply it to the most recently entered measurement in the specified data series.
  8395. This presents a problem for the coarser views as the data point the annotation
  8396. belongs to most likely does not exist in that view. Furthermore, the model as it
  8397. is currently written will overwrite annotations that already exist on a
  8398. measurement if it is still the most recently entered. When collecting samples
  8399. during profile development, it is common to produce several annotations in a
  8400. short amount of time. The most useful thing to do in such a case is to add the
  8401. most recent measurement to each model and then apply the annotation. This, of
  8402. course, should only be done if there is a most recent measurement. An annotation
  8403. regarding the starting condition of the roaster should apply to the yet to be
  8404. recorded time zero measurement.
  8405. Note that only the value from the temperature column specified is displayed in
  8406. the row with the annotation. It would be better to check the full detail model
  8407. to determine if there are other measurements at the annotation time and present
  8408. these as well. Another possibility in the case of data not existing in other
  8409. temperature columns would be to interpolate a value from the existing data in
  8410. these columns, however this is potentially challenging as I would want to keep
  8411. true measurements distinct from estimations.
  8412. @<ZoomLog Implementation@>=
  8413. void ZoomLog::newAnnotation(QString annotation, int tempcolumn,
  8414. int annotationcolumn)
  8415. {
  8416. model_ms->newAnnotation(annotation, tempcolumn, annotationcolumn);
  8417. MeasurementModel *m;
  8418. if(lastMeasurement.contains(tempcolumn))
  8419. {
  8420. foreach(m, modelSet)
  8421. {
  8422. m->newMeasurement(lastMeasurement.value(tempcolumn), tempcolumn);
  8423. }
  8424. }
  8425. foreach(m, modelSet)
  8426. {
  8427. m->newAnnotation(annotation, tempcolumn, annotationcolumn);
  8428. }
  8429. }
  8430. @ As measurements are added to the model, the model will emit rowChanged
  8431. signals. These signals are connected to a function here that will attempt to
  8432. scroll the view to keep the most recently entered data in the center of the
  8433. view.
  8434. @<ZoomLog Implementation@>=
  8435. void ZoomLog::centerOn(int row)
  8436. {
  8437. scrollTo(currentModel->index(row, 0), QAbstractItemView::PositionAtCenter);
  8438. }
  8439. @ Once we are done with the data in the table, we want to clear it to prepare
  8440. for new data. This also clears the lists holding the output columns to use when
  8441. saving data.
  8442. @<ZoomLog Implementation@>=
  8443. void ZoomLog::clear()
  8444. {
  8445. MeasurementModel *m;
  8446. foreach(m, modelSet)
  8447. {
  8448. m->clear();
  8449. }
  8450. lastMeasurement.clear();
  8451. saveTempCols.clear();
  8452. saveControlCols.clear();
  8453. saveNoteCols.clear();
  8454. }
  8455. @ These are depreciated methods originally written to assist in serializing
  8456. model data prior to the introduction of the |XMLOutput| class. These methods are
  8457. likely to be removed in a future version of the program.
  8458. @<ZoomLog Implementation@>=
  8459. QVariant ZoomLog::data(int row, int column) const
  8460. {
  8461. return model_ms->data(model_ms->index(row, column, QModelIndex()),
  8462. Qt::DisplayRole);
  8463. }
  8464. int ZoomLog::rowCount()
  8465. {
  8466. return model_ms->rowCount();
  8467. }
  8468. @ This method initializes an |XMLOutput| instance, passes the columns that we
  8469. would like to save to that object, and uses it to write an XML file with the
  8470. desired data to the specified device.
  8471. Since the output format does not currently specify a unit, there is an
  8472. assumption that the XML output will always have measurements in Fahrenheit. If
  8473. the model is not currently displaying measurements in Fahrenheit, it is asked to
  8474. do so before writing the XML data. User preference is restored after the XML
  8475. data has been written. Since this change is only performed on |model_ms|, most
  8476. users will never notice this.
  8477. @<ZoomLog Implementation@>=
  8478. bool ZoomLog::saveXML(QIODevice *device)
  8479. {
  8480. Units::Unit prevUnits = model_ms->displayUnits();
  8481. if(prevUnits != Units::Fahrenheit)
  8482. {
  8483. model_ms->setDisplayUnits(Units::Fahrenheit);
  8484. }
  8485. XMLOutput writer(model_ms, device, 0);
  8486. int c;
  8487. foreach(c, saveTempCols)
  8488. {
  8489. writer.addTemperatureColumn(model_ms->headerData(c, Qt::Horizontal).
  8490. toString(), c);
  8491. }
  8492. foreach(c, saveControlCols)
  8493. {
  8494. writer.addControlColumn(model_ms->headerData(c, Qt::Horizontal).
  8495. toString(), c);
  8496. }
  8497. foreach(c, saveNoteCols)
  8498. {
  8499. writer.addAnnotationColumn(model_ms->headerData(c, Qt::Horizontal).
  8500. toString(), c);
  8501. }
  8502. bool retval = writer.output();
  8503. if(prevUnits != Units::Fahrenheit)
  8504. {
  8505. model_ms->setDisplayUnits(prevUnits);
  8506. }
  8507. return retval;
  8508. }
  8509. @ This method is similar to |saveXML()|. The main difference is that CSV data is
  8510. exported instead of XML.
  8511. @<ZoomLog Implementation@>=
  8512. bool ZoomLog::saveCSV(QIODevice *device)
  8513. {
  8514. CSVOutput writer(currentModel, device, 0);
  8515. int c;
  8516. foreach(c, saveTempCols)
  8517. {
  8518. writer.addTemperatureColumn(model_ms->headerData(c, Qt::Horizontal).
  8519. toString(), c);
  8520. }
  8521. foreach(c, saveControlCols)
  8522. {
  8523. writer.addControlColumn(model_ms->headerData(c, Qt::Horizontal).
  8524. toString(), c);
  8525. }
  8526. foreach(c, saveNoteCols)
  8527. {
  8528. writer.addAnnotationColumn(model_ms->headerData(c, Qt::Horizontal).
  8529. toString(), c);
  8530. }
  8531. return writer.output();
  8532. }
  8533. @ Several little functions, all alike\nfnote{If you get the reference, you may
  8534. enjoy reading another \cweb{} program:\par\indent\pdfURL{%
  8535. http://www-cs-staff.stanford.edu/$\sim$uno/programs/advent.w.gz}
  8536. {http://www-cs-staff.stanford.edu/~uno/programs/advent.w.gz}}, are used to
  8537. switch the view from one level of detail to another.
  8538. @<ZoomLog Implementation@>=
  8539. void ZoomLog::switchLOD(MeasurementModel *m)
  8540. {
  8541. disconnect(currentModel, SIGNAL(rowChanged(int)), this, 0);
  8542. setModel(m);
  8543. currentModel = m;
  8544. connect(currentModel, SIGNAL(rowChanged(int)), this, SLOT(centerOn(int)));
  8545. }
  8546. void ZoomLog::LOD_ms()
  8547. {
  8548. switchLOD(model_ms);
  8549. }
  8550. void ZoomLog::LOD_1s()
  8551. {
  8552. switchLOD(model_1s);
  8553. }
  8554. void ZoomLog::LOD_5s()
  8555. {
  8556. switchLOD(model_5s);
  8557. }
  8558. void ZoomLog::LOD_10s()
  8559. {
  8560. switchLOD(model_10s);
  8561. }
  8562. void ZoomLog::LOD_15s()
  8563. {
  8564. switchLOD(model_15s);
  8565. }
  8566. void ZoomLog::LOD_30s()
  8567. {
  8568. switchLOD(model_30s);
  8569. }
  8570. void ZoomLog::LOD_1m()
  8571. {
  8572. switchLOD(model_1m);
  8573. }
  8574. @ It can be useful to display temperature measurements in various units. To do
  8575. so, we simply tell all of the models which unit to provide data in. It is also
  8576. possible to obtain the currently selected unit.
  8577. @<ZoomLog Implementation@>=
  8578. void ZoomLog::setDisplayUnits(Units::Unit scale)
  8579. {
  8580. model_ms->setDisplayUnits(scale);
  8581. model_1s->setDisplayUnits(scale);
  8582. model_5s->setDisplayUnits(scale);
  8583. model_10s->setDisplayUnits(scale);
  8584. model_15s->setDisplayUnits(scale);
  8585. model_30s->setDisplayUnits(scale);
  8586. model_1m->setDisplayUnits(scale);
  8587. }
  8588. Units::Unit ZoomLog::displayUnits()
  8589. {
  8590. return model_ms->displayUnits();
  8591. }
  8592. @ For convenience, a method is provided for returning a string containing the
  8593. time of the last inserted measurement in a given data series.
  8594. @<ZoomLog Implementation@>=
  8595. QString ZoomLog::lastTime(int series)
  8596. {
  8597. Measurement measure = lastMeasurement.value(series);
  8598. QTime time = measure.time();
  8599. return time.toString("h:mm:ss.zzz");
  8600. }
  8601. @ This just leaves the initial table setup.
  8602. @<ZoomLog Implementation@>=
  8603. ZoomLog::ZoomLog() : QTableView(NULL), model_ms(new MeasurementModel(this)),
  8604. model_1s(new MeasurementModel(this)),@/ model_5s(new MeasurementModel(this)),
  8605. model_10s(new MeasurementModel(this)),@/ model_15s(new MeasurementModel(this)),
  8606. model_30s(new MeasurementModel(this)),@/ model_1m(new MeasurementModel(this))@/
  8607. {@/
  8608. setEditTriggers(QAbstractItemView::NoEditTriggers);
  8609. setSelectionMode(QAbstractItemView::NoSelection);
  8610. modelSet << model_ms << model_1s << model_5s << model_10s << model_15s <<
  8611. model_30s << model_1m;
  8612. currentModel = model_30s;
  8613. setModel(currentModel);
  8614. connect(currentModel, SIGNAL(rowChanged(int)), this, SLOT(centerOn(int)));
  8615. connect(horizontalHeader(), SIGNAL(sectionResized(int, int, int)),
  8616. this, SLOT(persistColumnResize(int, int, int)));
  8617. connect(horizontalHeader(), SIGNAL(sectionCountChanged(int, int)),
  8618. this, SLOT(restoreColumnWidths()));
  8619. }
  8620. @ A new method was added to this class for version 1.0.7. This allows header
  8621. data to be set on the log and have it propagate to the model set. The longer
  8622. term plan involves removing the hard coding of some of the header data.
  8623. @<ZoomLog Implementation@>=
  8624. void ZoomLog::setHeaderData(int section, QString text)
  8625. {
  8626. MeasurementModel *m;
  8627. foreach(m, modelSet)
  8628. {
  8629. m->setHeaderData(section, Qt::Horizontal, QVariant(text));
  8630. }
  8631. }
  8632. @ As of version 1.2.3, these methods replace similar methods added for version
  8633. 1.0.8. The main difference is that it is now possible to save multiple data
  8634. series to the same output document.
  8635. Starting in version 1.6 it is possible to save control columns. These should
  8636. contain unitless data which should remain unaffected by the current displayed
  8637. unit.
  8638. @<ZoomLog Implementation@>=
  8639. void ZoomLog::addOutputTemperatureColumn(int column)
  8640. {
  8641. saveTempCols.append(column);
  8642. }
  8643. void ZoomLog::addOutputControlColumn(int column)
  8644. {
  8645. saveControlCols.append(column);
  8646. }
  8647. void ZoomLog::addOutputAnnotationColumn(int column)
  8648. {
  8649. saveNoteCols.append(column);
  8650. }
  8651. void ZoomLog::clearOutputColumns()
  8652. {
  8653. saveTempCols.clear();
  8654. saveControlCols.clear();
  8655. saveNoteCols.clear();
  8656. }
  8657. @ Starting in version 1.4 two methods have been introduced which are used to
  8658. save and restore column widths.
  8659. @<ZoomLog Implementation@>=
  8660. void ZoomLog::persistColumnResize(int column, int, int newsize)
  8661. {
  8662. @<Save updated column size@>@;
  8663. }
  8664. void ZoomLog::restoreColumnWidths()
  8665. {
  8666. @<Restore table column widths@>@;
  8667. }
  8668. void ZoomLog::setVisible(bool visibility)
  8669. {
  8670. QTableView::setVisible(visibility);
  8671. }
  8672. void ZoomLog::showEvent(QShowEvent *)
  8673. {
  8674. @<Restore table column widths@>@;
  8675. }
  8676. @ The |ZoomLog| class is one of the more complicated classes to expose to the
  8677. scripting engine. In addition to a script constructor, we also need functions
  8678. for saving and restoring the state of the display and functions for saving data
  8679. from the log in the supported formats.
  8680. @<Function prototypes for scripting@>=
  8681. void setZoomLogProperties(QScriptValue value, QScriptEngine *engine);
  8682. QScriptValue constructZoomLog(QScriptContext *context, QScriptEngine *engine);
  8683. QScriptValue ZoomLog_saveXML(QScriptContext *context, QScriptEngine *engine);
  8684. QScriptValue ZoomLog_saveCSV(QScriptContext *context, QScriptEngine *engine);
  8685. QScriptValue ZoomLog_saveState(QScriptContext *context, QScriptEngine *engine);
  8686. QScriptValue ZoomLog_restoreState(QScriptContext *context,
  8687. QScriptEngine *engine);
  8688. QScriptValue ZoomLog_lastTime(QScriptContext *context, QScriptEngine *engine);
  8689. QScriptValue ZoomLog_saveTemporary(QScriptContext *context,
  8690. QScriptEngine *engnie);
  8691. QScriptValue ZoomLog_setDisplayUnits(QScriptContext *context,
  8692. QScriptEngine *engine);
  8693. @ Of these, the global object only needs to know about the constructor.
  8694. @<Set up the scripting engine@>=
  8695. constructor = engine->newFunction(constructZoomLog);
  8696. value = engine->newQMetaObject(&ZoomLog::staticMetaObject, constructor);
  8697. engine->globalObject().setProperty("ZoomLog", value);
  8698. @ The script constructor sets properties on the newly created object to allow
  8699. the other functions to be called.
  8700. @<Functions for scripting@>=
  8701. QScriptValue constructZoomLog(QScriptContext *, QScriptEngine *engine)@/
  8702. {@/
  8703. QScriptValue object = engine->newQObject(new ZoomLog);
  8704. setZoomLogProperties(object, engine);
  8705. return object;@/
  8706. }
  8707. void setZoomLogProperties(QScriptValue value, QScriptEngine *engine)
  8708. {
  8709. setQTableViewProperties(value, engine);
  8710. value.setProperty("saveXML", engine->newFunction(ZoomLog_saveXML));
  8711. value.setProperty("saveCSV", engine->newFunction(ZoomLog_saveCSV));
  8712. value.setProperty("saveState", engine->newFunction(ZoomLog_saveState));
  8713. value.setProperty("restoreState",
  8714. engine->newFunction(ZoomLog_restoreState));
  8715. value.setProperty("lastTime", engine->newFunction(ZoomLog_lastTime));
  8716. value.setProperty("saveTemporary",
  8717. engine->newFunction(ZoomLog_saveTemporary));
  8718. value.setProperty("setDisplayUnits", engine->newFunction(ZoomLog_setDisplayUnits));
  8719. }
  8720. @ The functions for saving data are simple wrappers around the corresponding
  8721. calls in |ZoomLog|, except for a function added for saving data to a temporary
  8722. file. The last provides the name of the file saved for use in copying that data
  8723. to a database entry.
  8724. @<Functions for scripting@>=
  8725. QScriptValue ZoomLog_saveXML(QScriptContext *context, QScriptEngine *engine)
  8726. {
  8727. ZoomLog *self = getself<ZoomLog *>(context);
  8728. bool retval = self->saveXML(argument<QIODevice *>(0, context));
  8729. return QScriptValue(engine, retval);
  8730. }
  8731. QScriptValue ZoomLog_saveCSV(QScriptContext *context, QScriptEngine *engine)
  8732. {
  8733. ZoomLog *self = getself<ZoomLog *>(context);
  8734. bool retval = self->saveCSV(argument<QIODevice *>(0, context));
  8735. return QScriptValue(engine, retval);
  8736. }
  8737. QScriptValue ZoomLog_saveTemporary(QScriptContext *context,
  8738. QScriptEngine *engine)
  8739. {
  8740. ZoomLog *self = getself<ZoomLog *>(context);
  8741. QString filename = QDir::tempPath();
  8742. filename.append("/");
  8743. filename.append(QUuid::createUuid().toString());
  8744. filename.append(".xml");
  8745. QFile *file = new QFile(filename);
  8746. self->saveXML(file);
  8747. file->close();
  8748. delete file;
  8749. return QScriptValue(engine, filename);
  8750. }
  8751. @ The remaining functions are convenience functions for use with the scripting
  8752. engine. One will save the column widths to a |QSettings| object. Another will
  8753. restore the column widths from settings. Finally, there is a function for
  8754. obtaining a string representation of the most recent measurement from a data
  8755. series.
  8756. \danger There are a couple of problems with these functions. First, the body of
  8757. these functions would probably be better off as methods in the |ZoomLog| class
  8758. proper, either as slots or |Q_INVOKABLE| so the special scripting functions
  8759. could be eliminated. Second, rather than polluting the settings with separate
  8760. entries for each column, it would probably be better to store all of these
  8761. values in an array.\endanger
  8762. |ZoomLog_saveState()| was changed in version 1.2.3 to not save a new value for
  8763. the column width if that width is |0|. This was done mainly to ease debugging.
  8764. Similarly, |ZoomLog_restoreState()| picks a new default value when |0| is
  8765. encountered.
  8766. @<Functions for scripting@>=
  8767. QScriptValue ZoomLog_saveState(QScriptContext *context, QScriptEngine *)
  8768. {
  8769. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  8770. QString key = argument<QString>(0, context);
  8771. int columns = argument<int>(1, context);
  8772. QSettings settings;
  8773. for(int i = 0; i < columns; i++)
  8774. {
  8775. if(self->columnWidth(i))
  8776. {
  8777. settings.beginGroup(key);
  8778. settings.setValue(QString("%1").arg(i), self->columnWidth(i));
  8779. settings.endGroup();
  8780. }
  8781. }
  8782. return QScriptValue();
  8783. }
  8784. QScriptValue ZoomLog_restoreState(QScriptContext *context, QScriptEngine *)
  8785. {
  8786. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  8787. QString key = argument<QString>(0, context);
  8788. int columns = argument<int>(1, context);
  8789. QSettings settings;
  8790. for(int i = 0; i < columns; i++)
  8791. {
  8792. settings.beginGroup(key);
  8793. self->setColumnWidth(i,
  8794. settings.value(QString("%1").arg(i), 80).toInt());
  8795. if(settings.value(QString("%1").arg(i), 80).toInt() == 0)
  8796. {
  8797. self->setColumnWidth(i, 80);
  8798. }
  8799. settings.endGroup();
  8800. }
  8801. return QScriptValue();
  8802. }
  8803. QScriptValue ZoomLog_lastTime(QScriptContext *context, QScriptEngine *engine)
  8804. {
  8805. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  8806. return QScriptValue(engine, self->lastTime(argument<int>(0, context)));
  8807. }
  8808. @ There seems to be a bad interaction when enumerated value types as used as
  8809. the argument to slot methods called through QtScript. Script code that attempts
  8810. to make use of the enumeration appears to get the value without any type
  8811. information. When attempting to use that value as an argument the meta-object
  8812. system cannot find an appropriate match and the script just hangs silently.
  8813. The solution is to wrap such methods in the script bindings and explicitly cast
  8814. the argument value to the enumerated type. This looks stupid but it works.
  8815. @<Functions for scripting@>=
  8816. QScriptValue ZoomLog_setDisplayUnits(QScriptContext *context, QScriptEngine *)
  8817. {
  8818. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  8819. self->setDisplayUnits((Units::Unit)argument<int>(0, context));
  8820. return QScriptValue();
  8821. }
  8822. @* A model for roasting data.
  8823. \noindent Qt provides a tool called the model view architecture. This provides a
  8824. uniform interface allowing different types of model classes to work with
  8825. different types of view classes without either needing to know implementation
  8826. details of the other. \pn{} provides the |MeasurementModel| as a specialization
  8827. of |QAbstractItemModel| for use in this architecture.
  8828. @<Class declarations@>=
  8829. class MeasurementList;@/
  8830. class MeasurementModel : public QAbstractItemModel@/
  8831. {@t\1@>@/
  8832. Q_OBJECT@;
  8833. Units::Unit unit;
  8834. QList<MeasurementList *> *entries;
  8835. QStringList *hData;
  8836. int colcount;
  8837. QHash<int, int> *lastTemperature;
  8838. QList<MeasurementList *>::iterator@, lastInsertion;
  8839. QHash<int, bool> *controlColumns;
  8840. public:@/
  8841. MeasurementModel(QObject *parent = NULL);
  8842. ~MeasurementModel();
  8843. int rowCount(const QModelIndex &parent = QModelIndex()) const;
  8844. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  8845. bool setHeaderData(int section, Qt::Orientation orientation,
  8846. const QVariant &value,@|int role = Qt::DisplayRole);
  8847. QVariant data(const QModelIndex &index, int role) const;
  8848. bool setData(const QModelIndex &index, const QVariant &value,
  8849. int role = Qt::EditRole);
  8850. Qt::ItemFlags flags(const QModelIndex &index) const;
  8851. QVariant headerData(int section, Qt::Orientation orientation,
  8852. int role = Qt::DisplayRole) const;
  8853. QModelIndex index(int row, int column,
  8854. const QModelIndex &parent = QModelIndex()) const;
  8855. QModelIndex parent(const QModelIndex &index) const;
  8856. Units::Unit displayUnits();@/
  8857. @t\4@>public slots@t\kern-3pt@>:@/
  8858. void newMeasurement(Measurement measure, int tempcolumn);
  8859. void newAnnotation(QString annotation, int tempcolumn,
  8860. int annotationColumn);
  8861. void clear();
  8862. void setDisplayUnits(Units::Unit scale);
  8863. signals:@/
  8864. void rowChanged(int);@t\2@>@/
  8865. }@t\kern-3pt@>;
  8866. @ The measurement model stores its data in a list of measurement lists. This
  8867. allows the model to store as many sets of data as needed. In order to keep
  8868. measurements in the model sorted by time, the measurement list adds two
  8869. comparison functions.
  8870. @<Class declarations@>=
  8871. class MeasurementList : public QVariantList@/
  8872. {@t\1@>@/
  8873. @t\4@>public:@/
  8874. bool operator<(const MeasurementList &other) const;
  8875. bool operator==(const MeasurementList &other) const;@t\2@>@/
  8876. }@t\kern-3pt@>;
  8877. @ The overload of |<| checks if the time in one list (always stored in the first
  8878. column) is less than the time stored in the second. The overload of |==| is used
  8879. in an optimization that allows us to skip the search procedure on model
  8880. insertion.
  8881. @<MeasurementModel Implementation@>=
  8882. bool MeasurementList::operator<(const MeasurementList &other) const
  8883. {
  8884. return this->first().toTime() < other.first().toTime();
  8885. }
  8886. bool MeasurementList::operator==(const MeasurementList &other) const
  8887. {
  8888. return this->first().toTime() == other.first().toTime();
  8889. }
  8890. @ The |MeasurementModel| class extends the |QAbstractItemModel| class to work
  8891. better with measurements and annotations that are passed around in \pn{}. Many
  8892. of the class methods are required because of that choice. For example, the
  8893. parent function which is never used directly:
  8894. @<MeasurementModel Implementation@>=
  8895. QModelIndex MeasurementModel::parent(const QModelIndex&) const
  8896. {
  8897. return QModelIndex();
  8898. }
  8899. @ Perhaps the most complicated part of this class is the code for dealing with a
  8900. new measurement. This is complicated by the requirement to insert measurements
  8901. while keeping the model sorted by time.
  8902. @<MeasurementModel Implementation@>=
  8903. void MeasurementModel::newMeasurement(Measurement measure, int tempcolumn)
  8904. {
  8905. if(measure.scale() == Units::Unitless)
  8906. {
  8907. controlColumns->insert(tempcolumn, true);
  8908. }
  8909. else
  8910. {
  8911. controlColumns->insert(tempcolumn, false);
  8912. }
  8913. MeasurementList *temp;
  8914. temp = new MeasurementList;
  8915. temp->append(QVariant(measure.time()));
  8916. @<Find the insertion point@>@;
  8917. MeasurementList *newEntry;
  8918. int insertion;
  8919. if(i != entries->end())
  8920. {
  8921. insertion = entries->indexOf(*i);
  8922. if((*i)->first().toTime() == measure.time())
  8923. {
  8924. @<Insert a new measurement at an existing time@>@;
  8925. }
  8926. else
  8927. {
  8928. @<Insert a new measurement somewhere else@>@;
  8929. }
  8930. }
  8931. else
  8932. {
  8933. @<Append a measurement@>@;
  8934. }
  8935. if(tempcolumn >= colcount)
  8936. {
  8937. colcount = tempcolumn + 1;
  8938. }
  8939. emit rowChanged(insertion);
  8940. delete temp;
  8941. }
  8942. @ To find the insertion point for new measurements we use a binary search of the
  8943. existing data. The code below is a direct adaptation of Program B\nfnote{%
  8944. \underbar{The Art of Computer Programming} Volume 3 Sorting and Searching 2nd
  8945. ed. (Knuth, 1997) Section 6.2.1: Searching an Ordered Table} modified to use
  8946. list iterators and control structures more familiar to \CPLUSPLUS/programmers
  8947. rather than {\mc MIX} machine codes. When the loop exits |i| is the insertion
  8948. point.
  8949. \medskip
  8950. \centerline{\includegraphics{search}}
  8951. \smallskip
  8952. \centerline{Figure \secno: Binary Search}
  8953. \medskip
  8954. @<Find the insertion point@>=
  8955. @<Scan from most recent insertion@>@;
  8956. if(quickscan == false)
  8957. {
  8958. i = entries->begin();
  8959. QList<MeasurementList *>::iterator@, u = entries->end();
  8960. QList<MeasurementList *>::iterator@, midpoint;
  8961. int n = u - i;
  8962. int rA;
  8963. while(n > 0)@/
  8964. {
  8965. rA = n>>1; /* |rA = |~$\bigl\lfloor{n\over2}\bigr\rfloor$ */
  8966. midpoint = i + rA;
  8967. if(**midpoint < *temp)@/
  8968. {
  8969. i = midpoint + 1;
  8970. n -= rA + 1;
  8971. }
  8972. else@/
  8973. {
  8974. n = rA;
  8975. }
  8976. }
  8977. }
  8978. @ The binary search, while correct, is not a particularly optimal choice for
  8979. this application. While the average running time for this is on the order of
  8980. $\ln N$ when each insertion point is equally likely, the reality of this
  8981. application is that insertions will likely be at the beginning of the list, at
  8982. the point of the most recent insertion, or a short distance from the most recent
  8983. insertion. By first considering the possibility that the measurement should be
  8984. inserted at or near the most recent measurement, shorter, more constant running
  8985. times as $N$ increases can be obtained.
  8986. To do this, when the number of measurements in the list is above a small number
  8987. which must be greater than 1, we check first if the insertion point is at the
  8988. last insertion (the |<| comparison fails and we do an |==| comparison before
  8989. giving up), then we check a small number of rows for either the end of the list,
  8990. in which case the insertion point is at the end, or for a point at which the |<|
  8991. comparison fails. If neither condition holds for a small number of comparisons
  8992. we resort to the binary search.
  8993. Performance measurements with this modification compared with previous versions
  8994. shows that this provides a huge performance boost.
  8995. @<Scan from most recent insertion@>=
  8996. @[QList<MeasurementList *>::iterator@, i@] = lastInsertion;@/
  8997. bool quickscan = false;@/
  8998. if(entries->size() > 5)@/
  8999. {@t\1@>@/
  9000. if(**i < *temp)@/
  9001. {@t\1@>@/
  9002. i += 1;@/
  9003. for(int j = 10; j > 0; j--)@/
  9004. {@t\1@>@/
  9005. if(i != entries->end())@/
  9006. {@t\1@>@/
  9007. if(**i < *temp)@/
  9008. {
  9009. i += 1;
  9010. }@/
  9011. else@/
  9012. {@t\1@>@/
  9013. quickscan = true;
  9014. break;@t\2@>@/
  9015. }@t\2@>@/
  9016. }@/
  9017. else@/
  9018. {@t\1@>@/
  9019. quickscan = true;
  9020. break;@t\2@>@/
  9021. }@t\2@>@/
  9022. }@t\2@>@/
  9023. }@/
  9024. else@/
  9025. {@t\1@>@/
  9026. if(**i == *temp)@/
  9027. {@t\1@>@/
  9028. quickscan = true;@t\2@>@/
  9029. }@t\2@>@/
  9030. }@t\2@>@/
  9031. }
  9032. @ If the chosen insertion point is at an existing time, we don'@q'@>t need to
  9033. worry about inserting rows. There may be a need to increase the size of the
  9034. measurement list to accept an entry in a new data series.
  9035. @<Insert a new measurement at an existing time@>=
  9036. if((*i)->size() < tempcolumn + 1)
  9037. {
  9038. for(int j = (*i)->size() - 1; j < tempcolumn + 1; j++)
  9039. {
  9040. (*i)->append(QVariant());
  9041. }
  9042. }
  9043. (*i)->replace(tempcolumn, measure);
  9044. lastInsertion = i;
  9045. emit dataChanged(createIndex(insertion, tempcolumn),
  9046. createIndex(insertion, tempcolumn));
  9047. lastTemperature->insert(tempcolumn, insertion);
  9048. @ If the measurement is not past the end of the existing data and the insertion
  9049. point has a different time, we need to use |beginInsertRows()| and
  9050. |endInsertRows()| to notify any attached view that a new row will be added.
  9051. @<Insert a new measurement somewhere else@>=
  9052. beginInsertRows(QModelIndex(), insertion, insertion);
  9053. newEntry = new MeasurementList;
  9054. newEntry->append(QVariant(measure.time()));
  9055. for(int j = 0; j < tempcolumn + 1; j++)
  9056. {
  9057. newEntry->append(QVariant());
  9058. }
  9059. newEntry->replace(tempcolumn, measure);
  9060. lastInsertion = entries->insert(i, newEntry);
  9061. endInsertRows();
  9062. lastTemperature->insert(tempcolumn, insertion);
  9063. @ If the insertion point is past the end of the existing data, a new row should
  9064. be appended to the data. This only needs to be a separate case to prevent the
  9065. comparison with a nonexistent entry. This is very similar to the case of
  9066. inserting at a new time anywhere else.
  9067. @<Append a measurement@>=
  9068. insertion = entries->size();@/
  9069. @<Insert a new measurement somewhere else@>
  9070. @ The other bit of code that'@q'@>s a little bit more complicated than other
  9071. parts of the class handles adding annotations to the data. Two signals are
  9072. emitted in this method. The |dataChanged| signal is expected by view classes
  9073. that can use this model. The |rowChanged| signal is used by |ZoomLog| to scroll
  9074. the view to the row the annotation has been added to. This is mainly useful
  9075. when loading a target profile and entering the first annotation prior to
  9076. starting the batch.
  9077. @<MeasurementModel Implementation@>=
  9078. void MeasurementModel::newAnnotation(QString annotation, int tempcolumn,@|
  9079. int annotationColumn)
  9080. {
  9081. int r;
  9082. if(lastTemperature->contains(tempcolumn))
  9083. {
  9084. r = lastTemperature->value(tempcolumn);
  9085. }
  9086. else
  9087. {
  9088. r = 0;
  9089. }
  9090. if(r == 0 && entries->size() == 0)
  9091. {
  9092. @<Create the first row@>@;
  9093. }
  9094. MeasurementList *row = entries->at(r);
  9095. if(row->size() <= annotationColumn)
  9096. {
  9097. for(int i = row->size() - 1; i < annotationColumn + 1; i++)
  9098. {
  9099. row->append(QVariant());
  9100. }
  9101. }
  9102. row->replace(annotationColumn, annotation);
  9103. emit dataChanged(createIndex(r, annotationColumn),
  9104. createIndex(r, annotationColumn));
  9105. emit rowChanged(r);
  9106. if(annotationColumn > colcount - 1)
  9107. {
  9108. colcount = annotationColumn + 1;
  9109. }
  9110. }
  9111. @ There is no need to further complicate the function by adding the annotation
  9112. when the first row is created.
  9113. @<Create the first row@>=
  9114. beginInsertRows(QModelIndex(), 0, 0);
  9115. MeasurementList *newEntry = new MeasurementList;
  9116. newEntry->append(QVariant(QTime(0, 0, 0, 0)));
  9117. entries->append(newEntry);
  9118. endInsertRows();
  9119. @ Clearing the model data is a simple matter of deleting every row, remembering
  9120. to let any attached views know that we are doing this, and resetting the number
  9121. of columns.
  9122. @<MeasurementModel Implementation@>=
  9123. void MeasurementModel::clear()
  9124. {
  9125. beginRemoveRows(QModelIndex(), 0, entries->size());
  9126. while(entries->size() != 0)
  9127. {
  9128. MeasurementList *row = entries->takeFirst();
  9129. delete row;
  9130. }
  9131. endRemoveRows();
  9132. colcount = hData->size();
  9133. lastTemperature->clear();
  9134. reset();
  9135. }
  9136. @ While these methods for adding measurements and annotations are fine when
  9137. recording a stream of measurements, either from the |DAQ| or when loading saved
  9138. data, there are also cases where we'@q'@>d like to edit the data in the model
  9139. directly from the table view. For this, we need to reimplement |setData()|.
  9140. Note that editing from the |ZoomLog| has never been supported. While stream
  9141. inserted data currently preserves all properties of inserted measurements,
  9142. using |setData| it is possible to insert a numeric value as if it were a
  9143. measurement. Such an entry will not have any additional information associated
  9144. and cannot be expected to exhibit behavior implemented through the use of that
  9145. extra information.
  9146. Very little input checking is done here. Editable views may want to place
  9147. delegates\nfnote{Qt 4.4: Delegate Classes\par\indent\hbox{%
  9148. \pdfURL{http://doc.trolltech.com/4.4/model-view-delegate.html}{%
  9149. http://doc.trolltech.com/4.4/model-view-delegate.html}}} on the columns to make
  9150. editing the data easier and less error prone.
  9151. @<MeasurementModel Implementation@>=
  9152. bool MeasurementModel::setData(const QModelIndex &index,
  9153. const QVariant &value, int role)@t\2\2@>@/
  9154. {@t\1@>@/
  9155. if(role != Qt::EditRole && role != Qt::DisplayRole)@/
  9156. {@t\1@>@/
  9157. return false;@t\2@>@/
  9158. }@/
  9159. @<Check that the index is valid@>@;
  9160. if(!valid)@/
  9161. {@t\1@>@/
  9162. return false;@t\2@>@/
  9163. }@/
  9164. MeasurementList *row = entries->at(index.row());
  9165. if(index.column() >= row->size())
  9166. {
  9167. @<Expand the row to prepare for new data@>@;
  9168. }
  9169. if(index.column() == 0)
  9170. {
  9171. @<Edit data in the time column@>@;
  9172. }
  9173. else
  9174. {
  9175. @<Edit data in other columns@>@;
  9176. }
  9177. return true;@t\2@>@/
  9178. }
  9179. @ There is no sense in attempting to edit the data if there isn'@q'@>t any data
  9180. available to edit. This check is also used when retrieving data from the model.
  9181. @<Check that the index is valid@>=
  9182. bool valid = false;
  9183. if(index.isValid())@/
  9184. {@t\1@>@/
  9185. if(index.row() < entries->size())@/
  9186. {@t\1@>@/
  9187. if(index.column() < colcount)@/
  9188. {@t\1@>@/
  9189. valid = true;@t\2@>@/
  9190. }@t\2@>@/
  9191. }@t\2@>@/
  9192. }
  9193. @ When editing data, there might not be anything where we want to add the data.
  9194. For example, adding an annotation to an otherwise unannotated measurement. This
  9195. is fine, but we need to expand the row instead of inserting data out of bounds.
  9196. @<Expand the row to prepare for new data@>=
  9197. for(int i = row->size() - 1; i < index.column(); i++)
  9198. {
  9199. row->append(QVariant());
  9200. }
  9201. @ Changing time data must be considered separately from other data. As the model
  9202. keeps itself sorted based on the time field, allowing the user to get the model
  9203. data out of order would result in poorly defined behavior later. Our approach is
  9204. to remove the row from the model temporarily then reuse the code from
  9205. |newMeasurement()| to find the new insertion point. No attempt is made to merge
  9206. the contents from two rows with identical times, but an attempt is made to not
  9207. be too rigid in what we expect the user to enter. If an invalid time is entered,
  9208. we give up and leave the data as we found it.
  9209. @<Edit data in the time column@>=
  9210. QTime time;@/
  9211. if(!(time = QTime::fromString(value.toString(), "m:s.z")).isValid())@/
  9212. {@t\1@>@/
  9213. if(!(time = QTime::fromString(value.toString(), "m:s")).isValid())@/
  9214. {@t\1@>@/
  9215. return false;@t\2@>@/
  9216. }@t\2@>@/
  9217. }@/
  9218. row = entries->takeAt(index.row());
  9219. row->replace(index.column(), QVariant(time));
  9220. MeasurementList *temp = row;
  9221. @<Find the insertion point@>@;
  9222. entries->insert(i, row);
  9223. int newRow = entries->indexOf(*i);
  9224. if(newRow < index.row())@/
  9225. {
  9226. emit dataChanged(createIndex(newRow, index.column()), index);
  9227. }
  9228. else@/
  9229. {
  9230. emit dataChanged(index, createIndex(newRow, index.column()));
  9231. }
  9232. @ Data in other columns is a little easier to handle.
  9233. @<Edit data in other columns@>=
  9234. row->replace(index.column(), value);
  9235. emit dataChanged(index, index);
  9236. @ As it has already been established that the first column is always considered
  9237. the time of the measurement, this assumption can be built into the model
  9238. constructor.
  9239. @<MeasurementModel Implementation@>=
  9240. MeasurementModel::MeasurementModel(QObject *parent) : QAbstractItemModel(parent),
  9241. unit(Units::Fahrenheit), hData(new QStringList),
  9242. lastTemperature(new QHash<int, int>),
  9243. controlColumns(new QHash<int, bool>)@/
  9244. {
  9245. colcount = 1;
  9246. entries = new QList<MeasurementList *>;
  9247. lastInsertion = entries->begin();
  9248. hData->append(tr("Time"));
  9249. }
  9250. @ In the destructor we need to remember to clean up after ourselves.
  9251. @<MeasurementModel Implementation@>=
  9252. MeasurementModel::~MeasurementModel()
  9253. {
  9254. clear();
  9255. delete entries;
  9256. delete hData;
  9257. }
  9258. @ A pair of functions are used to determine the number of rows and columns the
  9259. model provides. No entries in the model have children, so the parent should
  9260. always be the invisible root object. If it isn'@q'@>t, we should return 0.
  9261. @<MeasurementModel Implementation@>=
  9262. int MeasurementModel::rowCount(const QModelIndex &parent) const
  9263. {
  9264. if(parent == QModelIndex())
  9265. {
  9266. return entries->size();
  9267. }
  9268. return 0;
  9269. }
  9270. int MeasurementModel::columnCount(const QModelIndex &parent) const
  9271. {
  9272. if(parent == QModelIndex())
  9273. {
  9274. return colcount;
  9275. }
  9276. return 0;
  9277. }
  9278. @ The model maintains a set of header data. At present, it only supports header
  9279. data at the top of the model due to the author'@q'@>s preference to not have row
  9280. numbers littering the left of the table (the time column is sufficient to
  9281. identify the row for the user).
  9282. The model view architecture supports the concept of different data roles in the
  9283. header data. At present, this model ignores the role when setting header data.
  9284. @<MeasurementModel Implementation@>=
  9285. bool MeasurementModel::setHeaderData(int section, Qt::Orientation orientation,@|
  9286. const QVariant &value, int)@t\2@>@/
  9287. @t\4@>{@/
  9288. if(orientation == Qt::Horizontal)@/
  9289. {@t\1@>@/
  9290. if(hData->size() < section + 1)@/
  9291. {@/
  9292. for(int i = hData->size(); i < section + 1; i++)@/
  9293. {@/
  9294. if(colcount < i)@/
  9295. {@/
  9296. beginInsertColumns(QModelIndex(), i, i);
  9297. }
  9298. hData->append(QString());
  9299. if(colcount < i)@/
  9300. {@/
  9301. endInsertColumns();
  9302. }
  9303. }
  9304. }
  9305. hData->replace(section, value.toString());
  9306. emit headerDataChanged(orientation, section, section);
  9307. if(colcount < section + 1)@/
  9308. {@/
  9309. colcount = section + 1;
  9310. }@/
  9311. return true;@t\2@>@/
  9312. }@/
  9313. return false;@/
  9314. @t\4@>}
  9315. @ While the current implementation always receives measurements in degrees
  9316. Fahrenheit, international users often want to see data presented in Celsius. To
  9317. do this, a slot is provided to allow selecting among different units. When this
  9318. method is called, the model indicates that all attached views must update all
  9319. displayed data and requests for temperature data will have any needed conversion
  9320. performed before sending that information to the view. Another method is
  9321. available to request a number identifyin the currently displayed units.
  9322. @<MeasurementModel Implementation@>=
  9323. void MeasurementModel::setDisplayUnits(Units::Unit scale)
  9324. {
  9325. beginResetModel();
  9326. unit = scale;
  9327. endResetModel();
  9328. }
  9329. Units::Unit MeasurementModel::displayUnits()
  9330. {
  9331. return unit;
  9332. }
  9333. @ A model is generally quite useless if the data the model contains cannot be
  9334. retrieved. To do this, we check that the index requested is a valid index that
  9335. is within the bounds of the model data and that a role we understand has been
  9336. requested. If none of these conditions are met, a default constructed |QVariant|
  9337. is returned.
  9338. At present, |Qt::DisplayRole| and |Qt::EditRole| are supported. These return the
  9339. same thing. Views will request the display role for presenting the information
  9340. to the user, but they will request the edit role if the user attempts to modify
  9341. the data through a view.
  9342. As of version 1.6, |Qt::UserRole| allows retrieval of raw measurement data.
  9343. @<MeasurementModel Implementation@>=
  9344. QVariant MeasurementModel::data(const QModelIndex &index, int role) const@/
  9345. {@/
  9346. @<Check that the index is valid@>@;
  9347. if(!valid)
  9348. {
  9349. return QVariant();
  9350. }
  9351. MeasurementList *row = entries->at(index.row());
  9352. if(role == Qt::UserRole)
  9353. {
  9354. return QVariant(row->at(index.column()));
  9355. }
  9356. if(role == Qt::DisplayRole || role == Qt::EditRole)
  9357. {
  9358. if(index.column() > row->size())
  9359. {
  9360. return QVariant();
  9361. }
  9362. else
  9363. {
  9364. if(index.column() == 0)
  9365. {
  9366. return QVariant(row->at(0).toTime().toString("mm:ss.zzz"));
  9367. }
  9368. else if(lastTemperature->contains(index.column()))
  9369. {
  9370. QVariantMap v = row->at(index.column()).toMap();
  9371. if(!v.contains("measurement"))
  9372. {
  9373. return QVariant();
  9374. }
  9375. if((Units::Unit)(v.value("unit").toInt()) == Units::Unitless)
  9376. {
  9377. return v.value("measurement");
  9378. }
  9379. else
  9380. {
  9381. if(v.contains("relative"))
  9382. {
  9383. if(v.value("relative").toBool())
  9384. {
  9385. return QVariant(QString("%1").@|arg(Units::convertRelativeTemperature(v.value("measurement").
  9386. toDouble(),@| (Units::Unit)(v.value("unit").toInt()), unit)));
  9387. }
  9388. }
  9389. return QVariant(QString("%1").@|
  9390. arg(Units::convertTemperature(v.value("measurement").toDouble(),@|
  9391. (Units::Unit)(v.value("unit").toInt()), unit)));
  9392. }
  9393. }
  9394. return QVariant(row->at(index.column()).toString());
  9395. }
  9396. }
  9397. return QVariant();@/
  9398. }
  9399. @ Views also must be able to retrieve the header data.
  9400. @<MeasurementModel Implementation@>=
  9401. QVariant MeasurementModel::headerData(int section, Qt::Orientation orientation,
  9402. int role ) const
  9403. {
  9404. if(orientation == Qt::Horizontal)
  9405. {
  9406. if(role == Qt::DisplayRole)
  9407. {
  9408. if(section < hData->size())
  9409. {
  9410. return QVariant(hData->at(section));
  9411. }
  9412. }
  9413. }
  9414. return QVariant();
  9415. }
  9416. @ Views will sometimes request information about the interactions available for
  9417. an index. In the case of this model, each index is treated in the same way.
  9418. It may be a good idea to extend the model class to allow models that can be
  9419. edited through the view such as the table view presented in the |LogEditWindow|
  9420. and models that probably shouldn'@q'@>t be edited in the view, such as the models
  9421. managed by |ZoomLog|. This could be done by subclassing and only reimplementing
  9422. this method. Otherwise, a new method to specify that the user should not edit
  9423. the model could be provided and a flag would be checked here.
  9424. @<MeasurementModel Implementation@>=
  9425. Qt::ItemFlags MeasurementModel::flags(const QModelIndex &index) const@/
  9426. {@/
  9427. @<Check that the index is valid@>@;
  9428. if(valid)
  9429. {
  9430. return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable;
  9431. }
  9432. return 0;
  9433. }
  9434. @ Much of the way models are interacted with in Qt'@q'@>s model view architecture is
  9435. through model indices. The model is responsible for creating these indices from
  9436. row column pairs.
  9437. @<MeasurementModel Implementation@>=
  9438. QModelIndex MeasurementModel::index(int row, int column,
  9439. const QModelIndex &parent) const@t\2\2@>@/
  9440. {@t\1@>@/
  9441. if(parent == QModelIndex())@/
  9442. {@t\1@>@/
  9443. if(row < entries->size() && entries->isEmpty() == false)@/
  9444. {@/
  9445. if(column < entries->at(row)->size())@/
  9446. {@/
  9447. return createIndex(row, column);@/
  9448. }@/
  9449. }@t\2@>@/
  9450. }@/
  9451. return QModelIndex();@/
  9452. @t\4@>}
  9453. @** Annotating roast data.
  9454. \noindent In addition to recording time temperature pairs, \pn{} allows the user
  9455. to annotate the roasting log to indicate control changes, the end of the batch,
  9456. or samples collected from the roast. It is important that these annotations can
  9457. be applied to the roasting log quickly. This is the purpose of the
  9458. |AnnotationButton| class.
  9459. @<Class declarations@>=
  9460. class AnnotationButton : public QPushButton@/
  9461. {@t\1@>@/
  9462. Q_OBJECT@;
  9463. QString note;
  9464. int tc;
  9465. int ac;
  9466. int count;
  9467. public:@/
  9468. AnnotationButton(const QString &text, QWidget *parent = NULL);@/
  9469. @t\4@>public slots@t\kern-3pt@>:@/
  9470. void setAnnotation(const QString &annotation);
  9471. void setTemperatureColumn(int tempcolumn);
  9472. void setAnnotationColumn(int annotationcolumn);
  9473. void annotate();
  9474. void resetCount();
  9475. signals:@/
  9476. void annotation(QString annotation, int tempcolumn,
  9477. int notecolumn);@t\2@>@/
  9478. }@t\kern-3pt@>;
  9479. @ Setting up a new annotation button begins with the constructor. This takes a
  9480. string specifying the text that will appear on the button and optionally a
  9481. parent widget. This is also a sensible place to set up the desired behavior the
  9482. button should exhibit when clicked.
  9483. @<AnnotationButton Implementation@>=
  9484. AnnotationButton::AnnotationButton(const QString &text, QWidget *parent) :
  9485. QPushButton(text, parent), note(""), tc(0), ac(0), count(0)@/
  9486. {
  9487. connect(this, SIGNAL(clicked()), this, SLOT(annotate()));
  9488. }
  9489. @ The slot that is called when the button is clicked needs to be able to handle
  9490. two types of annotations. Simple annotations send the same annotation every time
  9491. the button is clicked. Counting annotations are annotation strings that have a
  9492. |"%1"| somewhere in the string. That substring will be replaced with an integer
  9493. that is incremented before the annotation is sent. This integer is initialized
  9494. to 0. It will be incremented to 1 the first time the button is clicked and that
  9495. will be the replacement value.
  9496. @<AnnotationButton Implementation@>=
  9497. void AnnotationButton::annotate()
  9498. {
  9499. if(note.contains("%1"))
  9500. {
  9501. count++;
  9502. emit annotation(note.arg(count), tc, ac);
  9503. }
  9504. else
  9505. {
  9506. emit annotation(note, tc, ac);
  9507. }
  9508. }
  9509. @ A few methods are available to indicate which temperature series the
  9510. annotation should be applied to, which column in a table view the annotation
  9511. should be entered in, and what text should be in the annotation.
  9512. @<AnnotationButton Implementation@>=
  9513. void AnnotationButton::setTemperatureColumn(int tempcolumn)
  9514. {
  9515. tc = tempcolumn;
  9516. }
  9517. void AnnotationButton::setAnnotationColumn(int annotationcolumn)
  9518. {
  9519. ac = annotationcolumn;
  9520. }
  9521. void AnnotationButton::setAnnotation(const QString &annotation)
  9522. {
  9523. note = annotation;
  9524. }
  9525. @ Finally, in the case of counting annotations, there should be a way to reset
  9526. the number used in the annotation.
  9527. @<AnnotationButton Implementation@>=
  9528. void AnnotationButton::resetCount()
  9529. {
  9530. count = 0;
  9531. }
  9532. @ A script constructor is needed to allow an |AnnotationButton| to be created
  9533. from a script.
  9534. @<Function prototypes for scripting@>=
  9535. QScriptValue constructAnnotationButton(QScriptContext *context,
  9536. QScriptEngine *engine);
  9537. void setAnnotationButtonProperties(QScriptValue value, QScriptEngine *engine);
  9538. @ In order to use this, the engine needs to be informed of the function.
  9539. @<Set up the scripting engine@>=
  9540. constructor = engine->newFunction(constructAnnotationButton);
  9541. value = engine->newQMetaObject(&AnnotationButton::staticMetaObject,
  9542. constructor);
  9543. engine->globalObject().setProperty("AnnotationButton", value);
  9544. @ The implementation is trivial.
  9545. @<Functions for scripting@>=
  9546. QScriptValue constructAnnotationButton(QScriptContext *context,
  9547. QScriptEngine *engine)
  9548. {
  9549. QScriptValue object =
  9550. engine->newQObject(new AnnotationButton(argument<QString>(0, context)));
  9551. setAnnotationButtonProperties(object, engine);
  9552. return object;
  9553. }
  9554. void setAnnotationButtonProperties(QScriptValue value, QScriptEngine *engine)
  9555. {
  9556. setQPushButtonProperties(value, engine);
  9557. }
  9558. @* A spin box for annotations.
  9559. \noindent While the annotation button is adequate for most log annotation tasks,
  9560. there are some times where the log should contain a small number of numerical
  9561. observations where it is inconvenient or cost prohibitive to enable automated
  9562. logging. For these tasks, a spin box that produces an appropriate annotation may
  9563. be useful.
  9564. @<Class declarations@>=
  9565. class AnnotationSpinBox : public QDoubleSpinBox@/
  9566. {@t\1@>@/
  9567. Q_OBJECT@;
  9568. QString pretext;
  9569. QString posttext;
  9570. int tc;
  9571. int ac;
  9572. bool change;
  9573. public:
  9574. AnnotationSpinBox(const QString &pret, const QString &postt,
  9575. QWidget *parent = NULL);@/
  9576. @t\4@>public slots@t\kern-3pt@>:@/
  9577. void setPretext(const QString &pret);
  9578. void setPosttext(const QString &postt);
  9579. void setTemperatureColumn(int tempcolumn);
  9580. void setAnnotationColumn(int annotationcolumn);
  9581. void annotate();
  9582. void resetChange();
  9583. signals:@/
  9584. void annotation(QString annotation, int tempcolumn,
  9585. int notecolumn);@t\2@>@/
  9586. }@t\kern-3pt@>;
  9587. @ Setting up a new annotation spin box begins with the constructor. This takes
  9588. two strings specifying optional text that may appear before or after the
  9589. numerical value of the spin box in the annotation. No spaces are placed between
  9590. the text and the numerical values, so if such spacing is required, it must be
  9591. included in the relevant string.
  9592. This function also sets up the behavior for firing annotation events. An
  9593. annotation should be fired when the user presses enter while the spin box has
  9594. focus. This implementation will also attempt to fire an annotation when the
  9595. spin box loses focus. No annotation is fired if the value of the spin box has
  9596. not been changed since the previous annotation event.
  9597. @<AnnotationSpinBox Implementation@>=
  9598. AnnotationSpinBox::AnnotationSpinBox(const QString &pret,
  9599. const QString &postt,@|
  9600. QWidget *parent)
  9601. : QDoubleSpinBox(parent), pretext(pret), posttext(postt)@/
  9602. {
  9603. resetChange();
  9604. connect(this, SIGNAL(editingFinished()), this, SLOT(annotate()));
  9605. connect(this, SIGNAL(valueChanged(double)), this, SLOT(resetChange()));
  9606. }
  9607. @ The |resetChange()| signal just sets a boolean which is checked prior to
  9608. sending an annotation. This is called automatically when the value of the spin
  9609. box is changed, but it should also be called when a batch is finished in case
  9610. the first required annotation is the same as the last required annotation from
  9611. the previous batch.
  9612. @<AnnotationSpinBox Implementation@>=
  9613. void AnnotationSpinBox::resetChange()@t\2\2@>@/
  9614. {@t\1@>@/
  9615. change = true;@t\2@>@/
  9616. }
  9617. @ The annotation slot is responsible for determining if an annotation should be
  9618. sent. The current implementation is to only attempt to send such a signal when
  9619. the |editingFinished()| signal is emitted, however this could also be connected
  9620. to other signals.
  9621. @<AnnotationSpinBox Implementation@>=
  9622. void AnnotationSpinBox::annotate()@t\2\2@>@/
  9623. {@t\1@>@/
  9624. if(change)@/
  9625. {@t\1@>@/
  9626. change = false;@/
  9627. emit annotation(QString("%1%2%3").arg(pretext).
  9628. arg(value()).arg(posttext), tc, ac);@t\2@>@/
  9629. }@t\2@>@/
  9630. }
  9631. @ These methods set various properties of the annotation.
  9632. @<AnnotationSpinBox Implementation@>=
  9633. void AnnotationSpinBox::setTemperatureColumn(int tempcolumn)
  9634. {
  9635. tc = tempcolumn;
  9636. }
  9637. void AnnotationSpinBox::setAnnotationColumn(int annotationcolumn)
  9638. {
  9639. ac = annotationcolumn;
  9640. }
  9641. void AnnotationSpinBox::setPretext(const QString &pret)
  9642. {
  9643. pretext = pret;
  9644. }
  9645. void AnnotationSpinBox::setPosttext(const QString &postt)
  9646. {
  9647. posttext = postt;
  9648. }
  9649. @ Two functions are needed to interface |AnnotationSpinBox| with the host
  9650. environment. Additional functions are required for setting up inheritance
  9651. properly.
  9652. @<Function prototypes for scripting@>=
  9653. QScriptValue constructAnnotationSpinBox(QScriptContext *context,
  9654. QScriptEngine *engine);
  9655. void setAnnotationSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  9656. void setQDoubleSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  9657. void setQAbstractSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  9658. @ The first of these is passed into the host environment.
  9659. @<Set up the scripting engine@>=
  9660. constructor = engine->newFunction(constructAnnotationSpinBox);
  9661. value = engine->newQMetaObject(&AnnotationSpinBox::staticMetaObject,
  9662. constructor);
  9663. engine->globalObject().setProperty("AnnotationSpinBox", value);
  9664. @ The script constructor creates a new object and passes it to a function that
  9665. is responsible for setting up properties in the inheritance chain.
  9666. @<Functions for scripting@>=
  9667. QScriptValue constructAnnotationSpinBox(QScriptContext *context,
  9668. QScriptEngine *engine)
  9669. {
  9670. QScriptValue object = engine->newQObject(new AnnotationSpinBox(
  9671. argument<QString>(0, context), argument<QString>(1, context)));
  9672. setAnnotationSpinBoxProperties(object, engine);
  9673. return object;
  9674. }
  9675. void setAnnotationSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  9676. {
  9677. setQDoubleSpinBoxProperties(value, engine);
  9678. }
  9679. void setQDoubleSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  9680. {
  9681. setQAbstractSpinBoxProperties(value, engine);
  9682. }
  9683. void setQAbstractSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  9684. {
  9685. setQWidgetProperties(value, engine);
  9686. }
  9687. @** A digital timer.
  9688. \noindent Before \pn{} was a data logger, it was a simple digital timer written
  9689. because there were no shops in Racine that could sell a simple dual digital
  9690. count up timer at a time when my first timer was malfunctioning. After
  9691. attempting to purchase a replacement device at several stores that have sold
  9692. such devices in the past, I decided to spend a couple hours writing my own
  9693. timer.
  9694. For historical reasons, the |TimerDisplay| class is considerably more functional
  9695. than \pn{} requires. Those needing only a digital timer can extract the code for
  9696. this class and use it in a timer application. This should work on any platform
  9697. supported by Qt.
  9698. @<Class declarations@>=
  9699. class TimerDisplay : public QLCDNumber@/
  9700. {@t\1@>@/
  9701. Q_OBJECT@/
  9702. @<TimerDisplay Properties@>@;
  9703. @t\4@>private slots@t\kern-3pt@>:@/
  9704. void updateTime();
  9705. void setCountUpMode();
  9706. void setCountDownMode();
  9707. void setClockMode();
  9708. public:@/
  9709. TimerDisplay(QWidget *parent = NULL);
  9710. ~TimerDisplay();
  9711. enum TimerMode
  9712. {
  9713. CountUp,
  9714. CountDown,
  9715. Clock
  9716. };
  9717. QString value();
  9718. QTime seconds();
  9719. TimerMode mode();
  9720. bool isRunning();
  9721. QTime resetValue();
  9722. QString displayFormat();
  9723. bool autoReset();@/
  9724. @t\4@>public slots@t\kern-3pt@>:@/
  9725. void setTimer(QTime value = QTime(0, 0, 0));
  9726. void setMode(TimerMode mode);
  9727. void startTimer();
  9728. void stopTimer();
  9729. void copyTimer();
  9730. void setResetValue(QTime value = QTime(0, 0, 0));
  9731. void reset();
  9732. void setDisplayFormat(QString format);
  9733. void setAutoReset(bool reset);
  9734. void updateDisplay();
  9735. signals:@/
  9736. void valueChanged(QTime);
  9737. void runStateChanged(bool);@/
  9738. private:@/
  9739. @<TimerDisplay Private Variables@>@;@t\2@>@/
  9740. }@t\kern-3pt@>;
  9741. @ Qt provides a property system based on its meta-object system. This allows for
  9742. a number of advanced features which \pn{} does not use. The properties available
  9743. for the TimerDisplay class exist for historical reasons, but there are some
  9744. plans for future development which may make use of them. The properties may also
  9745. be useful for someone using this class in another program.
  9746. @<TimerDisplay Properties@>=
  9747. Q_PROPERTY(QTime seconds READ seconds WRITE setTimer)@/
  9748. Q_PROPERTY(TimerMode mode READ mode WRITE setMode)@/
  9749. Q_PROPERTY(bool running READ isRunning)@/
  9750. Q_PROPERTY(QTime resetValue READ resetValue WRITE setResetValue)@/
  9751. Q_PROPERTY(QString displayFormat READ displayFormat WRITE setDisplayFormat)@/
  9752. Q_PROPERTY(bool autoReset READ autoReset WRITE setAutoReset)@/
  9753. Q_PROPERTY(QString value READ value)@/
  9754. @ A number of private variables are used to implement this class.
  9755. @<TimerDisplay Private Variables@>=
  9756. QTime s;
  9757. QTime r;
  9758. QTimer clock;
  9759. TimerDisplay::TimerMode m;
  9760. bool running;
  9761. bool ar;
  9762. QAction *startAction;
  9763. QAction *stopAction;
  9764. QAction *resetAction;
  9765. QString f;
  9766. QTime relative;
  9767. QTime base;
  9768. @ |TimerDisplay| is a specialization of |QLCDNumber| designed for time keeping
  9769. purposes. It sets up a timer that fires roughly every half second to see if it
  9770. needs to update itself. The constructor sets this up, but does not start the
  9771. timer. The class provides three actions which can be used to start, stop, or
  9772. reset the timer. These actions are also set up in the constructor.
  9773. By default, the timer will display its time in hours, minutes, and seconds. This
  9774. can be changed as is done with the batch timer (it is expected that nobody will
  9775. want to spend an hour or more to roast a batch of coffee). The display style is
  9776. also changed to a sensible default, but this can be changed with the usual
  9777. |QLCDNumber| methods.
  9778. @<TimerDisplay Implementation@>=
  9779. TimerDisplay::TimerDisplay(QWidget *parent) : QLCDNumber(8, parent),
  9780. s(QTime(0, 0, 0)), r(QTime(0, 0, 0)), clock(NULL),@/ m(TimerDisplay::CountUp),
  9781. running(false), ar(false), startAction(new QAction(tr("Start"), NULL)),@/
  9782. stopAction(new QAction(tr("Stop"), NULL)),
  9783. resetAction(new QAction(tr("Reset"), NULL)),@/ f(QString("hh:mm:ss")),
  9784. relative(QTime::currentTime()), base(QTime(0, 0, 0))@/
  9785. {
  9786. connect(startAction, SIGNAL(triggered(bool)), this, SLOT(startTimer()));
  9787. connect(stopAction, SIGNAL(triggered(bool)), this, SLOT(stopTimer()));
  9788. connect(resetAction, SIGNAL(triggered(bool)), this, SLOT(reset()));
  9789. clock.setInterval(500);
  9790. clock.setSingleShot(false);
  9791. connect(&clock, SIGNAL(timeout()), this, SLOT(updateTime()));
  9792. setSegmentStyle(Filled);
  9793. updateDisplay();
  9794. }
  9795. @ The complicated bits are all in the |updateTime()| method. The behavior of
  9796. this function depends on the current |TimerMode| of the display.
  9797. @<TimerDisplay Implementation@>=
  9798. void TimerDisplay::updateTime()
  9799. {
  9800. QTime time;
  9801. int cseconds = 0;
  9802. int oseconds = 0;
  9803. int r = 0;
  9804. QTime nt = QTime(0, 0, 0);
  9805. int n = 0;
  9806. int bseconds = 0;
  9807. switch(m)@/
  9808. {@t\1@>@/
  9809. case TimerDisplay::CountUp:@/
  9810. @<Check for Timer Increment@>;
  9811. break;
  9812. case TimerDisplay::CountDown:@/
  9813. @<Check for Timer Decrement@>;
  9814. break;
  9815. case TimerDisplay::Clock:@/
  9816. @<Check for Clock Change@>;
  9817. break;
  9818. default:@/
  9819. Q_ASSERT_X(false, "updateTime", "invalid timer mode");
  9820. break;@t\2@>@/
  9821. }
  9822. updateDisplay();
  9823. }
  9824. @ To have the timer count up, we calculate the value that the timer should
  9825. indicate and compare it to the time indicated. If there is a difference, we
  9826. update the time to the new value and send emit a signal.
  9827. @<Check for Timer Increment@>=
  9828. @<Load seconds since base time into r@>@;
  9829. nt = nt.addSecs(r);
  9830. if(nt != s)
  9831. {
  9832. s = nt;
  9833. emit valueChanged(s);
  9834. }
  9835. @ Here we want to calculate the number of seconds in the current time, the
  9836. number of seconds in a base time, and the difference between the two. The
  9837. value loaded into oseconds could probably be cached.
  9838. @<Load seconds since base time into r@>=
  9839. #define TIMETOINT(t) ((t.hour() * 60 * 60) + (t.minute() * 60) + (t.second()))
  9840. time = QTime::currentTime();
  9841. cseconds = TIMETOINT(time);
  9842. oseconds = TIMETOINT(relative);
  9843. r = cseconds - oseconds;
  9844. @ The logic for a count down timer is very similar to the logic for a count up
  9845. timer. A key difference is that we don'@q'@>t want to continue counting down if the
  9846. timer has already reached 0.
  9847. @<Check for Timer Decrement@>=
  9848. if(s > QTime(0, 0, 0))@/
  9849. {@/
  9850. @<Load seconds since base time into r@>@;
  9851. bseconds = TIMETOINT(base);
  9852. n = bseconds - r;
  9853. nt = nt.addSecs(n);
  9854. if(nt != s)
  9855. {
  9856. s = nt;
  9857. emit valueChanged(s);
  9858. }
  9859. } else {
  9860. stopTimer();
  9861. }
  9862. @ The clock mode is the simplest case as it just needs to find out if the time
  9863. has changed.
  9864. @<Check for Clock Change@>=
  9865. time = QTime::currentTime();
  9866. if(time != s)
  9867. {
  9868. s = time;
  9869. emit valueChanged(s);
  9870. }
  9871. @ When counting up or down, it is important to record the time at which the
  9872. timer starts. The clock that triggers time updates must also be started. The
  9873. timer also needs to reset its value if that behavior is desired.
  9874. @<TimerDisplay Implementation@>=
  9875. #define TIMESUBTRACT(t1, t2) (t1.addSecs(-(TIMETOINT(t2))).addSecs(-t2.msec()))
  9876. void TimerDisplay::startTimer()@t\2\2@>@/
  9877. {@t\1@>@/
  9878. if(!running)@/
  9879. {@t\1@>@/
  9880. relative = QTime::currentTime();
  9881. if(ar)@/
  9882. {
  9883. reset();
  9884. }
  9885. else
  9886. {
  9887. relative = TIMESUBTRACT(relative, s);
  9888. }
  9889. if(m == Clock)@/
  9890. {
  9891. updateTime();
  9892. }
  9893. base = s;
  9894. clock.start();@/
  9895. running = true;
  9896. emit runStateChanged(true);@t\2@>@/
  9897. }@t\2@>@/
  9898. }
  9899. @ Stopping the timer is a little simpler. Remember to stop the clock so we
  9900. aren'@q'@>t updating senselessly.
  9901. @<TimerDisplay Implementation@>=
  9902. void TimerDisplay::stopTimer()@t\2\2@>@/
  9903. {@t\1@>@/
  9904. if(running)@/
  9905. {@t\1@>@/
  9906. clock.stop();@/
  9907. running = false;
  9908. emit runStateChanged(false);@t\2@>@/
  9909. }@t\2@>@/
  9910. }
  9911. @ The clock is also stopped in the destructor.
  9912. @<TimerDisplay Implementation@>=
  9913. TimerDisplay::~TimerDisplay()
  9914. {
  9915. clock.stop();
  9916. }
  9917. @ The rest of the functions are trivial. There are functions for changing the
  9918. timer mode:
  9919. @<TimerDisplay Implementation@>=
  9920. void TimerDisplay::setCountUpMode()
  9921. {
  9922. m = TimerDisplay::CountUp;
  9923. }
  9924. void TimerDisplay::setCountDownMode()
  9925. {
  9926. m = TimerDisplay::CountDown;
  9927. }
  9928. void TimerDisplay::setClockMode()
  9929. {
  9930. m = TimerDisplay::Clock;
  9931. }
  9932. @ There are a few functions to obtain information about the state of the timer.
  9933. @<TimerDisplay Implementation@>=
  9934. QString TimerDisplay::value()
  9935. {
  9936. return s.toString(f);
  9937. }
  9938. QTime TimerDisplay::seconds()
  9939. {
  9940. return s;
  9941. }
  9942. TimerDisplay::TimerMode TimerDisplay::mode()
  9943. {
  9944. return m;
  9945. }
  9946. bool TimerDisplay::isRunning()
  9947. {
  9948. return running;
  9949. }
  9950. QTime TimerDisplay::resetValue()
  9951. {
  9952. return r;
  9953. }
  9954. QString TimerDisplay::displayFormat()
  9955. {
  9956. return f;
  9957. }
  9958. bool TimerDisplay::autoReset()
  9959. {
  9960. return ar;
  9961. }
  9962. @ There are also some functions for setting aspects of the timer state.
  9963. @<TimerDisplay Implementation@>=
  9964. void TimerDisplay::setTimer(QTime value)
  9965. {
  9966. if(value.isValid())
  9967. {
  9968. s = value;
  9969. updateDisplay();
  9970. emit valueChanged(value);
  9971. }
  9972. }
  9973. void TimerDisplay::setMode(TimerDisplay::TimerMode mode)
  9974. {
  9975. m = mode;
  9976. }
  9977. void TimerDisplay::setResetValue(QTime value)
  9978. {
  9979. r = value;
  9980. }
  9981. void TimerDisplay::setDisplayFormat(QString format)
  9982. {
  9983. f = format;
  9984. setNumDigits(format.length());
  9985. }
  9986. void TimerDisplay::setAutoReset(bool reset)
  9987. {
  9988. ar = reset;
  9989. }
  9990. @ |TimerDisplay| supports using the system clipboard to copy the current timer
  9991. value.
  9992. @<TimerDisplay Implementation@>=
  9993. void TimerDisplay::copyTimer()
  9994. {
  9995. QApplication::clipboard()->setText(value());
  9996. }
  9997. @ Resetting the timer is simple. We don'@q'@>t reset the timer if it is still running
  9998. mainly to prevent accidents.
  9999. @<TimerDisplay Implementation@>=
  10000. void TimerDisplay::reset()
  10001. {
  10002. if(!running)
  10003. {
  10004. s = r;
  10005. updateDisplay();
  10006. }
  10007. }
  10008. @ Finally, there is the function for changing the text of the display to the
  10009. current time value.
  10010. @<TimerDisplay Implementation@>=
  10011. void TimerDisplay::updateDisplay()
  10012. {
  10013. display(value());
  10014. }
  10015. @ Exposing |TimerDisplay| to the host environment is simple.
  10016. @<Function prototypes for scripting@>=
  10017. QScriptValue constructTimerDisplay(QScriptContext *context,
  10018. QScriptEngine *engine);
  10019. void setTimerDisplayProperties(QScriptValue value, QScriptEngine *engine);
  10020. QScriptValue TimerDisplay_setTimerMode(QScriptContext *context, QScriptEngine *engine);
  10021. @ The engine must be informed of the script constructor.
  10022. @<Set up the scripting engine@>=
  10023. constructor = engine->newFunction(constructTimerDisplay);
  10024. value = engine->newQMetaObject(&TimerDisplay::staticMetaObject, constructor);
  10025. engine->globalObject().setProperty("TimerDisplay", value);
  10026. @ The implementation of these functions is trivial.
  10027. @<Functions for scripting@>=
  10028. QScriptValue constructTimerDisplay(QScriptContext *, QScriptEngine *engine)
  10029. {
  10030. QScriptValue object = engine->newQObject(new TimerDisplay);
  10031. setTimerDisplayProperties(object, engine);
  10032. return object;
  10033. }
  10034. void setTimerDisplayProperties(QScriptValue value, QScriptEngine *engine)
  10035. {
  10036. setQLCDNumberProperties(value, engine);
  10037. value.setProperty("setTimerMode", engine->newFunction(TimerDisplay_setTimerMode));
  10038. }
  10039. @ A new feature in \pn{} 1.6.4 benefits from having the ability to set the
  10040. timer mode from a script. Rather than exposing the |enum| responsible for this
  10041. to the host environment, a new function is provided to allow integer based
  10042. setting.
  10043. @<Functions for scripting@>=
  10044. QScriptValue TimerDisplay_setTimerMode(QScriptContext *context, QScriptEngine *)
  10045. {
  10046. TimerDisplay *self = getself<TimerDisplay *>(context);
  10047. if(self)
  10048. {
  10049. switch(argument<int>(0, context))
  10050. {
  10051. case 0:
  10052. self->setMode(TimerDisplay::CountUp);
  10053. break;
  10054. case 1:
  10055. self->setMode(TimerDisplay::CountDown);
  10056. break;
  10057. case 2:
  10058. self->setMode(TimerDisplay::Clock);
  10059. break;
  10060. default:
  10061. break;
  10062. }
  10063. }
  10064. return QScriptValue();
  10065. }
  10066. @** The Human Computer Interface.
  10067. \noindent A few classes are required for putting the rest of the program
  10068. together in a way that it can be used by a human. There is a layout class for
  10069. arranging widgets in a way that is not simple with the layouts provided by Qt.
  10070. There are classes for labeling the various indicators. There are also window
  10071. classes that put all of this together in a useful and usable way. One of these
  10072. classes is currently depreciated.
  10073. @* The PackLayout Class.
  10074. \noindent The |PackLayout| class provides functionality similar to the
  10075. |QBoxLayout| class in Qt. It allows the construction of a row or column of
  10076. widgets. Each item will take up space along the orientation of the layout equal
  10077. to its size hint except for the last widget which will take up all remaining
  10078. space. Widgets will be resized in the direction perpendicular to the orientation
  10079. of the layout to use all available space.
  10080. This class was originally written with the |WidgetDecorator| class which we will
  10081. get to later in mind, but it has found use in other places where the left or top
  10082. most widgets should not be resized.
  10083. By default, a new |PackLayout| will arrange widgets horizontally. This can be
  10084. changed with a call to |setOrientation()|.
  10085. @<Class declarations@>=
  10086. class PackLayout : public QLayout@/
  10087. {@/
  10088. int doLayout(const QRect &rect, bool testOnly) const;@/
  10089. QList<QLayoutItem *> itemList;@/
  10090. Qt::Orientations@, orientation;@/
  10091. public:@/
  10092. PackLayout(QWidget *parent, int margin = 0, int spacing = -1);
  10093. PackLayout(int spacing = -1);
  10094. ~PackLayout();
  10095. void addItem(QLayoutItem *item);
  10096. Qt::Orientations@, expandingDirections() const;
  10097. bool hasHeightForWidth() const;
  10098. int heightForWidth(int width) const;
  10099. int count() const;
  10100. QLayoutItem *itemAt(int index) const;
  10101. QSize minimumSize() const;
  10102. void setGeometry(const QRect &rect);
  10103. void setOrientation(Qt::Orientations direction);
  10104. QSize sizeHint() const;
  10105. QLayoutItem *takeAt(int index);
  10106. };
  10107. @ The interesting portion of this class is in |doLayout()|. This function goes
  10108. over the items in the layout and sets the geometry appropriately.
  10109. The seemingly odd choice of returning |y| at the end of this function (indeed of
  10110. having a return value at all) is to allow this function to provide the return
  10111. value needed in |heightForWidth()|.
  10112. If |testOnly| is set to |true|, |y| will be calculated, but the widget geometry
  10113. will not be changed.
  10114. @<PackLayout Implementation@>=
  10115. int PackLayout::doLayout(const QRect &rect, bool testOnly) const
  10116. {
  10117. int x = rect.x();
  10118. int y = rect.y();
  10119. QLayoutItem *item;
  10120. if(orientation == Qt::Horizontal)
  10121. {
  10122. @<Lay the widgets out horizontally@>@;
  10123. }
  10124. else
  10125. {
  10126. @<Lay the widgets out vertically@>@;
  10127. }
  10128. return y;
  10129. }
  10130. @ To lay the widgets out horizontally, we go over each item in the list taking
  10131. the width of the size hint and spacing into account unless the item is the last
  10132. item in the list, in which case the right of the widget needs to be at the end
  10133. of the available space. We use the foreach construction that Qt provides to
  10134. iterate over each item in the list in much the same way as foreach constructions
  10135. are used in languages that support them directly.
  10136. @<Lay the widgets out horizontally@>=
  10137. foreach(item, itemList)
  10138. {
  10139. int nextX = x + item->sizeHint().width() + spacing();
  10140. int right = x + item->sizeHint().width();
  10141. if(item == itemList.last())
  10142. {
  10143. right = rect.right();
  10144. }
  10145. int bottom = rect.bottom();
  10146. if(!testOnly)
  10147. {
  10148. item->setGeometry(QRect(QPoint(x, y), QPoint(right, bottom)));
  10149. }
  10150. x = nextX;
  10151. }
  10152. @ Laying out the widgets vertically is very similar.
  10153. @<Lay the widgets out vertically@>=
  10154. foreach(item, itemList)
  10155. {
  10156. int nextY = y + item->sizeHint().height() + spacing();
  10157. int bottom = y + item->sizeHint().height();
  10158. if(item == itemList.last())
  10159. {
  10160. bottom = rect.bottom();
  10161. }
  10162. int right = rect.right();
  10163. if(!testOnly)
  10164. {
  10165. item->setGeometry(QRect(QPoint(x, y), QPoint(right, bottom)));
  10166. }
  10167. y = nextY;
  10168. }
  10169. @ As a layout class, there are a number of things the class should be able to do
  10170. in order to play nicely with other classes. One of these is determining the
  10171. minimum size of the layout. The minimum size of the layout is equal to the space
  10172. required for each item in the layout plus the margin space. The margin space
  10173. will be equal to twice the specified margin in each direction to account for a
  10174. top, bottom, left, and right margin.
  10175. @<PackLayout Implementation@>=
  10176. QSize PackLayout::minimumSize() const
  10177. {
  10178. QSize size;
  10179. QLayoutItem *item;
  10180. foreach(item, itemList)
  10181. {
  10182. if(orientation == Qt::Horizontal)
  10183. {
  10184. size += QSize(item->minimumSize().width(), 0);
  10185. if(size.height() < item->minimumSize().height())
  10186. {
  10187. size.setHeight(item->minimumSize().height());
  10188. }
  10189. }
  10190. else
  10191. {
  10192. size += QSize(0, item->minimumSize().height());
  10193. if(size.width() < item->minimumSize().width())
  10194. {
  10195. size.setWidth(item->minimumSize().width());
  10196. }
  10197. }
  10198. }
  10199. size += QSize(2*margin(), 2*margin());
  10200. return size;
  10201. }
  10202. @ |PackLayout| features two constructors. One allows for setting the margin,
  10203. spacing, and a parent widget at the time of construction. The other creates a
  10204. parentless layout which will have to be added to another widget or layout.
  10205. @<PackLayout Implementation@>=
  10206. PackLayout::PackLayout(QWidget *parent, int margin, int spacing) :
  10207. QLayout(parent)@/
  10208. {
  10209. setMargin(margin);
  10210. setSpacing(spacing);
  10211. setOrientation(Qt::Horizontal);
  10212. }
  10213. PackLayout::PackLayout(int spacing)
  10214. {
  10215. setSpacing(spacing);
  10216. setOrientation(Qt::Horizontal);
  10217. }
  10218. @ In Qt, items in a layout are owned by that layout. When the layout is
  10219. destroyed, all of the items in that layout must also be deleted.
  10220. @<PackLayout Implementation@>=
  10221. PackLayout::~PackLayout()
  10222. {
  10223. QLayoutItem *item;
  10224. while((item = takeAt(0)))
  10225. {
  10226. delete item;
  10227. }
  10228. }
  10229. @ Deleting the items uses the |takeAt()| method to remove each widget from the
  10230. layout prior to deleting it. The item requested should exist, but if it doesn'@q'@>t,
  10231. |NULL| is returned.
  10232. @<PackLayout Implementation@>=
  10233. QLayoutItem* PackLayout::takeAt(int index)
  10234. {
  10235. if(index >= 0 && index < itemList.size())
  10236. {
  10237. return itemList.takeAt(index);
  10238. }
  10239. else
  10240. {
  10241. return NULL;
  10242. }
  10243. }
  10244. @ If we are interested in which item is in a particular position in the layout
  10245. but do not want to remove it from the layout, |itemAt()| provides that.
  10246. @<PackLayout Implementation@>=
  10247. QLayoutItem* PackLayout::itemAt(int index) const
  10248. {
  10249. if(index >= 0 && index < itemList.size())
  10250. {
  10251. return itemList.at(index);
  10252. }
  10253. else
  10254. {
  10255. return NULL;
  10256. }
  10257. }
  10258. @ A layout class is not very useful unless there is a way to get items into the
  10259. layout. The |QLayoutItem| class is designed in such a way that it is possible to
  10260. pass pointers to objects that inherit |QLayout| or |QWidget|.
  10261. The base |QLayout| class provides an |addWidget()| method that will use our
  10262. version of |addItem()|. That should be used when adding a widget to the layout.
  10263. The Qt documentation recommends also providing an |addLayout()| method so that
  10264. other code does not need to call this method, but that has not been provided
  10265. yet.
  10266. @<PackLayout Implementation@>=
  10267. void PackLayout::addItem(QLayoutItem *item)
  10268. {
  10269. itemList.append(item);
  10270. }
  10271. @ It is sometimes useful to know how many items are in a layout.
  10272. @<PackLayout Implementation@>=
  10273. int PackLayout::count() const@;@/
  10274. {@/
  10275. return itemList.size();@/
  10276. }
  10277. @ A few more functions are needed to make the layout class work well with other
  10278. classes. For more details, please consult the Qt Reference
  10279. Documentation\nfnote{Qt Reference Documentation\par\indent\hbox{%
  10280. \pdfURL{http://doc.trolltech.com/4.3/index.html}%
  10281. {http://doc.trolltech.com/4.3/index.html}}}
  10282. @<PackLayout Implementation@>=
  10283. Qt::Orientations PackLayout::expandingDirections() const
  10284. {
  10285. return Qt::Vertical | Qt::Horizontal;
  10286. }
  10287. bool PackLayout::hasHeightForWidth() const@t\2\2@>@/
  10288. {@t\1@>@/
  10289. return false;@t\2@>@/
  10290. }@/
  10291. int PackLayout::heightForWidth(int width) const
  10292. {
  10293. return doLayout(QRect(0, 0, width, 0), true);
  10294. }
  10295. void PackLayout::setGeometry(const QRect &rect)
  10296. {
  10297. QLayout::setGeometry(rect);
  10298. doLayout(rect, false);
  10299. }
  10300. QSize PackLayout::sizeHint() const
  10301. {
  10302. return minimumSize();
  10303. }
  10304. @ It was mentioned previously that this layout is capable of lining widgets up
  10305. in a row or presenting them in a column. This is done with the
  10306. |setOrientation()| method.
  10307. @<PackLayout Implementation@>=
  10308. void PackLayout::setOrientation(Qt::Orientations direction)
  10309. {
  10310. orientation = direction;
  10311. doLayout(geometry(), false);
  10312. }
  10313. @* The SceneButton Class.
  10314. \noindent Ordinarily, mouse down events that are passed from a |QGraphicsView|
  10315. to an interactive |QGraphicsScene| will continue to pass that click down to an
  10316. item in the scene. This class is used when we are interested in a click anywhere
  10317. in the view and it doesn'@q'@>t really matter where in the scene that click occurred
  10318. or even if there is a graphics item at that point. Any click passed to the
  10319. |SceneButton| will cause the scene to emit a signal containing the screen
  10320. coordinates of the click.
  10321. This was originally designed for use in the |WidgetDecorator| class. While the
  10322. functionality provided is not currently used, the original plan was to use this
  10323. to provide access to configuration options.
  10324. It is possible that this class is no longer necessary even if features it was
  10325. made for are implemented.
  10326. @<Class declarations@>=
  10327. class SceneButton : public QGraphicsScene@/
  10328. {@/
  10329. Q_OBJECT@;
  10330. public:@/
  10331. SceneButton();
  10332. ~SceneButton();
  10333. protected:@/
  10334. void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent);
  10335. signals:@/
  10336. void clicked(QPoint pos);
  10337. };
  10338. @ The implementation is trivial.
  10339. @<SceneButton Implementation@>=
  10340. SceneButton::SceneButton() : QGraphicsScene()@/
  10341. {
  10342. /* Nothing has to be done here. */
  10343. }
  10344. SceneButton::~SceneButton()
  10345. {
  10346. /* Nothing has to be done here. */
  10347. }
  10348. void SceneButton::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
  10349. {
  10350. emit clicked(mouseEvent->buttonDownScreenPos(mouseEvent->button()));
  10351. }
  10352. @* The WidgetDecorator Class.
  10353. \noindent The |WidgetDecorator| class provides a way to label various widgets
  10354. while also providing additional options for interacting with them. The
  10355. decoration can exist to the left or atop the widget being decorated. When the
  10356. label is to the left of the widget, the label text is rotated.
  10357. This class is likely to change considerably in the future as features are added
  10358. that allow actions to be added to the decoration to allow various configuration
  10359. options.
  10360. @<Class declarations@>=
  10361. class WidgetDecorator : public QWidget@/
  10362. {
  10363. Q_OBJECT@;
  10364. PackLayout *layout;
  10365. QGraphicsView *label;
  10366. QGraphicsTextItem *text;
  10367. SceneButton *scene;
  10368. public:@/
  10369. WidgetDecorator(QWidget *widget, const QString &labeltext,@|
  10370. Qt::Orientations@, orientation = Qt::Horizontal,@|
  10371. QWidget *parent = NULL, Qt::WindowFlags f = 0);
  10372. ~WidgetDecorator();
  10373. void setBackgroundBrush(QBrush background);
  10374. void setTextColor(QColor color);
  10375. };
  10376. @ Almost everything this class currently does is handled in the constructor.
  10377. @<WidgetDecorator Implementation@>=
  10378. WidgetDecorator::WidgetDecorator(QWidget *widget, const QString &labeltext,
  10379. Qt::Orientations orientation,
  10380. QWidget *parent, Qt::WindowFlags f)@/:
  10381. QWidget(parent, f), label(new QGraphicsView()),
  10382. scene(new SceneButton())@t\2@>@/
  10383. {
  10384. layout = new PackLayout(this);
  10385. layout->setOrientation(orientation);
  10386. @<Prepare the graphics view@>@;
  10387. @<Add the label to the scene@>@;
  10388. @<Adjust the decoration width@>@;
  10389. @<Pack widgets into the layout@>@;
  10390. }
  10391. @ The decoration is a |QGraphicsView|. To get this to look right, we need to
  10392. make sure there aren'@q'@>t any scroll bars and there shouldn'@q'@>t be a frame
  10393. surrounding it. While we'@q'@>re at it, we allow it to accept clicks, though this
  10394. functionality is not yet used.
  10395. @<Prepare the graphics view@>=
  10396. label->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  10397. label->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  10398. label->setFrameShape(QFrame::NoFrame);
  10399. label->setInteractive(true);
  10400. @ The |QGraphicsView| needs a scene to display anything. The scene consists of a
  10401. background which, by default is solid cyan. This can be changed later by setting
  10402. a different background brush. Text also needs to be added to the scene. If the
  10403. decoration is to the left of the widget, the text needs to be rotated.
  10404. @<Add the label to the scene@>=
  10405. scene->setBackgroundBrush(Qt::cyan);
  10406. text = scene->addText(labeltext);
  10407. if(orientation == Qt::Horizontal)
  10408. {
  10409. text->rotate(270.0);
  10410. }
  10411. label->setScene(scene);
  10412. @ The decoration should have the text centered in the view. The widget should
  10413. also be no wider (or taller for horizontal orientation) than necessary for the
  10414. text.
  10415. The case for horizontal orientation here may seem a little strange, however the
  10416. dimensions of the bounding rectangle are not affected by rotation. This means
  10417. that even though we want the width of the rotated text, this is the same as the
  10418. height of the text.
  10419. @<Adjust the decoration width@>=
  10420. if(orientation == Qt::Horizontal)
  10421. {
  10422. label->setMaximumWidth((int)(text->boundingRect().height() + 1));
  10423. }
  10424. else
  10425. {
  10426. label->setMaximumHeight((int)(text->boundingRect().height() + 1));
  10427. }
  10428. label->centerOn(text);
  10429. @ Once the decoration is ready, the decoration and the widget being decorated
  10430. can be added to the layout. A minimum size for the compound widget is also
  10431. calculated.
  10432. @<Pack widgets into the layout@>=
  10433. layout->addWidget(label);
  10434. layout->addWidget(widget);
  10435. if(orientation == Qt::Horizontal)
  10436. {
  10437. setMinimumSize(widget->sizeHint().width() + label->sizeHint().width(),
  10438. widget->sizeHint().height());
  10439. }
  10440. else
  10441. {
  10442. setMinimumSize(widget->sizeHint().width(),
  10443. widget->sizeHint().height() + label->sizeHint().height());
  10444. }
  10445. @ As mentioned previously, it is possible to change the background pattern for
  10446. the decoration. It is also possible to change the color of the text.
  10447. @<WidgetDecorator Implementation@>=
  10448. void WidgetDecorator::setBackgroundBrush(QBrush background)
  10449. {
  10450. scene->setBackgroundBrush(background);
  10451. }
  10452. void WidgetDecorator::setTextColor(QColor color)
  10453. {
  10454. text->setDefaultTextColor(color);
  10455. }
  10456. @ Finally, there is a destructor.
  10457. @<WidgetDecorator Implementation@>=
  10458. WidgetDecorator::~WidgetDecorator()
  10459. {
  10460. /* Nothing has to be done here. */
  10461. }
  10462. @ In order to create a decorated widget from a script, we need these functions.
  10463. @<Function prototypes for scripting@>=
  10464. void setWidgetDecoratorProperties(QScriptValue value, QScriptEngine *engine);
  10465. QScriptValue constructWidgetDecorator(QScriptContext *context,
  10466. QScriptEngine *engine);
  10467. @ The scripting engine must be informed of this function.
  10468. @<Set up the scripting engine@>=
  10469. constructor = engine->newFunction(constructWidgetDecorator);
  10470. value = engine->newQMetaObject(&WidgetDecorator::staticMetaObject, constructor);
  10471. engine->globalObject().setProperty("WidgetDecorator", value);
  10472. @ The constructor is slightly more complex than other script constructors, but
  10473. still simple.
  10474. @<Functions for scripting@>=
  10475. QScriptValue constructWidgetDecorator(QScriptContext *context,
  10476. QScriptEngine *engine)
  10477. {
  10478. QWidget *widget = argument<QWidget *>(0, context);
  10479. QString text = argument<QString>(1, context);
  10480. Qt::Orientations@, orientation;
  10481. switch(argument<int>(2, context))@/
  10482. {@t\1@>@/
  10483. case 2:@/
  10484. orientation = Qt::Vertical;
  10485. break;
  10486. default:@/
  10487. orientation = Qt::Horizontal;
  10488. break;@t\2@>@/
  10489. }
  10490. QScriptValue object =
  10491. engine->newQObject(new WidgetDecorator(widget, text, orientation));
  10492. setWidgetDecoratorProperties(object, engine);
  10493. return object;
  10494. }
  10495. void setWidgetDecoratorProperties(QScriptValue value, QScriptEngine *engine)
  10496. {
  10497. setQWidgetProperties(value, engine);
  10498. }
  10499. @* The LogEditWindow Class.
  10500. \noindent This class will be depreciated in a future release once I have
  10501. confirmed that the class can be replaced by the configuration system. It has not
  10502. been updated to support new functionality added in version 1.2.3 and use of this
  10503. class is highly discouraged.
  10504. While the logging window provided in the example configuration is fine for
  10505. recording an existing roast, there are some who would like to be able to use
  10506. \pn{} to work with data collected with a manual logger. Different controls are
  10507. useful in such a case. The |LogEditWindow| provides this.
  10508. @<Class declarations@>=
  10509. class LogEditWindow : public QMainWindow@/
  10510. {@t\1@>@/
  10511. Q_OBJECT@;
  10512. QWidget *centralWidget;
  10513. PackLayout *mainLayout;
  10514. QHBoxLayout *addRowsLayout;
  10515. QLabel *startTimeLabel;
  10516. QTimeEdit *startTime;
  10517. QLabel *endTimeLabel;
  10518. QTimeEdit *endTime;
  10519. QLabel *intervalLabel;
  10520. QSpinBox *interval;
  10521. QPushButton *addRows;
  10522. QAction *saveXml;
  10523. QAction *saveCsv;
  10524. QAction *openXml;
  10525. MeasurementModel *model;
  10526. QTableView *log;@/
  10527. @t\4@>private slots@t\kern-3pt@>:@/
  10528. void addTheRows();
  10529. void saveXML();
  10530. void saveCSV();
  10531. void openXML();@/
  10532. protected:@/
  10533. void closeEvent(QCloseEvent *event);@/
  10534. public:@/
  10535. LogEditWindow();@t\2@>@/
  10536. }@t\kern-3pt@>;
  10537. @ This window provides controls for adding rows to a measurement. Typically, the
  10538. data on a manual roast log will have measurements at regular intervals with the
  10539. possible exception of a few points where there are control changes or the end of
  10540. the batch. The routine for adding rows is capable of adding a single row, rows
  10541. in a range of times at regular intervals, or rows in a range of times at regular
  10542. intervals plus one time at the end.
  10543. @<LogEditWindow Implementation@>=
  10544. void LogEditWindow::addTheRows()
  10545. {
  10546. QTime s = startTime->time();
  10547. while(s < endTime->time())
  10548. {
  10549. model->newMeasurement(Measurement(0, s), 1);
  10550. s = s.addSecs(interval->value());
  10551. }
  10552. model->newMeasurement(Measurement(0, endTime->time()), 1);
  10553. }
  10554. @ The window is prepared in its constructor.
  10555. @<LogEditWindow Implementation@>=
  10556. LogEditWindow::LogEditWindow() : QMainWindow(NULL),
  10557. centralWidget(new QWidget(NULL)), mainLayout(new PackLayout(0)),@|
  10558. addRowsLayout(new QHBoxLayout(NULL)),
  10559. startTimeLabel(new QLabel("Start Time")),@|
  10560. startTime(new QTimeEdit(QTime(0, 0, 0, 0))),@|
  10561. endTimeLabel(new QLabel("End Time")),
  10562. endTime(new QTimeEdit(QTime(0, 20, 0, 0))),@|
  10563. intervalLabel(new QLabel("Interval (seconds)")),@|
  10564. interval(new QSpinBox()),
  10565. addRows(new QPushButton("Add Rows")),@|
  10566. saveXml(new QAction(tr("Save Profile As..."), NULL)),@|
  10567. saveCsv(new QAction(tr("Export CSV"), NULL)),@|
  10568. openXml(new QAction(tr("Load Target Profile..."), NULL)),@|
  10569. model(new MeasurementModel()),
  10570. log(new QTableView())@/
  10571. {
  10572. @<Restore editor window geometry from settings@>@;
  10573. @<Set up the editor control bar@>@;
  10574. @<Prepare the model@>@;
  10575. @<Prepare the log table@>@;
  10576. mainLayout->addItem(addRowsLayout);
  10577. mainLayout->addWidget(log);
  10578. centralWidget->setLayout(mainLayout);
  10579. setCentralWidget(centralWidget);
  10580. QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
  10581. fileMenu->addAction(openXml);
  10582. connect(openXml, SIGNAL(triggered()), this, SLOT(openXML()));
  10583. fileMenu->addAction(saveXml);
  10584. connect(saveXml, SIGNAL(triggered()), this, SLOT(saveXML()));
  10585. fileMenu->addAction(saveCsv);
  10586. connect(saveCsv, SIGNAL(triggered()), this, SLOT(saveCSV()));
  10587. }
  10588. @ The window keeps its previous size and location in settings. These need to be
  10589. restored when a new window is created.
  10590. @<Restore editor window geometry from settings@>=
  10591. QSettings settings;
  10592. resize(settings.value("logSize", QSize(620,400)).toSize());
  10593. move(settings.value("logPos", QPoint(200,60)).toPoint());
  10594. @ When a new window is opened, it starts with an empty profile. If this is used
  10595. to manually enter a profile rather than edit an existing profile, rows will need
  10596. to be added. For this, we provide a set of controls where a start time, an end
  10597. time, and an interval in seconds is specified along with a button that, when
  10598. pressed, will produce a row in the model for the starting time, the ending time,
  10599. and regularly spaced times between the two. If only a single row is needed, this
  10600. can be produced by setting the start and end times the same.
  10601. @<Set up the editor control bar@>=
  10602. mainLayout->setOrientation(Qt::Vertical);
  10603. addRowsLayout->addSpacing(10);
  10604. addRowsLayout->addWidget(startTimeLabel);
  10605. addRowsLayout->addWidget(startTime);
  10606. addRowsLayout->addSpacing(10);
  10607. startTime->setDisplayFormat("mm:ss");
  10608. addRowsLayout->addWidget(endTimeLabel);
  10609. addRowsLayout->addWidget(endTime);
  10610. addRowsLayout->addSpacing(10);
  10611. endTime->setDisplayFormat("mm:ss");
  10612. addRowsLayout->addWidget(intervalLabel);
  10613. addRowsLayout->addWidget(interval);
  10614. addRowsLayout->addSpacing(10);
  10615. interval->setRange(0, 60);
  10616. interval->setValue(30);
  10617. addRowsLayout->addWidget(addRows);
  10618. addRowsLayout->addSpacing(10);
  10619. connect(addRows, SIGNAL(clicked()), this, SLOT(addTheRows()));
  10620. @ The model will have three columns: Time, Temperature, and Annotation. This
  10621. probably should not be hard coded.
  10622. @<Prepare the model@>=
  10623. model->setHeaderData(0, Qt::Horizontal, "Time");
  10624. model->setHeaderData(1, Qt::Horizontal, "Temperature");
  10625. model->setHeaderData(2, Qt::Horizontal, "Annotation");
  10626. model->clear();
  10627. @ The profile is presented in a table view. The columns should be wide enough to
  10628. contain a label, the data contained in the column, and an editor delegate.
  10629. @<Prepare the log table@>=
  10630. log->setModel(model);
  10631. log->setColumnWidth(0, 100);
  10632. log->setColumnWidth(1, 100);
  10633. log->setColumnWidth(2, 100);
  10634. @ Most users will want to save a profile after they'@q'@>ve edited it. We also
  10635. provide CSV export here. Note that this class only supports logs with a single
  10636. temperature and a single annotation column. As the class is considered
  10637. depreciated, it will not be extended to support arbitrarily many columns.
  10638. @<LogEditWindow Implementation@>=
  10639. void LogEditWindow::saveXML()
  10640. {
  10641. QSettings settings;
  10642. QString lastDir = settings.value("lastDirectory").toString();
  10643. QString filename = QFileDialog::getSaveFileName(this, tr("Save Log As..."),
  10644. lastDir, "", 0);
  10645. QFile file(filename);
  10646. XMLOutput writer(model, &file, 0);
  10647. writer.addTemperatureColumn("Temperature", 1);
  10648. writer.addAnnotationColumn("Annotation", 2);
  10649. if(writer.output())
  10650. {
  10651. QFileInfo info(filename);
  10652. QDir directory = info.dir();
  10653. lastDir = directory.path();
  10654. settings.setValue("lastDirectory", lastDir);
  10655. }
  10656. }
  10657. void LogEditWindow::saveCSV()
  10658. {
  10659. QSettings settings;
  10660. QString lastDir = settings.value("lastDirectory").toString();
  10661. QString filename = QFileDialog::getSaveFileName(this, tr("Export As..."),
  10662. lastDir, "", 0);
  10663. QFile file(filename);
  10664. CSVOutput writer(model, &file, 0);
  10665. writer.addTemperatureColumn("Temperature", 1);
  10666. writer.addAnnotationColumn("Annotation", 2);
  10667. if(writer.output())
  10668. {
  10669. QFileInfo info(filename);
  10670. QDir directory = info.dir();
  10671. lastDir = directory.path();
  10672. settings.setValue("lastDirectory", lastDir);
  10673. }
  10674. }
  10675. @ Some may want to open a previously saved profile, for example, to adjust the
  10676. position of an annotation. Note that this class is not appropriate for editing
  10677. profiles with more than one temperature column.
  10678. @<LogEditWindow Implementation@>=
  10679. void LogEditWindow::openXML()
  10680. {
  10681. QSettings settings;
  10682. QString lastDir = settings.value("lastDirectory").toString();
  10683. QString filename = QFileDialog::getOpenFileName(this, tr("Open XML Log..."),
  10684. lastDir, "", 0);
  10685. if(filename.isNull())
  10686. {
  10687. return;
  10688. }
  10689. QFile file(filename);
  10690. XMLInput reader(&file, 1);
  10691. connect(&reader, SIGNAL(measure(Measurement, int)),
  10692. model, SLOT(newMeasurement(Measurement, int)));
  10693. connect(&reader, SIGNAL(annotation(QString, int, int)),
  10694. model, SLOT(newAnnotation(QString, int, int)));
  10695. if(reader.input())
  10696. {
  10697. QFileInfo info(filename);
  10698. setWindowTitle(QString(tr("%1 - %2")).@|
  10699. arg(QCoreApplication::applicationName()).arg(info.baseName()));
  10700. QDir directory = info.dir();
  10701. lastDir = directory.path();
  10702. settings.setValue("lastDirectory", lastDir);
  10703. }
  10704. }
  10705. @ The window should remember its last size and position, so we store this
  10706. information in settings when the window is closed.
  10707. @<LogEditWindow Implementation@>=
  10708. void LogEditWindow::closeEvent(QCloseEvent *event)
  10709. {
  10710. QSettings settings;
  10711. settings.setValue("logSize", size());
  10712. settings.setValue("logPos", pos());
  10713. event->accept();
  10714. }
  10715. @ One function is required to instantiate this class from a script.
  10716. @<Function prototypes for scripting@>=
  10717. QScriptValue constructLogEditWindow(QScriptContext *context,
  10718. QScriptEngine *engine);
  10719. @ The engine must be informed of this function.
  10720. @<Set up the scripting engine@>=
  10721. constructor = engine->newFunction(constructLogEditWindow);
  10722. value = engine->newQMetaObject(&LogEditWindow::staticMetaObject, constructor);
  10723. engine->globalObject().setProperty("LogEditWindow", value);
  10724. @ The constructor just creates the window and passes it back to the engine.
  10725. @<Functions for scripting@>=
  10726. QScriptValue constructLogEditWindow(QScriptContext *, QScriptEngine *engine)
  10727. {
  10728. QScriptValue object = engine->newQObject(new LogEditWindow);
  10729. return object;
  10730. }
  10731. @** File IO.
  10732. \noindent So far, the data is all stored in memory. It is often useful to save
  10733. data to a file or read back previously saved data. Presently, two formats are
  10734. supported: an XML format which can also be read back in and CSV which can easily
  10735. be used with many external tools.
  10736. File IO is handled by a few classes: one per input format and one per output
  10737. format. The classes in the following sections should be simple enough to follow
  10738. that it should be clear how to extend \pn{} to support other formats if needed.
  10739. Should additional output formats be required, it may be beneficial to
  10740. reimplement the serializers as subclasses of a new abstract serializer class in
  10741. order to share common code among them where reusing \cweb{} chunks is not an
  10742. appropriate technique.
  10743. @* XML Output.
  10744. \noindent An XML format has been chosen as the native format for \pn{} because
  10745. of Qt'@q'@>s excellent support for reading and writing such documents. Using this
  10746. capability is less error prone than developing a new, more compact format.
  10747. Another reason to choose XML is that it becomes quite easy to modify saved data
  10748. in a text editor and still end up with something \pn{} will understand.
  10749. The structure of the file we will produce is simple, however it has been
  10750. modified from a simpler structure that was used in versions of Typica prior to
  10751. 1.2.3. How to read these files can be determined by the document type found at
  10752. the start of the file. At the start of the file, there should be one or more
  10753. {\tt <tempseries>} elements and one or more {\tt <noteseries>} elements. These
  10754. are empty elements with a {\tt name} attribute which can be used to label the
  10755. column in a view. Once these column declarations have been written, a
  10756. {\tt <roast>} element is produced which contains a set of zero or more
  10757. {\tt <tuple>} elements. Each tuple contains one {\tt <time>} element containing
  10758. the time of the measurement relative to the start of the batch and optionally
  10759. one or more {\tt <temperature>} and {\tt <annotation>} elements containing
  10760. measurement and annotation data associated with that time. The
  10761. {\tt <temperature>} and {\tt <annotation>} elements have a {\tt series}
  10762. attribute where the value of the attribute matches the {\tt name} attribute of a
  10763. {\tt <tempseries>} or {\tt <noteseries>} element which allows each measurement
  10764. to be placed in the correct data series regardless of element ordering in the
  10765. document.
  10766. There are certain oddities about this format compared with other XML based
  10767. formats. The order of some elements in the current implementation affects the
  10768. behavior of the program and there is no longer a proper root element. This
  10769. format may be extended in future versions of \pn{} to support additional
  10770. functionality or to improve the robustness of the format. Should such
  10771. modifications occur, an effort should be made to ensure that \pn{} continues to
  10772. support the import of old data.
  10773. As of version 1.0.8, this class is derived from |QObject| for easier integration
  10774. with the scripting engine.
  10775. The |temperatureColumns| and |annotationColumns| member data structures are
  10776. currently a |QMap| rather than a |QHash| because the number of data series in a
  10777. single file is likely to be small enough that the difference in lookup time
  10778. should be negligeable and the ability to iterate over the keys in the |QMap| in
  10779. sorted order is useful.
  10780. @<Class declarations@>=
  10781. class XMLOutput : public QObject@/
  10782. {@/
  10783. Q_OBJECT@;@/
  10784. MeasurementModel *data;
  10785. QIODevice *out;
  10786. int time;
  10787. QMap<int, QString> temperatureColumns;
  10788. QMap<int, QString> controlColumns;
  10789. QMap<int, QString> annotationColumns;
  10790. public:@/
  10791. XMLOutput(MeasurementModel *model, QIODevice *device, int timec = 0);
  10792. void addTemperatureColumn(const QString &series, int column);
  10793. void addControlColumn(const QString &series, int column);
  10794. void addAnnotationColumn(const QString &series, int column);
  10795. void setModel(MeasurementModel *model);
  10796. void setTimeColumn(int column);
  10797. void setDevice(QIODevice *device);
  10798. bool output();
  10799. };
  10800. @ The interesting part of this class is the |output| routine. This goes over the
  10801. data in the model and constructs an appropriate XML document. If the operation
  10802. fails, the function returns |false|, otherwise it returns |true|.
  10803. @<XMLOutput Implementation@>=
  10804. bool XMLOutput::output()@t\2\2@>@/
  10805. {@t\1@>@/
  10806. if(!out->open(QIODevice::WriteOnly | QIODevice::Text))@/
  10807. {@t\1@>@/
  10808. return false;@t\2@>@/
  10809. }@/
  10810. QXmlStreamWriter xmlout(out);
  10811. xmlout.writeStartDocument("1.0");
  10812. xmlout.writeDTD("<!DOCTYPE roastlog3.0>");
  10813. xmlout.writeStartElement("roastlog");
  10814. @<Output the column declarations@>@;
  10815. xmlout.writeStartElement("roast");
  10816. bool oresult;
  10817. for(int i = 0; i < data->rowCount(); i++)@/
  10818. {
  10819. @<Check if row should be output@>@;
  10820. if(oresult)
  10821. {
  10822. @<Output tuple element@>@;
  10823. }
  10824. }
  10825. xmlout.writeEndElement();
  10826. xmlout.writeEndElement();
  10827. xmlout.writeEndDocument();
  10828. out->close();@/
  10829. return true;@t\2@>@/
  10830. }
  10831. @ Temperature column declarations are output before annotation column
  10832. declarations. Within each category, column declarations are output in order by
  10833. column number.
  10834. @<Output the column declarations@>=
  10835. foreach(int c, temperatureColumns.keys())
  10836. {
  10837. xmlout.writeStartElement("tempseries");
  10838. xmlout.writeAttribute("name", temperatureColumns.value(c));
  10839. xmlout.writeEndElement();
  10840. }
  10841. foreach(int c, controlColumns.keys())
  10842. {
  10843. xmlout.writeStartElement("controlseries");
  10844. xmlout.writeAttribute("name", controlColumns.value(c));
  10845. xmlout.writeEndElement();
  10846. }
  10847. foreach(int c, annotationColumns.keys())
  10848. {
  10849. xmlout.writeStartElement("noteseries");
  10850. xmlout.writeAttribute("name", annotationColumns.value(c));
  10851. xmlout.writeEndElement();
  10852. }
  10853. @ When checking a row in the model to determine if it contains values that need
  10854. to be written, we want to know if any of the temperature or annotation columns
  10855. contain a value. If at least one of these columns is not empty for this row, we
  10856. need to output a tuple for that row.
  10857. @<Check if row should be output@>=
  10858. oresult = false;@/
  10859. foreach(int c, temperatureColumns.keys())@/
  10860. {@t\1@>@/
  10861. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10862. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  10863. {@t\1@>@/
  10864. oresult = true;
  10865. break;@t\2@>@/
  10866. }@t\2@>@/
  10867. }@/
  10868. foreach(int c, controlColumns.keys())
  10869. {
  10870. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10871. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))
  10872. {
  10873. oresult = true;
  10874. break;
  10875. }
  10876. }
  10877. if(oresult == false)@/
  10878. {@t\1@>@/
  10879. foreach(int c, annotationColumns.keys())@/
  10880. {@t\1@>@/
  10881. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10882. !(data->data(data->index(i, c), Qt::DisplayRole).toString().
  10883. isEmpty()))@/
  10884. {@t\1@>@/
  10885. oresult = true;
  10886. break;@t\2@>@/
  10887. }@t\2@>@/
  10888. }@t\2@>@/
  10889. }
  10890. @ Now that we know that values from the current row should be output, we can
  10891. produce a {\tt <tuple>} element, a {\tt <time>} element for that tuple, and then
  10892. iterate over the set of columns we might want to output, producing an
  10893. appropriate element for each non-empty column for that row.
  10894. @<Output tuple element@>=
  10895. xmlout.writeStartElement("tuple");
  10896. xmlout.writeTextElement("time", data->data(data->index(i, time),
  10897. Qt::DisplayRole).toString());
  10898. foreach(int c, temperatureColumns.keys())@/
  10899. {
  10900. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10901. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  10902. {
  10903. xmlout.writeStartElement("temperature");
  10904. xmlout.writeAttribute("series", temperatureColumns.value(c));
  10905. if(data->data(data->index(i, c), Qt::UserRole).toMap().contains("relative"))
  10906. {
  10907. if(data->data(data->index(i, c), Qt::UserRole).toMap().value("relative").toBool())
  10908. {
  10909. xmlout.writeAttribute("relative", "true");
  10910. }
  10911. }
  10912. xmlout.writeCharacters(data->data(data->index(i, c), Qt::DisplayRole).
  10913. toString());
  10914. xmlout.writeEndElement();
  10915. }
  10916. }
  10917. foreach(int c, controlColumns.keys())
  10918. {
  10919. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10920. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))
  10921. {
  10922. xmlout.writeStartElement("control");
  10923. xmlout.writeAttribute("series", controlColumns.value(c));
  10924. xmlout.writeCharacters(data->data(data->index(i, c), Qt::DisplayRole).toString());
  10925. xmlout.writeEndElement();
  10926. }
  10927. }
  10928. foreach(int c, annotationColumns.keys())@/
  10929. {
  10930. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10931. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  10932. {
  10933. xmlout.writeStartElement("annotation");
  10934. xmlout.writeAttribute("series", annotationColumns.value(c));
  10935. xmlout.writeCharacters(data->data(data->index(i, c), Qt::DisplayRole).
  10936. toString());
  10937. xmlout.writeEndElement();
  10938. }
  10939. }
  10940. xmlout.writeEndElement();
  10941. @ The rest of the class just initializes the private member data.
  10942. @<XMLOutput Implementation@>=
  10943. XMLOutput::XMLOutput(MeasurementModel *model, QIODevice *device, int timec)
  10944. : QObject(NULL), data(model), out(device), time(timec)@/
  10945. {
  10946. /* Nothing has to be done here. */
  10947. }@;
  10948. void XMLOutput::setModel(MeasurementModel *model)
  10949. {
  10950. data = model;
  10951. }
  10952. void XMLOutput::setTimeColumn(int column)
  10953. {
  10954. time = column;
  10955. }
  10956. void XMLOutput::setDevice(QIODevice *device)
  10957. {
  10958. out = device;
  10959. }
  10960. @ As of version 1.2.3, the old |setTemperatureColumn()| and
  10961. |setAnnotationColumn()| methods have been replaced with the
  10962. |addTemperatureColumn()| and |addAnnotationColumn()| methods respectively. The
  10963. main difference is that the new methods take a column name in addition to a
  10964. number and it is now possible to specify multiple columns of each category for
  10965. export.
  10966. @<XMLOutput Implementation@>=
  10967. void XMLOutput::addTemperatureColumn(const QString &series, int column)
  10968. {
  10969. temperatureColumns.insert(column, series);
  10970. }
  10971. void XMLOutput::addControlColumn(const QString &series, int column)
  10972. {
  10973. controlColumns.insert(column, series);
  10974. }
  10975. void XMLOutput::addAnnotationColumn(const QString &series, int column)
  10976. {
  10977. annotationColumns.insert(column, series);
  10978. }
  10979. @* XML Input.
  10980. \noindent Once model data can be saved to a file, it is useful to be able to
  10981. read that data back in. This is a little different from reading data out of a
  10982. model as more than one object is potentially interested in the data. Instead, we
  10983. emit signals for measurements and annotations. This class has been modified to
  10984. support both the current (as of version 1.2.3) output of the |XMLOutput| class
  10985. and the older version. If changes are made to |XMLOutput| this class may also
  10986. need to be modified.
  10987. The main differences in the current version of this class are that the first
  10988. column is specified rather than specifying temperature and annotation columns
  10989. separately and additional signals are emitted to allow views to prepare for an
  10990. arbitrary number of columns.
  10991. The |newTemperatureColumn| and |newAnnotationColumn| signals can be used to set
  10992. up column headers while the |lastColumn| signal can be used to shift live data
  10993. streams to unoccupied columns.
  10994. @<Class declarations@>=
  10995. class XMLInput : public QObject@/
  10996. {
  10997. Q_OBJECT@;
  10998. int firstc;
  10999. QIODevice *in;
  11000. public:@/
  11001. XMLInput(QIODevice *input, int c);
  11002. void setFirstColumn(int column);
  11003. void setDevice(QIODevice *device);
  11004. bool input();
  11005. signals:@/
  11006. void measure(Measurement, int);
  11007. void annotation(QString, int, int);
  11008. void newTemperatureColumn(int, QString);
  11009. void newAnnotationColumn(int, QString);
  11010. void lastColumn(int);
  11011. };
  11012. @ The main point of interest here is the |input()| method. If the file is read
  11013. successfully, |true| is returned. Otherwise, |false| is returned.
  11014. @<XMLInput Implementation@>=
  11015. bool XMLInput::input()@t\2\2@>@/
  11016. {@t\1@>@/
  11017. if(!in->open(QIODevice::ReadOnly | QIODevice::Text))@/
  11018. {@t\1@>@/
  11019. return false;@t\2@>@/
  11020. }@/
  11021. QXmlStreamReader xmlin(in);
  11022. QMap<QString, int> temperatureColumns;
  11023. QMap<QString, int> annotationColumns;
  11024. int nextColumn = firstc;
  11025. @<Read column declarations@>@;
  11026. QTime timeval = QTime();
  11027. double tempval = 0;
  11028. QString noteval = QString();
  11029. int column;
  11030. int counter = 0;@/
  11031. while(!xmlin.atEnd())@/
  11032. {@/
  11033. @<Read XML file@>@;
  11034. }@/
  11035. return true;@t\2@>@/
  11036. }
  11037. @ A data file may or may not contain elements that specify the name of a column.
  11038. In order to determine how to proceed, we should check the doctype of the input
  11039. file. This should be the first element of the input file encountered.
  11040. \danger There is not nearly enough error checking here.
  11041. \endanger
  11042. @<Read column declarations@>=
  11043. while(!xmlin.isDTD())
  11044. {
  11045. xmlin.readNext();
  11046. }
  11047. if(xmlin.isDTD())
  11048. {
  11049. if(xmlin.text() == "<!DOCTYPE roastlog>")
  11050. {
  11051. @<Emit old format column specification@>@;
  11052. }
  11053. else
  11054. {
  11055. xmlin.readNext();
  11056. @<Scan for column declarations and emit@>@;
  11057. }
  11058. }
  11059. @ Old format data will not have column declarations. This means that we must
  11060. produce a default set of signals rather than waiting to read elements describing
  11061. the columns.
  11062. @<Emit old format column specification@>=
  11063. emit newTemperatureColumn(firstc, "Bean");
  11064. emit newAnnotationColumn(firstc + 1, "Note");
  11065. emit lastColumn(firstc + 1);
  11066. @ The current format will have column declarations prior to the {\tt <roast>}
  11067. element. We can just read until we hit that element and emit the appropriate
  11068. signals as elements are encountered.
  11069. @<Scan for column declarations and emit@>=
  11070. while(xmlin.name() != "roast")
  11071. {
  11072. if(xmlin.isStartElement())
  11073. {
  11074. if((xmlin.name() == "tempseries") || (xmlin.name() == "controlseries"))
  11075. {
  11076. temperatureColumns.insert(xmlin.attributes().value("name").
  11077. toString(),
  11078. nextColumn);
  11079. emit newTemperatureColumn(nextColumn,
  11080. xmlin.attributes().value("name").
  11081. toString());
  11082. nextColumn++;
  11083. }
  11084. else if(xmlin.name() == "noteseries")
  11085. {
  11086. annotationColumns.insert(xmlin.attributes().value("name").
  11087. toString(), nextColumn);
  11088. emit newAnnotationColumn(nextColumn,
  11089. xmlin.attributes().value("name").
  11090. toString());
  11091. nextColumn++;
  11092. }
  11093. }
  11094. xmlin.readNext();
  11095. }
  11096. emit lastColumn(nextColumn - 1);
  11097. @ Now we are ready to read measurements from the file. When encountering a
  11098. {\tt <time>} element, we record the time and move on. For {\tt <temperature>}
  11099. and {\tt <annotation>} elements, we emit the appropriate signal. This is handled
  11100. slightly differently depending on which version of the file format is being
  11101. used. Note that there is not nearly enough error checking here and we are
  11102. basically ignoring {\tt <tuple>} elements.
  11103. Due to the typically large number of measurements taken over the course of a
  11104. roast and the amount of time often taken to process these measurements when they
  11105. are read from a file, there is a need to periodically pass control back to the
  11106. event loop to remain responsive to user input.
  11107. @<Read XML file@>=
  11108. xmlin.readNext();
  11109. if(xmlin.isStartElement())
  11110. {
  11111. @<Read measurement data@>@;
  11112. }
  11113. counter++;
  11114. if(counter % 100 == 0)
  11115. {
  11116. QCoreApplication::processEvents();
  11117. }
  11118. @ When reading start elements, it is safe to ignore {\tt <tuple>} and
  11119. {\tt <roast>}. Technically, this means that the program can read certain types
  11120. of invalid data. The Robustness Principle\nfnote{``Be liberal in what you
  11121. accept, and conservative in what you send,'' --- Robert Braden, {\it RFC 1122
  11122. \S 1.2.2}} is generally applicable to any type of data exchange. That said,
  11123. malformed data is not guaranteed readable in the future, even if it does work
  11124. now.
  11125. \danger One set of test input caused this code to emit an empty annotation for
  11126. every measurement. This is the reason for wrapping the annotation signal
  11127. emission to check for this. The detected annotation elements were not present in
  11128. the input stream and I have absolutely no idea where the program came up with
  11129. them. \endanger
  11130. @<Read measurement data@>=
  11131. if(xmlin.name() == "time")
  11132. {
  11133. timeval = QTime::fromString(xmlin.readElementText(), "mm:ss.zzz");
  11134. }
  11135. else if(xmlin.name() == "temperature")
  11136. {
  11137. column = xmlin.attributes().hasAttribute("series") ?
  11138. temperatureColumns.value(xmlin.attributes().value("series").toString()) : firstc;
  11139. bool relative = (xmlin.attributes().value("relative") == "true");
  11140. tempval = xmlin.readElementText().toDouble();
  11141. Measurement measurement(tempval, timeval);
  11142. if(relative)
  11143. {
  11144. measurement.insert("relative", true);
  11145. }
  11146. emit measure(measurement, column);
  11147. }
  11148. else if(xmlin.name() == "control")
  11149. {
  11150. column = xmlin.attributes().value("series").toString().isEmpty() ?
  11151. firstc : temperatureColumns.value(xmlin.attributes().
  11152. value("series").toString());
  11153. tempval = xmlin.readElementText().toDouble();
  11154. Measurement measurement(tempval, timeval, Units::Unitless);
  11155. emit measure(measurement, column);
  11156. }
  11157. else if(xmlin.name() == "annotation")
  11158. {
  11159. column = xmlin.attributes().value("series").toString().isEmpty() ?
  11160. firstc + 1 : annotationColumns.value(xmlin.attributes().
  11161. value("series").toString());
  11162. noteval = xmlin.readElementText();
  11163. if(!noteval.isEmpty())
  11164. {
  11165. emit annotation(noteval, firstc, column);
  11166. }
  11167. }
  11168. @ The other methods just set the private member data.
  11169. @<XMLInput Implementation@>=
  11170. XMLInput::XMLInput(QIODevice *input, int c) :
  11171. firstc(c), in(input)@/
  11172. {@/
  11173. /* Nothing has to be done here. */
  11174. }
  11175. void XMLInput::setFirstColumn(int column)
  11176. {
  11177. firstc = column;
  11178. }
  11179. void XMLInput::setDevice(QIODevice *device)
  11180. {
  11181. in = device;
  11182. }
  11183. @ In order to allow scripts to instantiate the |XMLInput| class, we need a
  11184. constructor and a wrapper around the |input()| method.
  11185. @<Function prototypes for scripting@>=
  11186. QScriptValue constructXMLInput(QScriptContext *context, QScriptEngine *engine);
  11187. QScriptValue XMLInput_input(QScriptContext *context, QScriptEngine *engine);
  11188. @ The script constructor is passed to the scripting engine.
  11189. @<Set up the scripting engine@>=
  11190. constructor = engine->newFunction(constructXMLInput);
  11191. value = engine->newQMetaObject(&XMLInput::staticMetaObject, constructor);
  11192. engine->globalObject().setProperty("XMLInput", value);
  11193. @ The implementation should seem familiar.
  11194. @<Functions for scripting@>=
  11195. QScriptValue constructXMLInput(QScriptContext *context, QScriptEngine *engine)
  11196. {
  11197. QIODevice *device = argument<QIODevice *>(0, context);
  11198. QScriptValue object = engine->newQObject(new XMLInput(&*device,
  11199. argument<int>(1, context)));
  11200. object.setProperty("input", engine->newFunction(XMLInput_input));
  11201. return object;
  11202. }
  11203. QScriptValue XMLInput_input(QScriptContext *context, QScriptEngine *)
  11204. {
  11205. XMLInput *self = getself<@[XMLInput *@]>(context);
  11206. self->input();
  11207. return QScriptValue();
  11208. }
  11209. @* CSV Output.
  11210. \noindent While XML is convenient for \pn{}, other programs may not handle this
  11211. format well. For this purpose, we use a text file with comma separated values.
  11212. Data in this format can easily be handled by shell scripts, simple programs, and
  11213. any spreadsheet (though some may handle the time column poorly).
  11214. We do not need to concern ourselves with reading data in this format back in,
  11215. but there is no reason a class could not be written to do this.
  11216. The structure of this class is very similar to the |XMLOutput| class.
  11217. @<Class declarations@>=
  11218. class CSVOutput@/
  11219. {@/
  11220. MeasurementModel *data;
  11221. QIODevice *out;
  11222. int time;
  11223. QMap<int, QString> temperatureColumns;
  11224. QMap<int, QString> controlColumns;
  11225. QMap<int, QString> annotationColumns;@/
  11226. public:@/
  11227. CSVOutput(MeasurementModel *model, QIODevice *device, int timec = 0);
  11228. void addTemperatureColumn(const QString &series, int column);
  11229. void addControlColumn(const QString &series, int column);
  11230. void addAnnotationColumn(const QString &series, int column);
  11231. void setModel(MeasurementModel *model);
  11232. void setTimeColumn(int column);
  11233. void setDevice(QIODevice *device);
  11234. bool output();@/
  11235. };
  11236. @ Very little needs to be done to output the data. We open the output stream
  11237. and, if the output stream was successfully opened, we look for measurements and
  11238. output the text, remembering to output a comma between items and a newline after
  11239. each record. If the data is successfully output, |true| is returned, otherwise
  11240. we return |false|.
  11241. The comparably simple structure of the CSV format allows us to just fling the
  11242. data onto a text stream.
  11243. @<CSVOutput Implementation@>=
  11244. bool CSVOutput::output()@t\2\2@>@/
  11245. {@t\1@>@/
  11246. if(!out->open(QIODevice::WriteOnly | QIODevice::Text))@/
  11247. {@t\1@>@/
  11248. return false;@t\2@>@/
  11249. }@/
  11250. QTextStream output(out);
  11251. @<Output CSV column headers@>@;
  11252. bool oresult;
  11253. for(int i = 0; i < data->rowCount(); i++)@/
  11254. {
  11255. @<Check if row should be output@>@;
  11256. if(oresult)
  11257. {
  11258. @<Output CSV row@>@;
  11259. }
  11260. }
  11261. out->close();@/
  11262. return true;@t\2@>@/
  11263. }
  11264. @ Before writing the data, we output a row containing the name of each column.
  11265. @<Output CSV column headers@>=
  11266. output << "Time";
  11267. foreach(int c, temperatureColumns.keys())
  11268. {
  11269. output << ',' << temperatureColumns.value(c);
  11270. }
  11271. foreach(int c, controlColumns.keys())
  11272. {
  11273. output << ',' << controlColumns.value(c);
  11274. }
  11275. foreach(int c, annotationColumns.keys())
  11276. {
  11277. output << ',' << annotationColumns.value(c);
  11278. }
  11279. output << '\n';
  11280. @ Once the header information has been written, we can proceed to output the
  11281. real data. The algorithm for doing this has been changed as of version 1.2.3
  11282. with the result that most uses will now produce more delimiters than the same
  11283. data in previous versions. This should have no impact on the ability of other
  11284. programs to interact with data produced by \pn{}. The code to handle output in
  11285. this way is much easier to read. A future version might once again suppress
  11286. superfluous commas, however the presence of these commas is not considered a
  11287. serious issue at this time.
  11288. @<Output CSV row@>=
  11289. output << data->data(data->index(i, time), Qt::DisplayRole).toString();
  11290. foreach(int c, temperatureColumns.keys())
  11291. {
  11292. output << ',' << data->data(data->index(i, c), Qt::DisplayRole).toString();
  11293. }
  11294. foreach(int c, controlColumns.keys())
  11295. {
  11296. output << ',' << data->data(data->index(i, c), Qt::DisplayRole).toString();
  11297. }
  11298. foreach(int c, annotationColumns.keys())
  11299. {
  11300. output << ',' << data->data(data->index(i, c), Qt::DisplayRole).toString();
  11301. }
  11302. output << '\n';
  11303. @ The rest of the class just initializes the private member data. See notes
  11304. on the implementation of |XMLOutput|.
  11305. @<CSVOutput Implementation@>=
  11306. CSVOutput::CSVOutput(MeasurementModel *model, QIODevice *device, int timec) :
  11307. data(model), out(device), time(timec)@/
  11308. {
  11309. /* Nothing has to be done here. */
  11310. }@;
  11311. void CSVOutput::setModel(MeasurementModel *model)
  11312. {
  11313. data = model;
  11314. }
  11315. void CSVOutput::setTimeColumn(int column)
  11316. {
  11317. time = column;
  11318. }
  11319. void CSVOutput::addTemperatureColumn(const QString &series, int column)
  11320. {
  11321. temperatureColumns.insert(column, series);
  11322. }
  11323. void CSVOutput::addControlColumn(const QString &series, int column)
  11324. {
  11325. controlColumns.insert(column, series);
  11326. }
  11327. void CSVOutput::addAnnotationColumn(const QString &series, int column)
  11328. {
  11329. annotationColumns.insert(column, series);
  11330. }
  11331. void CSVOutput::setDevice(QIODevice *device)
  11332. {
  11333. out = device;
  11334. }
  11335. @i webview.w
  11336. @i printerselector.w
  11337. @* The Application class.
  11338. The |Application| class represents the \pn{} program. It is responsible for
  11339. setting up the settings object and localization in addition to the normal
  11340. responsibilities of |QApplication|. In addition to declaring the class, we also
  11341. define a macro that returns the |Application| instance.
  11342. @<Class declarations@>=
  11343. #define AppInstance (qobject_cast<@[Application *@]>(qApp))
  11344. class NodeInserter;
  11345. class DeviceTreeModel;
  11346. class DatabaseNotification;
  11347. class Application : public QApplication@/
  11348. {@/
  11349. @[Q_OBJECT@]@;
  11350. public:@/
  11351. Application(int &argc, char **argv);
  11352. QDomDocument* configuration();
  11353. @<Device configuration members@>@;
  11354. QSqlDatabase database();
  11355. Q_INVOKABLE bool databaseConnected();
  11356. Q_INVOKABLE QString currentTypicaUser();
  11357. Q_INVOKABLE bool login(const QString &user, const QString &password);
  11358. Q_INVOKABLE bool autoLogin();
  11359. QScriptEngine *engine;
  11360. QNetworkAccessManager *network;
  11361. DatabaseNotification *subscribe(const QString &notification);@/
  11362. @[public slots@]:@/
  11363. void setDatabaseConnected(bool status);
  11364. void setCurrentTypicaUser(const QString &user);
  11365. void notify(const QString &notification);
  11366. @<Extended Application slots@>@;
  11367. @[signals@]:@/
  11368. void userChanged(const QString &user);
  11369. private:@/
  11370. @<Application private data members@>@;
  11371. QDomDocument conf;
  11372. bool connectionStatus;
  11373. QString currentUser;
  11374. QMap<QString, DatabaseNotification*> notifiers;
  11375. QSqlDriver *notificationDriver;
  11376. };
  11377. @ The constructor for this class handles a few things that had previously been
  11378. handled in |main()|.
  11379. @<Application Implementation@>=
  11380. Application::Application(int &argc, char **argv) : QApplication(argc, argv),
  11381. connectionStatus(false), currentUser(QString())@/
  11382. {
  11383. network = new QNetworkAccessManager(this);
  11384. @<Allow use of the default QSettings constructor@>@;
  11385. @<Load translation objects@>@;
  11386. @<Register meta-types@>@;
  11387. @<Register top level device configuration nodes@>@;
  11388. }
  11389. @ We use |QSettings| objects throughout \pn{} to remember details such as the
  11390. size and position of windows and the most recently used directory. To simplify
  11391. the creation of these objects, we specify some details up front. This allows us
  11392. to use the default constructor rather than specifying these things every time we
  11393. need an object.
  11394. @<Allow use of the default QSettings constructor@>=
  11395. setOrganizationName("Wilson's Coffee & Tea");
  11396. setOrganizationDomain("wilsonscoffee.com");
  11397. setApplicationName(PROGRAM_NAME);
  11398. @ Much of the user visible text in \pn{} is wrapped in a call to |tr()|. Such
  11399. text can be replaced with translated text based on the user'@q'@>s locale. For more
  11400. details, see the Qt Linguist manual.
  11401. @<Load translation objects@>=
  11402. QTranslator *base = new QTranslator;
  11403. if(base->load(QString("qt_%1").arg(QLocale::system().name()), QString("%1/Translations").arg(QCoreApplication::applicationDirPath())))
  11404. {
  11405. installTranslator(base);
  11406. }
  11407. QTranslator *app = new QTranslator;
  11408. if(app->load(QString("%1_%2").arg("Typica").arg(QLocale::system().name()), QString("%1/Translations").arg(QCoreApplication::applicationDirPath())))
  11409. {
  11410. installTranslator(app);
  11411. }
  11412. @ We also want to be able to access the application instance from within the
  11413. scripting engine. We don'@q'@>t need to be able to create new instances, just access the one that already exists.
  11414. @<Set up the scripting engine@>=
  11415. value = engine->newQObject(AppInstance);
  11416. value.setProperty("subscribe", engine->newFunction(Application_subscribe));
  11417. engine->globalObject().setProperty("Application", value);
  11418. @ The |configuration()| method provides access to an XML document containing the
  11419. current application configuration. The object is populated in |main()|.
  11420. @<Application Implementation@>=
  11421. QDomDocument* Application::configuration()
  11422. {
  11423. return &conf;
  11424. }
  11425. @ The |database()| method provides access to a database connection for use by
  11426. database aware widgets.
  11427. @<Application Implementation@>=
  11428. QSqlDatabase Application::database()
  11429. {
  11430. QString connectionName;
  11431. QSqlDatabase connection =
  11432. QSqlDatabase::database(QLatin1String(QSqlDatabase::defaultConnection), false);
  11433. do
  11434. {
  11435. connectionName = QUuid::createUuid().toString();
  11436. } while (QSqlDatabase::connectionNames().contains(connectionName));
  11437. return QSqlDatabase::cloneDatabase(connection, QString(connectionName));
  11438. }
  11439. @ Starting with version 1.8 there are methods for determining if a connection
  11440. to the database was successfully established when Typica was opened.
  11441. @<Application Implementation@>=
  11442. void Application::setDatabaseConnected(bool status)
  11443. {
  11444. connectionStatus = status;
  11445. }
  11446. bool Application::databaseConnected()
  11447. {
  11448. return connectionStatus;
  11449. }
  11450. @ Database notifications allow various parts of Typica to be aware when data in
  11451. the database may have been changed by another instance of Typica running on a
  11452. different computer or by another program that uses the same database. To pass
  11453. notifications to the various places that may be interested in these and not
  11454. bother notification aware controls that are uninterested in unrelated
  11455. notifications, a notification object is created for each notification.
  11456. Note that the notification channel is an identifier and unquoted identifiers
  11457. will be converted to lowercase while \pn{} will attempt to match subscribed to
  11458. notifications exactly. This means that it is generally a good idea to subscribe
  11459. with the channel specified in lowercase.
  11460. @<Application Implementation@>=
  11461. DatabaseNotification* Application::subscribe(const QString &notification)
  11462. {
  11463. DatabaseNotification *retval;
  11464. if(notifiers.contains(notification))
  11465. {
  11466. retval = notifiers.value(notification);
  11467. }
  11468. else
  11469. {
  11470. if(notifiers.size() == 0)
  11471. {
  11472. notificationDriver = QSqlDatabase::database().driver();
  11473. connect(notificationDriver, SIGNAL(notification(QString)), this, SLOT(notify(QString)));
  11474. }
  11475. retval = new DatabaseNotification;
  11476. connect(this, SIGNAL(aboutToQuit()), retval, SLOT(deleteLater()));
  11477. if(notifiers.size() !=
  11478. notificationDriver->subscribedToNotifications().size())
  11479. {
  11480. for(int i = 0; i < notifiers.size(); i++)
  11481. {
  11482. notificationDriver->subscribeToNotification(notifiers.keys().at(i));
  11483. }
  11484. }
  11485. notifiers.insert(notification, retval);
  11486. notificationDriver->subscribeToNotification(notification);
  11487. }
  11488. return retval;
  11489. }
  11490. @ As the various parts of \pn{} operate mostly indepent of each other and
  11491. notifications from the current instance may not be immediately returned, it is
  11492. generally a good idea for operations that would generate a notification to also
  11493. signal that notification within the application.
  11494. @<Application Implementation@>=
  11495. void Application::notify(const QString &notification)
  11496. {
  11497. if(notifiers.contains(notification))
  11498. {
  11499. DatabaseNotification *notifier = notifiers.value(notification);
  11500. notifier->forwardNotification(notification);
  11501. }
  11502. }
  11503. @ A function is provided to allow subscribing to notifications from scripts.
  11504. @<Function prototypes for scripting@>=
  11505. QScriptValue Application_subscribe(QScriptContext *context,
  11506. QScriptEngine *engine);
  11507. @ The implementation is trivial.
  11508. @<Functions for scripting@>=
  11509. QScriptValue Application_subscribe(QScriptContext *context,
  11510. QScriptEngine *engine)
  11511. {
  11512. return engine->newQObject(
  11513. AppInstance->subscribe(argument<QString>(0, context)));
  11514. }
  11515. @ The DatabaseNotification object just needs a signal that interested objects
  11516. can connect to.
  11517. @<Class declarations@>=
  11518. class DatabaseNotification : public QObject
  11519. {
  11520. Q_OBJECT
  11521. public:
  11522. DatabaseNotification();
  11523. public slots:
  11524. void forwardNotification(const QString &notification);
  11525. signals:
  11526. void notify(const QString &notification);
  11527. };
  11528. @ The implementation is trivial.
  11529. @<Class declarations@>=
  11530. DatabaseNotification::DatabaseNotification() : QObject(NULL)
  11531. {
  11532. /* Nothing needs to be done here. */
  11533. }
  11534. void DatabaseNotification::forwardNotification(const QString &notification)
  11535. {
  11536. emit notify(notification);
  11537. }
  11538. @** Table editor for ordered arrays with SQL relations.
  11539. \noindent A database in use at Wilson's Coffee \char'046~Tea stores information
  11540. for a roasting log and uses entered information to adjust inventory tracking
  11541. tables. This roasting log connects the use of unroasted coffee with the creation
  11542. of roasted coffee. In order to support roasting coffee from more than one lot at
  11543. the same time, the columns that specify the types of coffee used and the amount
  11544. of each coffee are entered as ordered arrays in which the first entry in the
  11545. array specifying an unroasted coffee is associated with the first entry in the
  11546. array specifying the amount of coffee used. While most batches will involve only
  11547. a single unroasted coffee, the database has no limitation on the number of
  11548. coffees that may be roasted in a single batch. An additional characteristic of
  11549. this table is that the database requires an identification number for unroasted
  11550. coffee items, but it would be better to provide a list of acceptable items with
  11551. human readable names.
  11552. A scrollable area containing a table view which can provide the necessary input
  11553. delegates (such as a combo box for SQL relations) and validators which ensures
  11554. that there is always at least one empty row available for input with convenience
  11555. functions for extracting the arrays needed for database insertion would be ideal
  11556. for this.
  11557. To get this, we need a simple table model based on |QStandardItemModel|
  11558. or |QAbstractItemModel|. The model should ensure that there is always at least
  11559. one empty row available for editing. It should also provide a function for
  11560. obtaining a string that presents all values from a specified column with a given
  11561. role as an array literal suitable for binding to an SQL query.
  11562. A class based on |QComboBox| providing options selected from an SQL query will
  11563. be needed. This can be used as a standalone widget elsewhere, but here it is
  11564. also needed as an editor class for a column delegate. Another delegate class
  11565. allows input in another column to be constrained by a |QValidator| (in this case
  11566. a |QDoubleValidator|).
  11567. A class based on |QTableView| brings all of these classes together and presents
  11568. them to the user.
  11569. @* A table model for producing SQL array literals.
  11570. \noindent This is a simple table model which provides two somewhat unusual
  11571. features. First, it always provides at least one empty row at the end of the
  11572. data. Second, it provides SQL array literals for columns in the model.
  11573. \danger At some point I would like to replace this model and |MeasurementModel|
  11574. with an improved table model suitable to replace both. Some preliminary design
  11575. work suggests that this improvement simplifies \pn{} considerably both
  11576. internally and in the data flow configuration. This has not yet been done due to
  11577. development time constraints.\endanger
  11578. @<Class declarations@>=
  11579. class SaltModel : public QAbstractItemModel@/
  11580. {
  11581. Q_OBJECT@t\2\2@>@/
  11582. QList<QList<QMap<int, QVariant> > > modelData;
  11583. QStringList hData;
  11584. int colcount;@t\1\1@>@/
  11585. public:@/
  11586. SaltModel(int columns);
  11587. ~SaltModel();
  11588. int rowCount(const QModelIndex &parent = QModelIndex()) const;
  11589. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  11590. bool setHeaderData(int section, Qt::Orientation@, orientation,
  11591. const QVariant &value, int role = Qt::DisplayRole);
  11592. QVariant data(const QModelIndex &index, int role) const;
  11593. bool setData(const QModelIndex &index, const QVariant &value,
  11594. int role = Qt::EditRole);
  11595. Qt::ItemFlags@, flags(const QModelIndex &index) const;
  11596. QVariant headerData(int section, Qt::Orientation@, orientation,
  11597. int role = Qt::DisplayRole) const;
  11598. QModelIndex index(int row, int column,
  11599. const QModelIndex &parent = QModelIndex()) const;
  11600. QModelIndex parent(const QModelIndex &index) const;
  11601. QString arrayLiteral(int column, int role) const;
  11602. QString quotedArrayLiteral(int column, int role) const;
  11603. void clear();
  11604. bool removeRows(int row, int count,
  11605. const QModelIndex &parent = QModelIndex());
  11606. int findData(const QVariant &value, int column, int role = Qt::UserRole);
  11607. };
  11608. @ The only unique methods in this class are the |arrayLiteral| and
  11609. |quotedArrayLiteral| methods. These take a column number and a data role and
  11610. produce a SQL array literal for every entry in that column with the specified
  11611. role. The string will take the form of
  11612. {\tt{'\LB row 1, row 2, }}$\dots$ {\tt{row N\RB '}}.
  11613. This is done simply by starting with a string identifying the start of an array
  11614. literal, looping over the rows in the model while appending any data found along
  11615. with the commas to separate values. If any data is found, the extra comma and
  11616. space are removed from the constructed string. Finally, text marking the end of
  11617. the array literal is added.
  11618. The |arrayLiteral| method is appropriate where the expected values are numeric.
  11619. The |quotedArrayLiteral| method is appropriate where the expected values are
  11620. text. The values in the array will have quotation marks around them for the
  11621. |quotedArrayLiteral|. Note that when binding these values to placeholders in a
  11622. SQL query the leading and trailing single quote characters should be removed.
  11623. \danger The way this method is currently used is quite harmless. Data from one
  11624. column is integer data obtained as a result of a previous database query and
  11625. data from the other column is restricted by the view to numeric data. Please
  11626. note, however, that it would be extremely stupid to use code such as this when
  11627. user input cannot be controlled so tightly. Were this model used with a view
  11628. that allows general text input, it would be trivial to construct an SQL
  11629. injection attack.
  11630. \medskip
  11631. \centerline{\includegraphics[width=6in]{exploits_of_a_mom}}
  11632. \smallskip
  11633. \centerline{Figure \secno: An Example of an SQL injection attack.\nfnote{%
  11634. Comic copyright Randall Munroe. Original can be found at:~%
  11635. \pdfURL{%
  11636. http://xkcd.com/327/}%
  11637. {http://xkcd.com/327/}}}
  11638. \medskip
  11639. \endanger
  11640. @<SaltModel Implementation@>=
  11641. QString SaltModel::arrayLiteral(int column, int role) const
  11642. {
  11643. QString literal = "'{";
  11644. for(int i = 0; i < rowCount(); i++)
  11645. {
  11646. QString datum = data(index(i, column), role).toString();
  11647. if(!datum.isEmpty())
  11648. {
  11649. literal.append(datum);
  11650. literal.append(", ");
  11651. }
  11652. }
  11653. if(literal.size() > 2)
  11654. {
  11655. literal.chop(2);
  11656. }
  11657. literal.append("}'");
  11658. return literal;
  11659. }
  11660. QString SaltModel::quotedArrayLiteral(int column, int role) const
  11661. {
  11662. QString literal = "'{";
  11663. for(int i = 0; i < rowCount(); i++)
  11664. {
  11665. QString datum = data(index(i, column), role).toString();
  11666. if(!datum.isEmpty())
  11667. {
  11668. literal.append("\"");
  11669. literal.append(datum);
  11670. literal.append("\", ");
  11671. }
  11672. }
  11673. if(literal.size() > 2)
  11674. {
  11675. literal.chop(2);
  11676. }
  11677. literal.append("}'");
  11678. return literal;
  11679. }
  11680. @ No entries in this model have children.
  11681. @<SaltModel Implementation@>=
  11682. QModelIndex SaltModel::parent(const QModelIndex &) const
  11683. {
  11684. return QModelIndex();
  11685. }
  11686. @ The |setData()| method is called by delegates on views when the user enters
  11687. new data. This method must check to determine if the data is being entered in
  11688. the last row to increase the size of the table.
  11689. The end of this function may seem a little strange. Why not simply look up the
  11690. map and insert information directly into the model data? Well, as of this
  11691. writing, that doesn'@q'@>t work. There are two ways around that problem. One is to
  11692. have the lists store references and dereference the real data. The other option
  11693. is to obtain a copy of the row, then a copy of the cell, update the cell, then
  11694. replace the old value of the cell in the copy of the row, then replace the old
  11695. values of the row in the real data. The other option would probably be more
  11696. efficient, but this does work.
  11697. @<SaltModel Implementation@>=
  11698. bool SaltModel::setData(const QModelIndex &index, const QVariant &value,
  11699. int role)@t\2\2@>@/
  11700. {@t\1@>@/
  11701. @<Check that the SaltModel index is valid@>@;
  11702. if(!valid)@/
  11703. {@t\1@>@/
  11704. return false;@t\2@>@/
  11705. }
  11706. if(index.row() == modelData.size() - 1)@/
  11707. {
  11708. beginInsertRows(QModelIndex(), modelData.size(), modelData.size());
  11709. @<Expand the SaltModel@>@;
  11710. endInsertRows();
  11711. }
  11712. QList<QMap<int, QVariant> > row = modelData.at(index.row());
  11713. QMap<int, QVariant> cell = row.at(index.column());
  11714. cell.insert(role, value);
  11715. if(role == Qt::EditRole)@/
  11716. {
  11717. cell.insert(Qt::DisplayRole, value);
  11718. }
  11719. row.replace(index.column(), cell);
  11720. modelData.replace(index.row(), row);
  11721. emit dataChanged(index, index);@/
  11722. return true;@t\2@>@/
  11723. }
  11724. @ Some model operations require checking that a model index is valid. This
  11725. chunk is used in these cases.
  11726. @<Check that the SaltModel index is valid@>=
  11727. bool valid = false;@/
  11728. if(index.isValid())@/
  11729. {@t\1@>@/
  11730. if(index.row() < modelData.size())@/
  11731. {@t\1@>@/
  11732. if(index.column() < colcount)@/
  11733. {@t\1@>@/
  11734. valid = true;@t\2@>@/
  11735. }@t\2@>@/
  11736. }@t\2@>@/
  11737. }
  11738. @ When data is modified in the last row of the table, the model must be expanded
  11739. to allow for additional data.
  11740. @<Expand the SaltModel@>=
  11741. QList<QMap<int, QVariant> > newRow;
  11742. QMap<int, QVariant> defaults;
  11743. for(int i = 0; i < colcount; i++)
  11744. {
  11745. newRow.append(defaults);
  11746. }
  11747. modelData.append(newRow);
  11748. @ The number of columns in the table is specified in the model constructor.
  11749. @<SaltModel Implementation@>=
  11750. SaltModel::SaltModel(int columns) : QAbstractItemModel(), colcount(columns)
  11751. {
  11752. for(int i = 0; i < columns; i++)
  11753. {
  11754. hData << "";
  11755. }
  11756. @<Expand the SaltModel@>@;
  11757. }
  11758. @ The destructor doesn'@q'@>t need to do anything.
  11759. @<SaltModel Implementation@>=
  11760. SaltModel::~SaltModel()
  11761. {
  11762. /* Nothing needs to be done here. */
  11763. }
  11764. @ A pair of methods provide the number of rows and columns in the model. No
  11765. entries in the model have children, so the parent should always be the invisible
  11766. root object.
  11767. @<SaltModel Implementation@>=
  11768. int SaltModel::rowCount(const QModelIndex &parent) const
  11769. {
  11770. return (parent == QModelIndex() ? modelData.size() : 0);
  11771. }
  11772. int SaltModel::columnCount(const QModelIndex &parent) const
  11773. {
  11774. return (parent == QModelIndex() ? colcount : 0);
  11775. }
  11776. @ The model maintains header data for labeling the model columns.
  11777. @<SaltModel Implementation@>=
  11778. bool SaltModel::setHeaderData(int section, Qt::Orientation@, orientation,@|
  11779. const QVariant &value, int)@t\2\2@>@/
  11780. {@t\1@>@/
  11781. if(orientation == Qt::Horizontal && section < colcount)@/
  11782. {@t\1@>@/
  11783. hData.replace(section, value.toString());@/
  11784. emit headerDataChanged(orientation, section, section);@/
  11785. return true;@t\2@>@/
  11786. }@/
  11787. return false;@t\2@>@/
  11788. }
  11789. @ Views need to be able to retrieve model and header data.
  11790. @<SaltModel Implementation@>=
  11791. QVariant SaltModel::data(const QModelIndex &index, int role) const
  11792. {
  11793. @<Check that the SaltModel index is valid@>@;
  11794. if(!valid)
  11795. {
  11796. return QVariant();
  11797. }
  11798. QList<QMap<int,QVariant> > row = modelData.at(index.row());
  11799. QMap<int,QVariant> cell = row.at(index.column());
  11800. return cell.value(role, QVariant());
  11801. }
  11802. QVariant SaltModel::headerData(int section, Qt::Orientation@, orientation,
  11803. int role) const
  11804. {
  11805. if(orientation == Qt::Horizontal && role == Qt::DisplayRole &&
  11806. section < colcount)
  11807. {
  11808. return QVariant(hData.at(section));
  11809. }
  11810. return QVariant();
  11811. }
  11812. @ Views need to know certain details such as if an item in the view can be
  11813. altered by the view. For this model, all valid indices can be edited.
  11814. @<SaltModel Implementation@>=
  11815. Qt::ItemFlags SaltModel::flags(const QModelIndex &index) const
  11816. {
  11817. @<Check that the SaltModel index is valid@>@;
  11818. if(valid)
  11819. {
  11820. return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled;
  11821. }
  11822. return 0;
  11823. }
  11824. @ So far, many of the methods use model indices. The model is responsible for
  11825. creating these.
  11826. @<SaltModel Implementation@>=
  11827. QModelIndex SaltModel::index(int row, int column,
  11828. const QModelIndex &parent) const
  11829. {
  11830. if(parent == QModelIndex())
  11831. {
  11832. if(row < modelData.size() && column < colcount)
  11833. {
  11834. return createIndex(row, column);
  11835. }
  11836. }
  11837. return QModelIndex();
  11838. }
  11839. @ There are some times when it is useful to clear the model data. Note that
  11840. column header data is retained and the table will contain a single empty row
  11841. after this method is called.
  11842. @<SaltModel Implementation@>=
  11843. void SaltModel::clear()
  11844. {
  11845. beginResetModel();
  11846. modelData.clear();
  11847. @<Expand the SaltModel@>@;
  11848. endResetModel();
  11849. }
  11850. @ Another commonly useful operation is the ability to remove rows from the
  11851. model. The new batch window uses this feature to eliminate rows in which the
  11852. coffee is set to NULL. Note that if all rows of the model are removed, a new
  11853. empty row will be created.
  11854. @<SaltModel Implementation@>=
  11855. bool SaltModel::removeRows(int row, int count,
  11856. const QModelIndex &parent)
  11857. {
  11858. if(parent == QModelIndex())
  11859. {
  11860. if(row >= 0 && count > 0 && (row + count - 1) < modelData.size())
  11861. {
  11862. beginRemoveRows(parent, row, row + count - 1);
  11863. for(int i = 0; i < count; i++)
  11864. {
  11865. modelData.removeAt(row);
  11866. }
  11867. endRemoveRows();
  11868. if(modelData.size() == 0)
  11869. {
  11870. beginInsertRows(parent, 0, 0);
  11871. @<Expand the SaltModel@>@;
  11872. endInsertRows();
  11873. }
  11874. return @[true@];
  11875. }
  11876. }
  11877. return @[false@];
  11878. }
  11879. @ To find the row number for removal operations it is useful to search for
  11880. special values on a given role. The |findData()| method returns the first row
  11881. in which the given value matches for a particular column and a particular role
  11882. or |-1| if no such match exists.
  11883. @<SaltModel Implementation@>=
  11884. int SaltModel::findData(const QVariant &value, int column, int role)
  11885. {
  11886. for(int i = 0; i < modelData.size(); i++)
  11887. {
  11888. if(modelData.at(i).size() > column)
  11889. {
  11890. if(modelData.at(i).at(column).contains(role))
  11891. {
  11892. if(modelData.at(i).at(column).value(role) == value)
  11893. {
  11894. return i;
  11895. }
  11896. }
  11897. }
  11898. }
  11899. return -1;
  11900. }
  11901. @* A Delegate for SQL Relations.
  11902. \noindent The first column of the table view being described is responsible for
  11903. providing item numbers to the database. Requiring that these numbers be entered
  11904. directly is prone to not particularly user friendly and almost encourages input
  11905. errors. These item numbers, however, refer to the items table in the database
  11906. which includes, among other details, a human readable text string naming the
  11907. item. This delegate provides the user with a drop down menu from which such a
  11908. string may be selected with this information provided by the database itself.
  11909. When the user selects an item, it informs the model not only of the text string
  11910. in the display role, but also of the id number in a user data role which can
  11911. later be queried in order to properly craft the appropriate query.
  11912. This is implemented with two classes. The first is a |QComboBox| which queries
  11913. the database and maintains a mapping of id to text. This is made its own widget
  11914. as it is useful without being turned into a delegate. The second class provides
  11915. this widget as a delegate and handles communications between it and the model.
  11916. @<Class declarations@>=
  11917. class SqlComboBox : public QComboBox@/
  11918. {@t\1@>@/
  11919. Q_OBJECT@;
  11920. int dataColumn;
  11921. int displayColumn;
  11922. bool dataColumnShown;
  11923. QString specialNullText;
  11924. QVariant specialNullData;
  11925. public:@/
  11926. SqlComboBox();
  11927. ~SqlComboBox();
  11928. SqlComboBox* clone(QWidget *parent);@/
  11929. @t\4@>public slots@t\kern-3pt@>:@/
  11930. void addNullOption();
  11931. void addSqlOptions(QString query);
  11932. void setDataColumn(int column);
  11933. void setDisplayColumn(int column);
  11934. void showData(bool show);
  11935. void setNullText(QString nullText);
  11936. void setNullData(QVariant nullData);@t\2@>@/
  11937. }@t\kern-3pt@>;
  11938. @ In order to make this class work a little more nicely as an item delegate,
  11939. the |clone()| method has been provided to create a new object with the same
  11940. options as a prototype.
  11941. @<SqlComboBox Implementation@>=
  11942. SqlComboBox* SqlComboBox::clone(QWidget *parent)
  11943. {
  11944. SqlComboBox *widget = new SqlComboBox();
  11945. widget->setParent(parent);
  11946. for(int i = 0; i < count(); i++)
  11947. {
  11948. widget->addItem(itemText(i), itemData(i));
  11949. }
  11950. return widget;
  11951. }
  11952. @ When using this class, we must first decide if the data column is shown. If
  11953. this is desired, the entries displayed will contain both the value from the
  11954. display column followed by the value from the data column. This can be useful in
  11955. cases where the same text is used for two different items.
  11956. @<SqlComboBox Implementation@>=
  11957. void SqlComboBox::showData(bool show)
  11958. {
  11959. dataColumnShown = show;
  11960. }
  11961. @ Next, there is a need to know if the NULL value may legally be selected. Where
  11962. this is the case, we generally want this to be inserted first. As the
  11963. |QComboBox| supports storing both display and user data, much of the code is a
  11964. thin wrapper around calls to the base class. The text and data for the NULL
  11965. value can be set arbitrarily, which can be useful in certain cases. Note that
  11966. any customization of the NULL text or data must be set before a call to
  11967. |addNullOption()|.
  11968. @<SqlComboBox Implementation@>=
  11969. void SqlComboBox::addNullOption()
  11970. {
  11971. addItem(specialNullText, specialNullData);
  11972. }
  11973. void SqlComboBox::setNullText(QString nullText)
  11974. {
  11975. specialNullText = nullText;
  11976. }
  11977. void SqlComboBox::setNullData(QVariant nullData)
  11978. {
  11979. specialNullData = nullData;
  11980. }
  11981. @ Typically, the SQL query used to populate this widget will request two columns
  11982. of data. One column is used as the display data, the other as user data. This is
  11983. done to present a human readable string where a database query needs an
  11984. identification number. By default, column |0| is used in both roles. If this
  11985. is not desired, the methods to change that must be called before specifying the
  11986. query.
  11987. @<SqlComboBox Implementation@>=
  11988. void SqlComboBox::setDataColumn(int column)
  11989. {
  11990. dataColumn = column;
  11991. }
  11992. void SqlComboBox::setDisplayColumn(int column)
  11993. {
  11994. displayColumn = column;
  11995. }
  11996. @ Once the widget is properly configured, we can run the SQL query and populate
  11997. the combo box with the results.
  11998. @<SqlComboBox Implementation@>=
  11999. void SqlComboBox::addSqlOptions(QString query)
  12000. {
  12001. SqlQueryConnection h;
  12002. QSqlQuery *dbquery = h.operator->();
  12003. if(!dbquery->exec(query))
  12004. {
  12005. QSqlError error = dbquery->lastError();
  12006. qDebug() << error.databaseText();
  12007. qDebug() << error.driverText();
  12008. qDebug() << error.text();
  12009. qDebug() << dbquery->lastQuery();
  12010. /* Throw an error here, please. */
  12011. }
  12012. while(dbquery->next())
  12013. {
  12014. QString displayValue(dbquery->value(displayColumn).toString());
  12015. QString dataValue(dbquery->value(dataColumn).toString());
  12016. if(dataColumnShown)
  12017. {
  12018. displayValue.append(QString(" (%1)").arg(dataValue));
  12019. }
  12020. addItem(displayValue, dataValue);
  12021. }
  12022. }
  12023. @ The constructor initializes some private member data. A size policy is also
  12024. set on the pop up. This allows the pop up to appear wider than the combo box to
  12025. allow more data to appear. On Linux this appears to also change the text elide
  12026. mode to something that is conveniently more appropriate for the use cases in
  12027. Typica. Note that this was not enough of a change to force the pop up to be
  12028. wide enough to contain all of the text for especially long items, but if the
  12029. combo box is wide enough the pop up will match that width.
  12030. The destructor is trivial.
  12031. @<SqlComboBox Implementation@>=
  12032. SqlComboBox::SqlComboBox() :
  12033. dataColumn(0), displayColumn(0), dataColumnShown(false),
  12034. specialNullText(tr("Unknown")), specialNullData(QVariant::String)
  12035. {
  12036. view()->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
  12037. }
  12038. SqlComboBox::~SqlComboBox()
  12039. {
  12040. /* Nothing needs to be done here. */
  12041. }
  12042. @ To use this class as an editor delegate in a model we wrap the class in a
  12043. |QItemDelegate|.
  12044. @<Class declarations@>=
  12045. class SqlComboBoxDelegate : public QItemDelegate@/
  12046. {
  12047. Q_OBJECT@;
  12048. SqlComboBox *delegate;
  12049. public:@/
  12050. SqlComboBoxDelegate(QObject *parent = NULL);
  12051. QWidget *createEditor(QWidget *parent,
  12052. const QStyleOptionViewItem &option,@|
  12053. const QModelIndex &index) const;
  12054. void setEditorData(QWidget *editor, const QModelIndex &index) const;
  12055. void setModelData(QWidget *editor, QAbstractItemModel *model,@|
  12056. const QModelIndex &index) const;
  12057. void setWidget(SqlComboBox *widget);
  12058. virtual QSize sizeHint() const;
  12059. void updateEditorGeometry(QWidget *editor,
  12060. const QStyleOptionViewItem &option,@|
  12061. const QModelIndex &index) const;
  12062. };
  12063. @ Rather than set the values for the combo box through the delegate class, we
  12064. create the editor and pass it in to the delegate.
  12065. @<SqlComboBoxDelegate Implementation@>=
  12066. void SqlComboBoxDelegate::setWidget(SqlComboBox *widget)
  12067. {
  12068. delegate = widget;
  12069. }
  12070. @ When a view requests this delegate, we simply return the widget that was
  12071. previously passed in.
  12072. @<SqlComboBoxDelegate Implementation@>=
  12073. QWidget* SqlComboBoxDelegate::createEditor(QWidget *parent,@|
  12074. const QStyleOptionViewItem &,
  12075. const QModelIndex &) const
  12076. {
  12077. return delegate->clone(parent);
  12078. }
  12079. @ To set the appropriate editor data, we check the value in the model and
  12080. attempt to set the value to match that.
  12081. @<SqlComboBoxDelegate Implementation@>=
  12082. void SqlComboBoxDelegate::setEditorData(QWidget *editor,
  12083. const QModelIndex &index) const
  12084. {
  12085. SqlComboBox *self = qobject_cast<SqlComboBox *>(editor);
  12086. self->setCurrentIndex(self->findData(
  12087. index.model()->data(index,
  12088. Qt::UserRole).toString()));
  12089. }
  12090. @ When setting the model data, we need to specify both the display role and the
  12091. user data role.
  12092. @<SqlComboBoxDelegate Implementation@>=
  12093. void SqlComboBoxDelegate::setModelData(QWidget *editor,@|
  12094. QAbstractItemModel *model,
  12095. const QModelIndex &index) const
  12096. {
  12097. SqlComboBox *self = qobject_cast<SqlComboBox *>(editor);
  12098. model->setData(index, self->itemData(self->currentIndex(), Qt::UserRole),
  12099. Qt::UserRole);
  12100. model->setData(index, self->currentText(), Qt::DisplayRole);
  12101. }
  12102. @ This is needed to play nicely with the model view architecture.
  12103. @<SqlComboBoxDelegate Implementation@>=
  12104. void SqlComboBoxDelegate::updateEditorGeometry(QWidget *editor,
  12105. const QStyleOptionViewItem &option,
  12106. const QModelIndex &) const
  12107. {
  12108. editor->setGeometry(option.rect);
  12109. }
  12110. @ When this delegate is used in a table view, we want to be able to provide a
  12111. size hint that can be used to resize the column in order to fit the delegate.
  12112. @<SqlComboBoxDelegate Implementation@>=
  12113. QSize SqlComboBoxDelegate::sizeHint() const
  12114. {
  12115. return delegate->sizeHint();
  12116. }
  12117. @ Finally, we need a constructor.
  12118. @<SqlComboBoxDelegate Implementation@>=
  12119. SqlComboBoxDelegate::SqlComboBoxDelegate(QObject *parent)
  12120. : QItemDelegate(parent)@/
  12121. {
  12122. /* Nothing needs to be done here. */
  12123. }
  12124. @** The main program.
  12125. The |main()| function is where program execution starts. Most of the work
  12126. required here is taken care of for us by the |Application| object.
  12127. The odd handling of argc is required to prevent segmentation faults in the Linux
  12128. build.
  12129. @<The main program@>=
  12130. int main(int argc, char **argv)@/
  12131. {@/
  12132. int *c = &argc;
  12133. Application app(*c, argv);
  12134. QSettings settings;
  12135. @<Set up logging@>@;
  12136. @<Set up icons@>@;
  12137. @<Set up fonts@>@;
  12138. @<Register device configuration widgets@>@;
  12139. @<Prepare the database connection@>@;
  12140. @<Load the application configuration@>@;
  12141. @<Set up the scripting engine@>@;
  12142. app.engine = engine;
  12143. @<Find and evaluate starting script@>@;
  12144. int retval = app.exec();
  12145. delete engine;
  12146. return retval;@/
  12147. }
  12148. @ \pn{} 1.6.3 introduces optional logging of diagnostic messages to a file. By
  12149. default this feature is not enabled. A sensible future refinement to this would
  12150. allow specification of where this file should be created.
  12151. @<Set up logging@>=
  12152. if(settings.value("settings/advanced/logging", false).toBool())
  12153. {
  12154. qInstallMsgHandler(messageFileOutput);
  12155. }
  12156. @ This requires that we have our messageFileOutput function.
  12157. @<Logging function prototype@>=
  12158. void messageFileOutput(QtMsgType type, const char *msg);
  12159. @ The current implementation is straightforward.
  12160. @<Logging function implementation@>=
  12161. void messageFileOutput(QtMsgType, const char *msg)
  12162. {
  12163. QFile output("Typica-"+QDate::currentDate().toString("yyyy-MM-dd")+".log");
  12164. output.open(QIODevice::WriteOnly | QIODevice::Append);
  12165. QTextStream outstream(&output);
  12166. outstream << msg << "\r\n";
  12167. }
  12168. @ \pn{} 1.4 introduces the ability to use icons in certain interface elements.
  12169. Some commonly desired public domain graphics are provided by the Tango Desktop
  12170. Project. We also set an application level default window icon.
  12171. @<Set up icons@>=
  12172. QStringList themeSearchPath = QIcon::themeSearchPaths();
  12173. themeSearchPath.append(":/resources/icons/tango");
  12174. QIcon::setThemeSearchPaths(themeSearchPath);
  12175. QIcon::setThemeName(":/resources/icons/tango");
  12176. app.setWindowIcon(QIcon(":/resources/icons/appicons/logo.svg"));
  12177. @ Similarly some elements make use of a special font which is loaded from
  12178. resource data.
  12179. There has been a report of a bug which I have not been able to reproduce and
  12180. which the original reporter has not yet gotten back to me with the results of
  12181. a test, so I have opted for an alternate approach which does not preclude the
  12182. use of the earlier plan but which may solve the matter. This brings in the
  12183. TeX Gyre Pagella font and sets this as the default standard font for all web
  12184. views.
  12185. @s QFontDatabase int
  12186. @s QWebSettings int
  12187. @<Set up fonts@>=
  12188. QFile entypo(":/resources/fonts/entypo.ttf");
  12189. entypo.open(QIODevice::ReadOnly);
  12190. QFontDatabase::addApplicationFontFromData(entypo.readAll());
  12191. entypo.close();
  12192. QFontDatabase::addApplicationFont(":/resources/fonts/texgyrepagella-regular.otf");
  12193. QFontDatabase::addApplicationFont(":/resources/fonts/texgyrepagella-bold.otf");
  12194. QFontDatabase::addApplicationFont(":/resources/fonts/texgyrepagella-bolditalic.otf");
  12195. QFontDatabase::addApplicationFont(":/resources/fonts/texgyrepagella-italic.otf");
  12196. QWebSettings::globalSettings()->setFontFamily(QWebSettings::StandardFont, "Tex Gyre Pagella");
  12197. @ Some widgets provided by \pn{} require access to a database in order to work.
  12198. To simplify using these widgets, the application will request information
  12199. needed to connect to a database. The use of two distinct |if| blocks rather than
  12200. an |if|$\dots$|else| construction is used because the data from settings can be
  12201. changed if an attempt to connect to the database fails.
  12202. @<Prepare the database connection@>=
  12203. if(settings.value("database/exists", "false").toString() == "true")
  12204. {
  12205. @<Try connecting to the database@>@;
  12206. }
  12207. if(settings.value("database/exists", "false").toString() == "false")
  12208. {
  12209. @<Prompt for database connection information@>@;
  12210. }
  12211. @ In order to connect to the database, we need five pieces of information: the
  12212. name of a database driver (PostgreSQL is recommended for now), the host name of
  12213. the computer running the database, the name of the database, the name of the
  12214. user connecting to the database, and that user'@q'@>s password. This information will
  12215. be stored in the user settings for the application so that the database
  12216. connection can be established without prompting the user next time. A class is
  12217. provided to gather this information.
  12218. @<Class declarations@>=
  12219. class SqlConnectionSetup : public QDialog@/
  12220. {@t\1@>@/
  12221. Q_OBJECT@;
  12222. public:@/
  12223. SqlConnectionSetup();
  12224. ~SqlConnectionSetup();@/
  12225. @t\4@>public slots@t\kern-3pt@>:@/
  12226. void testConnection();
  12227. private:@/
  12228. QFormLayout *formLayout;
  12229. QComboBox *driver;
  12230. QLineEdit *hostname;
  12231. QLineEdit *portnumber;
  12232. QLineEdit *dbname;
  12233. QLineEdit *user;
  12234. QLineEdit *password;
  12235. QVBoxLayout *layout;
  12236. QHBoxLayout *buttons;
  12237. QPushButton *cancelButton;
  12238. QPushButton *connectButton;@t\2@>@/
  12239. }@t\kern-3pt@>;
  12240. @ The constructor sets up this widget. The destructor does nothing.
  12241. @<SqlConnectionSetup implementation@>=
  12242. SqlConnectionSetup::SqlConnectionSetup() :
  12243. formLayout(new QFormLayout), driver(new QComboBox), hostname(new QLineEdit),
  12244. portnumber(new QLineEdit),
  12245. dbname(new QLineEdit), user(new QLineEdit), password(new QLineEdit),
  12246. layout(new QVBoxLayout), buttons(new QHBoxLayout),
  12247. cancelButton(new QPushButton(tr("Cancel"))),
  12248. connectButton(new QPushButton(tr("Connect")))@/
  12249. {
  12250. QSettings settings;
  12251. driver->addItem("PostgreSQL", "QPSQL");
  12252. formLayout->addRow(tr("Database driver:"), driver);
  12253. formLayout->addRow(tr("Host name:"), hostname);
  12254. hostname->setText(settings.value("database/hostname").toString());
  12255. formLayout->addRow(tr("Port number:"), portnumber);
  12256. portnumber->setText(settings.value("database/portnumber", "5432").toString());
  12257. formLayout->addRow(tr("Database name:"), dbname);
  12258. dbname->setText(settings.value("database/dbname").toString());
  12259. formLayout->addRow(tr("User name:"), user);
  12260. user->setText(settings.value("database/user").toString());
  12261. password->setEchoMode(QLineEdit::Password);
  12262. formLayout->addRow(tr("Password:"), password);
  12263. password->setText(settings.value("database/password").toString());
  12264. layout->addLayout(formLayout);
  12265. buttons->addStretch(1);
  12266. buttons->addWidget(cancelButton);
  12267. connect(cancelButton, SIGNAL(clicked(bool)), this, SLOT(reject()));
  12268. buttons->addWidget(connectButton);
  12269. layout->addLayout(buttons);
  12270. connect(connectButton, SIGNAL(clicked(bool)), this, SLOT(testConnection()));
  12271. connectButton->setDefault(true);
  12272. setLayout(layout);
  12273. setModal(true);
  12274. }
  12275. SqlConnectionSetup::~SqlConnectionSetup()
  12276. {
  12277. /* Nothing needs to be done here. */
  12278. }
  12279. @ The |testConnection()| method checks if the information provided can be used
  12280. to open a new database connection.
  12281. @<SqlConnectionSetup implementation@>=
  12282. void SqlConnectionSetup::testConnection()
  12283. {
  12284. QSqlDatabase database =
  12285. QSqlDatabase::addDatabase(driver->itemData(driver->currentIndex()).
  12286. toString());
  12287. database.setConnectOptions("application_name=Typica");
  12288. database.setHostName(hostname->text());
  12289. database.setPort(portnumber->text().toInt());
  12290. database.setDatabaseName(dbname->text());
  12291. database.setUserName(user->text());
  12292. database.setPassword(password->text());
  12293. if(database.open())
  12294. {
  12295. QSettings settings;
  12296. settings.setValue("database/exists", "true");
  12297. settings.setValue("database/driver",
  12298. driver->itemData(driver->currentIndex()).toString());
  12299. settings.setValue("database/hostname", hostname->text());
  12300. settings.setValue("database/portnumber", portnumber->text());
  12301. settings.setValue("database/dbname", dbname->text());
  12302. settings.setValue("database/user", user->text());
  12303. settings.setValue("database/password", password->text());
  12304. AppInstance->setDatabaseConnected(true);
  12305. accept();
  12306. }
  12307. else
  12308. {
  12309. QMessageBox::information(this, tr("Database connection failed"),
  12310. tr("Failed to connect to database."));
  12311. }
  12312. }
  12313. @ In order to prompt for connection information, we simply create a
  12314. |SqlConnectionSetup| object and call |exec()|. When control returns, the
  12315. settings will either contain appropriate connection information or we have to
  12316. give up on getting that information from the user for now.
  12317. @<Prompt for database connection information@>=
  12318. SqlConnectionSetup dialog;
  12319. dialog.exec();
  12320. @ If we have connected to a database in the previous running of the application,
  12321. we try to connect to the same database automatically rather than prompt the
  12322. user. If the connection attempt fails, we can fall back on asking the user for
  12323. help.
  12324. @<Try connecting to the database@>=
  12325. QSqlDatabase database =
  12326. QSqlDatabase::addDatabase(settings.value("database/driver").toString());
  12327. database.setConnectOptions("application_name=Typica");
  12328. database.setHostName(settings.value("database/hostname").toString());
  12329. database.setPort(settings.value("database/portnumber", 5432).toInt());
  12330. database.setDatabaseName(settings.value("database/dbname").toString());
  12331. database.setUserName(settings.value("database/user").toString());
  12332. database.setPassword(settings.value("database/password").toString());
  12333. if(!database.open())
  12334. {
  12335. settings.setValue("database/exists", "false");
  12336. }
  12337. else
  12338. {
  12339. AppInstance->setDatabaseConnected(true);
  12340. }
  12341. @** Viewing a record of batches.
  12342. \noindent It is frequently useful to present a table view with the results of a
  12343. SQL query and have a way of interacting with that view to obtain more details
  12344. related to a given record in that table. For this purpose, \pn{} provides a
  12345. widget based on |QTableView| which presents information from a
  12346. |QSqlQueryModel|. The table emits signals when an entry in the table is double
  12347. clicked. One of these contains the data from the first column of that row and
  12348. is suitable for use when a primary key is presented in that column and this is
  12349. sufficient for the desired drill down. The other signal provides the row number
  12350. which can be used along with a reference to the table to obtain the data in any
  12351. column.
  12352. This class also automatically persists column widths when these are changed.
  12353. @<Class declarations@>=
  12354. class SqlQueryView : public QTableView@/
  12355. {@/
  12356. @[Q_OBJECT@]@;
  12357. public:@/
  12358. SqlQueryView(QWidget *parent = NULL);
  12359. void setQuery(const QString &query);
  12360. bool setHeaderData(int section, Qt::Orientation@, orientation,
  12361. const QVariant &value, int role);
  12362. @[Q_INVOKABLE@,@, QVariant@]@, data(int row, int column,
  12363. int role = Qt::DisplayRole);@t\2\2@>@/
  12364. signals:@/
  12365. void openEntry(QString key);
  12366. void openEntryRow(int row);
  12367. void selectEntry(QString key);
  12368. void selectEntryRow(int row);@/
  12369. protected:@/
  12370. virtual void showEvent(QShowEvent *event);@/
  12371. @[private slots@]:@/
  12372. void openRow(const QModelIndex &index);
  12373. void persistColumnResize(int column, int oldsize, int newsize);
  12374. void selectRow(const QModelIndex &index);@/
  12375. };
  12376. @ The constructor sets up the communication between the model and the view and
  12377. also provides the connection needed to notice when columns change size to
  12378. persist that preference.
  12379. @<SqlQueryView implementation@>=
  12380. SqlQueryView::SqlQueryView(QWidget *parent) : QTableView(parent)
  12381. {
  12382. setModel(new QSqlQueryModel);
  12383. connect(this, SIGNAL(doubleClicked(QModelIndex)),
  12384. this, SLOT(openRow(QModelIndex)));
  12385. connect(horizontalHeader(), SIGNAL(sectionResized(int, int, int)),
  12386. this, SLOT(persistColumnResize(int, int, int)));
  12387. connect(this, SIGNAL(activated(QModelIndex)),
  12388. this, SLOT(selectRow(QModelIndex)));
  12389. }
  12390. @ Column width persistance requires two methods. First we have a slot
  12391. method which is called when a column width is changed. This is saved with
  12392. |QSettings| under a key utilizing the name of the window, the name of the
  12393. table, and the column number.
  12394. @<SqlQueryView implementation@>=
  12395. void SqlQueryView::persistColumnResize(int column, int, int newsize)
  12396. {
  12397. @<Save updated column size@>@;
  12398. }
  12399. @ The body of this function has been split out so that it can be shared with
  12400. other table views without the need to introduce a new common base class.
  12401. @<Save updated column size@>=
  12402. QSettings settings;
  12403. @<Obtain top level widget@>@;
  12404. settings.setValue(QString("columnWidths/%1/%2/%3").
  12405. arg(topLevelWidget->objectName()).
  12406. arg(objectName()).arg(column),
  12407. QVariant(newsize));
  12408. @ To determine which window a given table is in, we just follow
  12409. |parentWidget()| until there isn'@q'@>t one. It is possible that the table view
  12410. will also be the window, however this is not advised as it is easier for the
  12411. settings key to be non-unique in such a case.
  12412. @<Obtain top level widget@>=
  12413. QWidget *topLevelWidget = this;
  12414. while(topLevelWidget->parentWidget())
  12415. {
  12416. topLevelWidget = topLevelWidget->parentWidget();
  12417. }
  12418. @ We restore column widths in response to a show event. One of these should be
  12419. received just before the widget is shown so the widget should appear correctly.
  12420. @<SqlQueryView implementation@>=
  12421. void SqlQueryView::showEvent(QShowEvent *event)
  12422. {
  12423. @<Restore table column widths@>@;
  12424. event->accept();
  12425. }
  12426. @ Similarly, most of the body of this method has also been split into a chunk
  12427. so that it might be shared with other classes.
  12428. @<Restore table column widths@>=
  12429. QSettings settings;
  12430. @<Obtain top level widget@>
  12431. QString baseKey =
  12432. QString("columnWidths/%1/%2").arg(topLevelWidget->objectName()).
  12433. arg(objectName());
  12434. for(int i = 0; i < model()->columnCount(); i++)
  12435. {
  12436. QString key = QString("%1/%2").arg(baseKey).arg(i);
  12437. if(settings.contains(key))
  12438. {
  12439. setColumnWidth(i, settings.value(key).toInt());
  12440. }
  12441. }
  12442. @ A slot is required for obtaining the information to send out in our signals.
  12443. @<SqlQueryView implementation@>=
  12444. void SqlQueryView::openRow(const QModelIndex &index)
  12445. {
  12446. emit openEntry(((QSqlQueryModel *)model())->record(index.row()).value(0).toString());
  12447. emit openEntryRow(index.row());
  12448. }
  12449. void SqlQueryView::selectRow(const QModelIndex &index)
  12450. {
  12451. emit selectEntry(((QSqlQueryModel *)model())->record(index.row()).value(0).toString());
  12452. emit selectEntryRow(index.row());
  12453. }
  12454. @ The other functions are wrappers around model methods.
  12455. @<SqlQueryView implementation@>=
  12456. void SqlQueryView::setQuery(const QString &query)
  12457. {
  12458. QSqlDatabase database = AppInstance->database();
  12459. database.open();
  12460. QSqlQuery q(query, database);
  12461. ((QSqlQueryModel*)model())->setQuery(q);
  12462. database.close();
  12463. }
  12464. bool SqlQueryView::setHeaderData(int section, Qt::Orientation@, orientation,
  12465. const QVariant &value, int role)
  12466. {
  12467. return model()->setHeaderData(section, orientation, value, role);
  12468. }
  12469. @ A method is also provided to allow scripts to access the data.
  12470. @<SqlQueryView implementation@>=
  12471. QVariant SqlQueryView::data(int row, int column, int role)
  12472. {
  12473. return model()->data(model()->index(row, column), role);
  12474. }
  12475. @ To use this class, it is useful to expose it to the host environment.
  12476. @<Function prototypes for scripting@>=
  12477. void setSqlQueryViewProperties(QScriptValue value, QScriptEngine *engine);
  12478. QScriptValue constructSqlQueryView(QScriptContext *context,
  12479. QScriptEngine *engine);
  12480. QScriptValue SqlQueryView_setQuery(QScriptContext *context,
  12481. QScriptEngine *engine);
  12482. QScriptValue SqlQueryView_setHeaderData(QScriptContext *context,
  12483. QScriptEngine *engine);
  12484. QScriptValue SqlQueryView_rows(QScriptContext *context,
  12485. QScriptEngine *engine);
  12486. @ The script constructor is passed to the host environment.
  12487. @<Set up the scripting engine@>=
  12488. constructor = engine->newFunction(constructSqlQueryView);
  12489. value = engine->newQMetaObject(&SqlQueryView::staticMetaObject, constructor);
  12490. engine->globalObject().setProperty("SqlQueryView", value);
  12491. @ Next we construct the view, add properties to access its methods from the host
  12492. environment, and pass that back.
  12493. @<Functions for scripting@>=
  12494. QScriptValue constructSqlQueryView(QScriptContext *, QScriptEngine *engine)
  12495. {
  12496. QScriptValue object = engine->newQObject(new SqlQueryView);
  12497. setSqlQueryViewProperties(object, engine);
  12498. return object;
  12499. }
  12500. void setSqlQueryViewProperties(QScriptValue value, QScriptEngine *engine)
  12501. {
  12502. setQTableViewProperties(value, engine);
  12503. value.setProperty("setHeaderData",
  12504. engine->newFunction(SqlQueryView_setHeaderData));
  12505. value.setProperty("setQuery", engine->newFunction(SqlQueryView_setQuery));
  12506. value.setProperty("rows", engine->newFunction(SqlQueryView_rows));
  12507. }
  12508. @ The properties added are simplified wrappers around the class methods.
  12509. @<Functions for scripting@>=
  12510. QScriptValue SqlQueryView_setQuery(QScriptContext *context, QScriptEngine *)
  12511. {
  12512. SqlQueryView *self = getself<SqlQueryView *>(context);
  12513. QString query = argument<QString>(0, context);
  12514. self->setQuery(query);
  12515. self->reset();
  12516. return QScriptValue();
  12517. }
  12518. QScriptValue SqlQueryView_setHeaderData(QScriptContext *context,
  12519. QScriptEngine *)
  12520. {
  12521. SqlQueryView *self = getself<SqlQueryView *>(context);
  12522. int section = argument<int>(0, context);
  12523. QString data = argument<QString>(1, context);
  12524. self->setHeaderData(section, Qt::Horizontal, data, Qt::DisplayRole);
  12525. return QScriptValue();
  12526. }
  12527. QScriptValue SqlQueryView_rows(QScriptContext *context, QScriptEngine *)
  12528. {
  12529. SqlQueryView *self = getself<SqlQueryView *>(context);
  12530. return QScriptValue(self->model()->rowCount());
  12531. }
  12532. @** Reporting.
  12533. \noindent \pn{} version 1.4 added a new type of menu which is designed to
  12534. handle reports. This makes extensive use of the previously existing reporting
  12535. system at present which makes modifying existing reports to work with the new
  12536. system very simple. Further changes may be introduced in the future that
  12537. substantially depart from this in order to simplify report files.
  12538. Previously to add a new report to a configuration, you needed to create the
  12539. report, add an {\tt <include>} tag in the main configuration file to bring that
  12540. report into the application configuration, then in any window with a Reports
  12541. menu you would need to add the report to that menu in its configuration file
  12542. and write a small bit of JavaScript to obtain a reference to that new menu
  12543. item and create the report when that menu item is triggered. This is highly
  12544. repetetive, error prone, and with the new approach it is not needed at all.
  12545. To add a new report to a configuration using the new approach one need only
  12546. save the new report file in the appropriate directory and \pn{} will detect
  12547. this, add it to any Reports menus that may exist, and handle all of the details
  12548. of generating these reports on demand.
  12549. The Reports menu is created in a configuration as a {\tt <menu>} element with
  12550. three attributes. The {\tt name} attribute as usual is the name of the menu
  12551. item. The {\tt type} attribute will have a value of {\tt "reports"} and the
  12552. {\tt src} attribute will indicate the directory to search for reports to
  12553. populate that menu. This allows for multiple Reports menus with different
  12554. reports in each menu if desired.
  12555. Reports are added to the menu in the order of the file names in the reports
  12556. directory.
  12557. \danger While it should not be an issue with the limited number of reports
  12558. presently distributed with Typica, the approach taken to implementing this menu
  12559. type is highly inefficient. There are many optimizations available if this
  12560. becomes problematic.\endanger
  12561. When a report menu is generated, the directory used for this is added as a
  12562. search path for the |"reports"| prefix. This is used by the |createReport()|
  12563. script method and is intended to allow access to reports from outside of the
  12564. Report menu.
  12565. @<Populate reports menu@>=
  12566. QSettings settings;
  12567. QString reportDirectory = QString("%1/%2").arg(settings.value("config").
  12568. toString()).
  12569. arg(element.attribute("src"));
  12570. QDir::addSearchPath("reports", reportDirectory);
  12571. QDir directory(reportDirectory);
  12572. directory.setFilter(QDir::Files);
  12573. directory.setSorting(QDir::Name);
  12574. QStringList nameFilter;
  12575. nameFilter << "*.xml";
  12576. directory.setNameFilters(nameFilter);
  12577. QFileInfoList reportFiles = directory.entryInfoList();
  12578. for(int i = 0; i < reportFiles.size(); i++)
  12579. {
  12580. QFileInfo reportFile = reportFiles.at(i);
  12581. @<Add report to reports menu@>@;
  12582. }
  12583. @ The menu items themselves are a subclass of |QAction| which holds all of the
  12584. information needed to respond to its activation by generating the appropriate
  12585. report.
  12586. @<Class declarations@>=
  12587. class ReportAction : public QAction@/
  12588. {@/
  12589. @[Q_OBJECT@]@;
  12590. public:@/
  12591. ReportAction(const QString &fileName, const QString &reportName,
  12592. QObject *parent = NULL);@/
  12593. @[private slots@]:@/
  12594. void createReport();@/
  12595. private:@/
  12596. QString reportFile;@/
  12597. };
  12598. @ The constructor receives the name of the report file which is used to
  12599. generate the report when needed and the name of the report which is used as the
  12600. name presented in the menu.
  12601. @<ReportAction implementation@>=
  12602. ReportAction::ReportAction(const QString &fileName, const QString &reportName,
  12603. QObject *parent) :
  12604. QAction(reportName, parent), reportFile(fileName)
  12605. {
  12606. connect(this, SIGNAL(triggered()), this, SLOT(createReport()));
  12607. }
  12608. @ The slot method is responsible for creating the new report. This is very
  12609. similar to the old approach and reuses much of the same code. Of particular
  12610. note is the |targetID| variable. This is set to facilitate window geometry
  12611. management, though this should probably be set from the {\tt id} attribute
  12612. of the {\tt <window>} element in the file to preserve window geometry
  12613. settings if the configuration is moved to another location in the file
  12614. system.
  12615. @<ReportAction implementation@>=
  12616. void ReportAction::createReport()
  12617. {
  12618. QFile file(reportFile);
  12619. QDomDocument document;
  12620. if(file.open(QIODevice::ReadOnly))
  12621. {
  12622. document.setContent(&file, true);
  12623. QDomElement element = document.documentElement();
  12624. QScriptEngine *engine = AppInstance->engine;
  12625. QScriptContext *context = engine->pushContext();
  12626. QScriptValue object;
  12627. QString targetID = reportFile;
  12628. @<Display the window@>@;
  12629. file.close();
  12630. engine->popContext();
  12631. }
  12632. }
  12633. @ With the |ReportAction| available, we are now ready to add reports to the
  12634. Reports menu. To do this we check each file in the given directory to determine
  12635. if it is a report file, obtain the report title and location within the menu
  12636. hierarchy from the file data, create the actions, and add them to the menu.
  12637. @<Add report to reports menu@>=
  12638. QString path = reportFile.absoluteFilePath();
  12639. QFile file(path);
  12640. if(file.open(QIODevice::ReadOnly))
  12641. {
  12642. QDomDocument document;
  12643. document.setContent(&file, true);
  12644. QDomElement root = document.documentElement();
  12645. QString translationContext = root.attribute("id");
  12646. QDomNode titleNode = root.elementsByTagName("reporttitle").at(0);
  12647. if(!titleNode.isNull())
  12648. {
  12649. QDomElement titleElement = titleNode.toElement();
  12650. QString title = QCoreApplication::translate("configuration",
  12651. titleElement.text().toUtf8().data());
  12652. if(!title.isEmpty())
  12653. {
  12654. QStringList hierarchy = title.split(":->");
  12655. QMenu *insertionPoint = menu;
  12656. @<Traverse report menu hierarchy@>
  12657. ReportAction *action = new ReportAction(path, hierarchy.last());
  12658. insertionPoint->addAction(action);
  12659. }
  12660. }
  12661. }
  12662. @ \pn{} allows the Reports menu to contain arbitrarily deep menu hierarchies.
  12663. It is advised to keep these hierarchies shallow.
  12664. @<Traverse report menu hierarchy@>=
  12665. for(int j = 0; j < hierarchy.size() - 1; j++)
  12666. {
  12667. QObjectList menuList = insertionPoint->children();
  12668. bool menuFound = @[false@];
  12669. for(int k = 0; k < menuList.size(); k++)
  12670. {
  12671. QMenu *currentItem = qobject_cast<QMenu*>(menuList.at(k));
  12672. if(currentItem)
  12673. {
  12674. if(currentItem->title() == hierarchy.at(j))
  12675. {
  12676. menuFound = @[true@];
  12677. insertionPoint = currentItem;
  12678. break;
  12679. }
  12680. }
  12681. }
  12682. if(!menuFound)
  12683. {
  12684. insertionPoint = insertionPoint->addMenu(hierarchy.at(j));
  12685. }
  12686. }
  12687. @ \noindent The reporting functionality in \pn{} is based on the Scribe framework
  12688. in Qt. This brings several benefits, including making it easy to print reports
  12689. or save reports as plain text or HTML.
  12690. Reports are specified in the \pn{}'@q'@>s configuration document and can include both
  12691. static elements and elements that are populated by external data such as the
  12692. result of a SQL query.
  12693. @<Function prototypes for scripting@>=
  12694. void addReportToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  12695. QStack<QLayout *> *layoutStack);
  12696. @ When adding a report to a layout, we must not only add the widget to the
  12697. layout, but also construct the document.
  12698. @<Functions for scripting@>=
  12699. void addReportToLayout(QDomElement element, QStack<QWidget *> *,@|
  12700. QStack<QLayout *> *layoutStack)
  12701. {
  12702. QTextEdit *widget = new QTextEdit;
  12703. if(element.hasAttribute("id"))
  12704. {
  12705. widget->setObjectName(element.attribute("id"));
  12706. }
  12707. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  12708. layout->addWidget(widget);
  12709. QTextDocument *document = new QTextDocument;
  12710. QFont defaultFont;
  12711. defaultFont.setPointSize(11);
  12712. document->setDefaultFont(defaultFont);
  12713. QTextCursor cursor(document);
  12714. @<Construct report document@>@;
  12715. widget->setDocument(document);
  12716. }
  12717. @ Several child elements are allowed under the {\tt <report>} element. These
  12718. should be processed in order to produce the final report document.
  12719. @<Construct report document@>=
  12720. QDomNodeList children = element.childNodes();
  12721. for(int i = 0; i < children.count(); i++)
  12722. {
  12723. QDomNode current;
  12724. QDomElement currentElement;
  12725. current = children.at(i);
  12726. if(current.isElement())
  12727. {
  12728. currentElement = current.toElement();
  12729. @<Process report document elements@>@;
  12730. }
  12731. }
  12732. @ If any custom styling for HTML content is required, a {\tt <style>} element
  12733. should be placed in the report description before any such content.
  12734. @<Process report document elements@>=
  12735. if(currentElement.tagName() == "style")
  12736. {
  12737. document->setDefaultStyleSheet(currentElement.text());
  12738. }
  12739. @ One common need is the ability to insert static text, such as the title of the
  12740. report. In order to simplify formatting, the text can be interpreted as HTML.
  12741. Note that to avoid having HTML tags eaten by the parser, the text of this
  12742. element should be a CDATA section.
  12743. @<Process report document elements@>=
  12744. if(currentElement.tagName() == "html")
  12745. {
  12746. cursor.insertHtml(currentElement.text());
  12747. }
  12748. @ If no special formatting is needed, a plain text element can be used. This
  12749. might be extended in the future to allow attributes for specifying the character
  12750. formatting to be used with the text.
  12751. @<Process report document elements@>=
  12752. if(currentElement.tagName() == "text")
  12753. {
  12754. cursor.insertText(currentElement.text());
  12755. }
  12756. @ One of the more interesting elements of a report is the {\tt <table>} element.
  12757. This is an element which can change its contents in response to changes in user
  12758. controls.
  12759. @<Process report document elements@>=
  12760. if(currentElement.tagName() == "table")
  12761. {
  12762. QTextFrame *frame = cursor.insertFrame(QTextFrameFormat());
  12763. ReportTable *table = new ReportTable(frame, currentElement);
  12764. table->setParent(widget);
  12765. if(currentElement.hasAttribute("id"))
  12766. {
  12767. table->setObjectName(currentElement.attribute("id"));
  12768. }
  12769. }
  12770. @ The |ReportTable| class is responsible for parsing {\tt <table>} child
  12771. elements and inserting the table into the document at the correct location.
  12772. @<Class declarations@>=
  12773. class ReportTable : public QObject@/
  12774. {@t\1@>@/
  12775. Q_OBJECT@;
  12776. QTextFrame *area;
  12777. QDomElement configuration;
  12778. QMap<QString, QVariant> bindings;
  12779. public:@/
  12780. ReportTable(QTextFrame *frame, QDomElement description);
  12781. ~ReportTable();
  12782. @[Q_INVOKABLE@,@, void@]@, bind(QString placeholder, QVariant value);@t\2\2@>@/
  12783. @t\4@>public slots@t\kern-3pt@>:@/
  12784. void refresh();@t\2@>@/
  12785. }@t\kern-3pt@>;
  12786. @ The |ReportTable| class takes a |QTextFrame| and |QDomElement| pointer in
  12787. its constructor. The former is used to establish the bounds of the table within
  12788. a document and the latter is used for generating the table contents.
  12789. @<ReportTable implementation@>=
  12790. ReportTable::ReportTable(QTextFrame *frame, QDomElement description) :
  12791. area(frame), configuration(description)
  12792. {
  12793. refresh();
  12794. }
  12795. ReportTable::~ReportTable()
  12796. {
  12797. }
  12798. @ In order to change the table contents based on user controls, the |bind()|
  12799. method allows a placeholder to be replaced with a value when evaluating a SQL
  12800. query.
  12801. @<ReportTable implementation@>=
  12802. void ReportTable::bind(QString placeholder, QVariant value)
  12803. {
  12804. bindings.insert(placeholder, value);
  12805. }
  12806. @ All of the interesting work is done in the |refresh()| slot. This method
  12807. deletes the current content of the frame and creates a table based on the
  12808. description of the table in the configuration document.
  12809. @<ReportTable implementation@>=
  12810. void ReportTable::refresh()
  12811. {
  12812. @<Delete current report table content@>@;
  12813. int rows = 1;
  12814. int columns = 1;
  12815. int currentRow = 0;
  12816. QTextTable *table = cursor.insertTable(rows, columns);
  12817. @<Set table formatting@>@;
  12818. @<Reconstruct report table content@>@;
  12819. if(rows > 1)
  12820. {
  12821. table->removeRows(0, 1);
  12822. }
  12823. }
  12824. @ Deleting the current content of the table involves using a cursor to select
  12825. everything in the frame and then removing that selection. There are more optimal
  12826. ways to do this but if there are performance problems with this, you may want to
  12827. reconsider what you are trying to do.
  12828. @<Delete current report table content@>=
  12829. QTextCursor cursor = area->firstCursorPosition();
  12830. while(cursor < area->lastCursorPosition())
  12831. {
  12832. cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
  12833. }
  12834. cursor.removeSelectedText();
  12835. @ When creating a new table, we may need to alter the formatting of that table.
  12836. To do this, we get the current format, modify that based on attributes of the
  12837. {\tt <table>} element, and apply the modified copy to the newly constructed
  12838. table.
  12839. @<Set table formatting@>=
  12840. QTextTableFormat format = table->format();
  12841. format.setBorderStyle(QTextFrameFormat::BorderStyle_None);
  12842. if(configuration.hasAttribute("align"))
  12843. {
  12844. if(configuration.attribute("align") == "center")
  12845. {
  12846. format.setAlignment(Qt::AlignHCenter);
  12847. }
  12848. }
  12849. table->setFormat(format);
  12850. @ To reconstruct the table, we need to parse the description of the table.
  12851. @<Reconstruct report table content@>=
  12852. QDomNodeList children = configuration.childNodes();
  12853. for(int i = 0; i < children.count(); i++)
  12854. {
  12855. QDomNode current;
  12856. QDomElement currentElement;
  12857. current = children.at(i);
  12858. if(current.isElement())
  12859. {
  12860. currentElement = current.toElement();
  12861. if(currentElement.tagName() == "query")
  12862. {
  12863. @<Add SQL query results to report table@>@;
  12864. }
  12865. else if(currentElement.tagName() == "row")
  12866. {
  12867. @<Add new row to report table@>@;
  12868. }
  12869. }
  12870. }
  12871. @ The text of a {\tt <query>} element will be the query desired in the table.
  12872. This might include placeholders that must be bound to values before the query is
  12873. executed. If query execution results in an error (as it will if it contains
  12874. placeholders that have not yet had values bound to them), there will be no
  12875. change to the table and the next child element, if any, will be processed.
  12876. @<Add SQL query results to report table@>=
  12877. SqlQueryConnection h;
  12878. QSqlQuery *query = h.operator->();
  12879. query->prepare(currentElement.text());
  12880. foreach(QString key, bindings.uniqueKeys())
  12881. {
  12882. if(currentElement.text().contains(key))
  12883. {
  12884. query->bindValue(key, bindings.value(key));
  12885. }
  12886. }
  12887. query->exec();
  12888. if(!query->next())
  12889. {
  12890. continue;
  12891. }
  12892. if(query->record().count() > columns)
  12893. {
  12894. table->appendColumns(query->record().count() - columns);
  12895. }
  12896. do
  12897. {
  12898. table->appendRows(1);
  12899. rows++;
  12900. currentRow++;
  12901. for(int j = 0; j < query->record().count(); j++)
  12902. {
  12903. QTextTableCell cell = table->cellAt(currentRow, j);
  12904. cursor = cell.firstCursorPosition();
  12905. cursor.insertText(query->value(j).toString());
  12906. }
  12907. } while(query->next());
  12908. @ It is sometimes desirable to add fixed data such as column headers to a table.
  12909. This is done with the {\tt <row>} element.
  12910. Technically, this isn'@q'@>t needed. The same results can be produced by using a
  12911. {\tt <query>} element to select constant data, but this approach saves a trip to
  12912. the database.
  12913. @<Add new row to report table@>=
  12914. table->appendRows(1);
  12915. currentRow++;
  12916. rows++;
  12917. QDomNodeList rowChildren = currentElement.childNodes();
  12918. int currentColumn = 0;
  12919. for(int j = 0; j < rowChildren.count(); j++)
  12920. {
  12921. QDomNode node;
  12922. QDomElement nodeElement;
  12923. node = rowChildren.at(j);
  12924. if(node.isElement())
  12925. {
  12926. nodeElement = node.toElement();
  12927. if(nodeElement.tagName() == "cell")
  12928. {
  12929. if(currentColumn == columns)
  12930. {
  12931. table->appendColumns(1);
  12932. columns++;
  12933. }
  12934. QTextTableCell cell = table->cellAt(currentRow, currentColumn);
  12935. cursor = cell.firstCursorPosition();
  12936. cursor.insertText(nodeElement.text());
  12937. currentColumn++;
  12938. }
  12939. }
  12940. }
  12941. @ In order to expose report printing capabilities, we provide a property on
  12942. |QTextEdit| objects to handle this.
  12943. @<Function prototypes for scripting@>=
  12944. void setQTextEditProperties(QScriptValue value, QScriptEngine *engine);
  12945. QScriptValue QTextEdit_print(QScriptContext *context, QScriptEngine *engine);
  12946. @ This function is a trivial adaptation from the Qt documentation.
  12947. @<Functions for scripting@>=
  12948. QScriptValue QTextEdit_print(QScriptContext *context, QScriptEngine *)
  12949. {
  12950. QTextEdit *self = getself<QTextEdit *>(context);
  12951. QTextDocument *document = self->document();
  12952. QPrinter printer;
  12953. QPrintDialog printwindow(&printer, self);
  12954. if(printwindow.exec() != QDialog::Accepted)
  12955. {
  12956. return QScriptValue();
  12957. }
  12958. document->print(&printer);
  12959. return QScriptValue();
  12960. }
  12961. @ The host environment must be informed of this function.
  12962. @<Functions for scripting@>=
  12963. void setQTextEditProperties(QScriptValue value, QScriptEngine *engine)
  12964. {
  12965. setQAbstractScrollAreaProperties(value, engine);
  12966. value.setProperty("print", engine->newFunction(QTextEdit_print));
  12967. }
  12968. @i plugins.w
  12969. @i daterangeselector.w
  12970. @** An area for repeated user interface elements.
  12971. \noindent There are multiple use cases in which it is useful to specify a
  12972. complex aggregation of user interface elements to be repeated arbitrarily many
  12973. times. For example, placing multiple copies of a cupping form in a single area
  12974. for conveniently entering observations for all coffees in a particular session
  12975. or providing any number of copies of the form for entering coffee purchase
  12976. information. The |FormArray| widget provides this capability, allowing the
  12977. XML portion of the configuration document to specify the form once and allowing
  12978. the host environment to access the copies.
  12979. Slots and the |Q_INVOKABLE| macro are used to simplify the use of this class
  12980. from the host environment.
  12981. @<Class declarations@>=
  12982. class FormArray : public QScrollArea@/
  12983. {@t\1@>@/
  12984. Q_OBJECT@;
  12985. QDomElement configuration;
  12986. QWidget itemContainer;
  12987. QVBoxLayout itemLayout;
  12988. int maxwidth;
  12989. int maxheight;
  12990. public:@/
  12991. FormArray(QDomElement description);
  12992. @[Q_INVOKABLE@,@, QWidget*@] elementAt(int index);@t\2\2@>@/
  12993. @[Q_INVOKABLE@,@, int@] elements();@t\2\2@>@/
  12994. @t\4@>public slots@t\kern-3pt@>:@/
  12995. void addElements(int copies = 1);
  12996. void removeAllElements();
  12997. void setMaximumElementWidth(int width);
  12998. void setMaximumElementHeight(int height);@t\2@>@/
  12999. }@t\kern-3pt@>;
  13000. @ The |FormArray| is just a |QScrollArea| providing a view onto a |QWidget|
  13001. containing a layout which has arbitrarily many copies of a |QWidget| with
  13002. contents determined by the configuration document used to create the
  13003. |FormArray|.
  13004. @<FormArray implementation@>=
  13005. FormArray::FormArray(QDomElement description) : configuration(description),
  13006. maxwidth(-1), maxheight(-1)@/
  13007. {
  13008. setWidget(&itemContainer);
  13009. itemContainer.setLayout(&itemLayout);
  13010. }
  13011. @ The |FormArray| was initially created by an XML element. A copy of this is
  13012. stored in the private variable |configuration|. This can have the same child
  13013. elements as {\tt <widget>}, allowing us to reuse the function for creating
  13014. populating the widget. When adding a new element, we must resize the
  13015. |itemContainer|, otherwise Qt will attempt to cram all widgets in the layout
  13016. into the same vertical space as was previously required. The result is not
  13017. attractive. We also set a minimum width just in case the newly created widget is
  13018. the first one added to the area.
  13019. @<FormArray implementation@>=
  13020. void FormArray::addElements(int copies)
  13021. {
  13022. QStack<QWidget *> *widgetStack = new QStack<QWidget *>;
  13023. QStack<QLayout *> *layoutStack = new QStack<QLayout *>;
  13024. QWidget *widget;
  13025. for(int i = 0; i < copies; i++)
  13026. {
  13027. widget = new QWidget;
  13028. if(maxwidth > -1)
  13029. {
  13030. widget->setMaximumWidth(maxwidth);
  13031. }
  13032. if(maxheight > -1)
  13033. {
  13034. widget->setMaximumHeight(maxheight);
  13035. }
  13036. if(configuration.hasChildNodes())
  13037. {
  13038. widgetStack->push(widget);
  13039. populateWidget(configuration, widgetStack, layoutStack);
  13040. widgetStack->pop();
  13041. widget->setMinimumHeight(widget->sizeHint().height());
  13042. itemLayout.addWidget(widget);
  13043. if(widget->sizeHint().height() > maxheight && maxheight > -1)
  13044. {
  13045. itemContainer.setMinimumHeight(maxheight * elements() + 50);
  13046. }
  13047. else
  13048. {
  13049. itemContainer.setMinimumHeight(itemContainer.sizeHint().height()
  13050. + widget->sizeHint().height());
  13051. }
  13052. if(maxwidth > -1)
  13053. {
  13054. itemContainer.setMinimumWidth(maxwidth + 50);
  13055. }
  13056. else
  13057. {
  13058. itemContainer.setMinimumWidth(widget->sizeHint().width() + 50);
  13059. }
  13060. }
  13061. }
  13062. }
  13063. @ In order to retrieve a widget from the area, we use the |elementAt()| method.
  13064. The pointer returned by this function can be used as the first argument to
  13065. |findChildObject()| in the host environment in order to find any widget in the
  13066. form.
  13067. @<FormArray implementation@>=
  13068. QWidget* FormArray::elementAt(int index)
  13069. {
  13070. if(index < itemLayout.count())
  13071. {
  13072. QLayoutItem *item = itemLayout.itemAt(index);
  13073. return item->widget();
  13074. }
  13075. else
  13076. {
  13077. return NULL;
  13078. }
  13079. }
  13080. @ Removing all elements is trivial, however we must be sure to reset the size of
  13081. |itemContainer|.
  13082. @<FormArray implementation@>=
  13083. void FormArray::removeAllElements()
  13084. {
  13085. while(itemLayout.count() > 0)
  13086. {
  13087. QLayoutItem *item;
  13088. item = itemLayout.itemAt(0);
  13089. item->widget()->hide();
  13090. itemLayout.removeWidget(item->widget());
  13091. }
  13092. itemContainer.setMinimumHeight(0);
  13093. }
  13094. @ This just leaves a method for determining the number of elements already in
  13095. the view. This is equal to the number of items in the layout.
  13096. @<FormArray implementation@>=
  13097. int FormArray::elements()
  13098. {
  13099. return itemLayout.count();
  13100. }
  13101. @ Some widgets do not behave well in a |FormArray| setting and will try to use
  13102. an excess of screen space. In these cases, constraining the size of the elements
  13103. can be beneficial. These just set private member variables which are used when
  13104. adding new elements.
  13105. @<FormArray implementation@>=
  13106. void FormArray::setMaximumElementWidth(int width)
  13107. {
  13108. maxwidth = width;
  13109. }
  13110. void FormArray::setMaximumElementHeight(int height)
  13111. {
  13112. maxheight = height;
  13113. }
  13114. @ In order to create an instance of this class from the configuration document,
  13115. a {\tt <formarray>} element is used. This can be added to any layout.
  13116. @<Function prototypes for scripting@>=
  13117. void addFormArrayToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  13118. QStack<QLayout *> *layoutStack);
  13119. @ Processing child elements is deferred until a call to
  13120. |FormArray::addElements()| has been made.
  13121. @<Functions for scripting@>=
  13122. void addFormArrayToLayout(QDomElement element, QStack<QWidget *> *,@|
  13123. QStack<QLayout *> *layoutStack)
  13124. {
  13125. FormArray *widget = new FormArray(element);
  13126. if(element.hasAttribute("id"))
  13127. {
  13128. widget->setObjectName(element.attribute("id"));
  13129. }
  13130. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  13131. layout->addWidget(widget);
  13132. }
  13133. @** Scale widgets.
  13134. \noindent One of the most commonly used methods of documenting the properties of
  13135. a coffee is through a cupping form. Several such forms exist to meet different
  13136. needs, however most involve several scales which can be marked to determine some
  13137. aspect of a particular attribute. Some of these scales are scored values which,
  13138. when considered with other scored values produce a numerical representation of
  13139. the quality of a given coffee. Others are unscored values which serve to provide
  13140. additional documentation of a property. For example, when the SCAA cupping form
  13141. expanded to the current form of ten scored properties with defects subtracted
  13142. from the total, a second scale was added for the acidity property. The scored
  13143. scale is used for marking the quality of the acidity while another unscored
  13144. scale is used for marking the intensity of that acidity.
  13145. Previously, in order to enter cupping information in \pn{}, numeric entry fields
  13146. were used. While this was very efficient for transcribing paper cupping forms
  13147. (and this was, in fact, the principal use case for our prototype cupping form
  13148. database software), it is not a form that lends itself to convenient use at the
  13149. cupping table.
  13150. Two new widgets are therefore introduced which allows a cupper to simply click
  13151. at some point on the scale to record that impression. Unfortunately, this is
  13152. still something of a tradeoff. It is not quite so efficient as using a paper
  13153. form in my experience, however it is faster than transcribing a stack of cupping
  13154. forms, particularly when working with cuppers with ambiguous handwriting. By
  13155. moving data acquisition to the point of data generation, a more useful record
  13156. can be produced for use in aggregate analysis.
  13157. @* The Horizontal Scale.
  13158. \noindent Several cupping forms make use of 10 point scales for the quality of
  13159. various attributes. The |ScaleControl| widget provides such a scale. It
  13160. consists of a bar with major ticks at 0, 5, and 10 and minor ticks at integer
  13161. values within this range. The first click sets both the initial and final value
  13162. of the scale while subsequent clicks adjust only the final value. A pair of
  13163. controls at each end of the scale allows the user to adjust either of these
  13164. values to compensate for imprecision at the point of the click. The two values,
  13165. an initial unscored value and a final scored value, provide some limited
  13166. temporal documentation. That is, it documents how the perception of a coffee
  13167. changes as it cools.
  13168. The widget is implemented as a |QGraphicsView| subclass. Please note that the
  13169. scale widgets are not particularly robust. In order to support a broader range
  13170. of cupping forms, there are plans to extend this class to allow user defined
  13171. range and tick patterns and user defined colors for the indicators.
  13172. @<Class declarations@>=
  13173. class ScaleControl : public QGraphicsView@/
  13174. {@t\1@>@/
  13175. Q_OBJECT@/
  13176. Q_PROPERTY(double initialValue READ initialValue WRITE setInitialValue)@/
  13177. Q_PROPERTY(double finalValue READ finalValue WRITE setFinalValue)@/
  13178. @<ScaleControl private members@>@t\2\2@>@/
  13179. public:@/
  13180. ScaleControl();
  13181. double initialValue(void);
  13182. double finalValue(void);
  13183. virtual QSize sizeHint() const;@/
  13184. @[public slots@]:@/
  13185. void setInitialValue(double value);
  13186. void setFinalValue(double value);@/
  13187. signals:@/
  13188. void initialChanged(double);
  13189. void finalChanged(double);@/
  13190. protected:@/
  13191. virtual void mousePressEvent(QMouseEvent *event);
  13192. virtual void mouseReleaseEvent(QMouseEvent *event);@t\2@>@/
  13193. }@t\kern-4pt@>;
  13194. @ The private variables available to instances of this class are used for
  13195. managing various aspects of the widget.
  13196. @<ScaleControl private members@>=
  13197. QGraphicsScene scene;
  13198. QGraphicsPolygonItem initialDecrement;
  13199. QGraphicsPolygonItem initialIncrement;
  13200. QGraphicsPolygonItem finalDecrement;
  13201. QGraphicsPolygonItem finalIncrement;
  13202. QGraphicsPolygonItem initialIndicator;
  13203. QGraphicsPolygonItem finalIndicator;
  13204. QGraphicsPathItem scaleLine;
  13205. QPolygonF left;
  13206. QPolygonF right;
  13207. QPolygonF down;
  13208. QPolygonF up;
  13209. QPainterPath scalePath;
  13210. QBrush initialBrush;
  13211. QBrush finalBrush;
  13212. double nonScoredValue;
  13213. double scoredValue;
  13214. bool initialSet;
  13215. bool finalSet;
  13216. bool scaleDown;
  13217. @ The constructor sets up the scene displayed by this widget. There is
  13218. considerable room for improvement here.
  13219. @<ScaleControl implementation@>=
  13220. ScaleControl::ScaleControl() : QGraphicsView(NULL, NULL), nonScoredValue(-1),
  13221. scoredValue(-1), initialSet(false), finalSet(false), scaleDown(false)
  13222. {
  13223. left << QPointF(0, 5) << QPointF(10, 0) << QPointF(10, 10) <<
  13224. QPointF(0, 5);
  13225. right << QPointF(10, 5) << QPointF(0, 0) << QPointF(0, 10) <<
  13226. QPointF(10, 5);
  13227. down << QPointF(0, 0) << QPointF(-5, -10) << QPointF(5, -10) <<
  13228. QPointF(0, 0);
  13229. up << QPointF(0, 0) << QPointF(-5, 10) << QPointF(4, 10) << QPointF(0, 0);
  13230. initialBrush.setColor(QColor(170, 170, 255));
  13231. initialBrush.setStyle(Qt::SolidPattern);
  13232. finalBrush.setColor(Qt::blue);
  13233. finalBrush.setStyle(Qt::SolidPattern);
  13234. initialDecrement.setPolygon(left);
  13235. initialDecrement.setBrush(initialBrush);
  13236. initialDecrement.setPos(0, 0);
  13237. scene.addItem(&initialDecrement);
  13238. initialIncrement.setPolygon(right);
  13239. initialIncrement.setBrush(initialBrush);
  13240. initialIncrement.setPos(122, 0);
  13241. scene.addItem(&initialIncrement);
  13242. finalDecrement.setPolygon(left);
  13243. finalDecrement.setBrush(finalBrush);
  13244. finalDecrement.setPos(0, 12);
  13245. scene.addItem(&finalDecrement);
  13246. finalIncrement.setPolygon(right);
  13247. finalIncrement.setBrush(finalBrush);
  13248. finalIncrement.setPos(122, 12);
  13249. scene.addItem(&finalIncrement);
  13250. scalePath.moveTo(0, 10);
  13251. scalePath.lineTo(100, 10);
  13252. scalePath.moveTo(0, 0);
  13253. scalePath.lineTo(0, 20);
  13254. scalePath.moveTo(10, 5);
  13255. scalePath.lineTo(10, 15);
  13256. scalePath.moveTo(20, 5);
  13257. scalePath.lineTo(20, 15);
  13258. scalePath.moveTo(30, 5);
  13259. scalePath.lineTo(30, 15);
  13260. scalePath.moveTo(40, 5);
  13261. scalePath.lineTo(40, 15);
  13262. scalePath.moveTo(50, 0);
  13263. scalePath.lineTo(50, 20);
  13264. scalePath.moveTo(60, 5);
  13265. scalePath.lineTo(60, 15);
  13266. scalePath.moveTo(70, 5);
  13267. scalePath.lineTo(70, 15);
  13268. scalePath.moveTo(80, 5);
  13269. scalePath.lineTo(80, 15);
  13270. scalePath.moveTo(90, 5);
  13271. scalePath.lineTo(90, 15);
  13272. scalePath.moveTo(100, 0);
  13273. scalePath.lineTo(100, 20);
  13274. scaleLine.setPath(scalePath);
  13275. scaleLine.setPos(16, 1);
  13276. scene.addItem(&scaleLine);
  13277. setScene(&scene);
  13278. initialIndicator.setPolygon(down);
  13279. initialIndicator.setBrush(initialBrush);
  13280. finalIndicator.setPolygon(up);
  13281. finalIndicator.setBrush(finalBrush);
  13282. setMinimumSize(sizeHint());
  13283. setMaximumSize(sizeHint());
  13284. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  13285. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  13286. setMinimumSize(sizeHint());
  13287. }
  13288. @ The size hint forces a smaller representation of the widget, making it easier
  13289. to arrange with other widgets.
  13290. @<ScaleControl implementation@>=
  13291. QSize ScaleControl::sizeHint() const
  13292. {
  13293. return QSize(140, 30);
  13294. }
  13295. @ The methods for setting the values represented on the scale must ensure that
  13296. the appropriate indicator is drawn and position it appropriately.
  13297. @<ScaleControl implementation@>=
  13298. void ScaleControl::setInitialValue(double value)@t\2\2@>@/
  13299. {@t\1@>@/
  13300. if(value >= 0 && value <= 10)@/
  13301. {@t\1@>@/
  13302. nonScoredValue = value;
  13303. if(!initialSet)
  13304. {
  13305. scene.addItem(&initialIndicator);
  13306. }
  13307. initialSet = true;
  13308. initialIndicator.setPos(value * 10 + 16, 10);
  13309. emit initialChanged(value);
  13310. if(!finalSet)
  13311. {
  13312. setFinalValue(value);
  13313. }@t\2@>@/
  13314. }@t\2@>@/
  13315. }@/@/
  13316. void ScaleControl::setFinalValue(double value)@t\2\2@>@/
  13317. {@t\1@>@/
  13318. if(value >= 0 && value <= 10)@/
  13319. {@t\1@>@/
  13320. scoredValue = value;
  13321. if(!finalSet)@/
  13322. {
  13323. scene.addItem(&finalIndicator);
  13324. }
  13325. finalSet = true;
  13326. finalIndicator.setPos(value * 10 + 16, 11);
  13327. emit finalChanged(value);@t\2@>@/
  13328. }@t\2@>@/
  13329. }
  13330. @ These values can, of course, be retrieved programmatically.
  13331. @<ScaleControl implementation@>=
  13332. double ScaleControl::initialValue(void)
  13333. {
  13334. return nonScoredValue;
  13335. }
  13336. double ScaleControl::finalValue(void)
  13337. {
  13338. return scoredValue;
  13339. }
  13340. @ This only leaves the matter of handling interaction with the widget. A future
  13341. version of this class might split the various interface elements in the scene
  13342. into distinct classes capable of using the event propagation capabilities
  13343. provided by the graphics view framework, however with the current design, we
  13344. must do a little more work.
  13345. There are two events which must be accepted in order to register a click on a
  13346. given portion of the scale. One event is generated when the mouse button is
  13347. pressed.
  13348. @<ScaleControl implementation@>=
  13349. void ScaleControl::mousePressEvent(QMouseEvent *event)
  13350. {
  13351. @<Check that the left button was pressed@>@;
  13352. scaleDown = @[true@];
  13353. event->accept();
  13354. }
  13355. @ The primary action button on the mouse is the left button. While there might
  13356. be sensible interactions to provide in response to other buttons, these are not
  13357. presently supported.
  13358. @<Check that the left button was pressed@>=
  13359. if(event->button() != Qt::LeftButton)
  13360. {
  13361. event->ignore();
  13362. return;
  13363. }
  13364. @ Most of the click event handling is done in response to releasing the mouse
  13365. button. In this event handler we must determine if the click occurred in a
  13366. clickable portion of the scale and take the appropriate action in response.
  13367. @<ScaleControl implementation@>=
  13368. void ScaleControl::mouseReleaseEvent(QMouseEvent *event)@t\2\2@>@/
  13369. {@t\1@>@/
  13370. @<Check that the left button was pressed@>@;
  13371. if(!scaleDown)
  13372. {
  13373. event->ignore();
  13374. return;
  13375. }
  13376. scaleDown = false;
  13377. QPointF sceneCoordinate = mapToScene(event->x(), event->y());
  13378. @<Handle clicks in the decrement controls@>@;
  13379. @<Handle clicks in the increment controls@>@;
  13380. @<Handle clicks in the scale area@>@;
  13381. event->ignore();
  13382. return;@t\2@>@/
  13383. }
  13384. @ As currently implemented, each horizontal pixel position represents a value
  13385. evenly divisible by $0.1$. It is, however, quite common to see vaues with a
  13386. $.25$ or $.75$ after the whole number on cupping forms. In order to make it
  13387. possible to select such values without vastly increasing the length of the
  13388. scale, the increment and decrement controls adjust the represented value by
  13389. $0.05$.
  13390. @<Handle clicks in the decrement controls@>=
  13391. if(sceneCoordinate.x() >= 0 && sceneCoordinate.x() <= 10)
  13392. {
  13393. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  13394. {
  13395. if(initialSet)
  13396. {
  13397. setInitialValue(nonScoredValue - 0.05);
  13398. }
  13399. event->accept();
  13400. return;
  13401. }
  13402. else if(sceneCoordinate.y() >= 12 && sceneCoordinate.y() <= 22)
  13403. {
  13404. if(finalSet)
  13405. {
  13406. setFinalValue(scoredValue - 0.05);
  13407. event->accept();
  13408. return;
  13409. }
  13410. }
  13411. }
  13412. @ Incrementing represented values is done in the same manner as decrementing
  13413. them.
  13414. @<Handle clicks in the increment controls@>=
  13415. else if(sceneCoordinate.x() >= 122 && sceneCoordinate.x() <= 132)
  13416. {
  13417. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  13418. {
  13419. if(initialSet)
  13420. {
  13421. setInitialValue(nonScoredValue + 0.05);
  13422. event->accept();
  13423. return;
  13424. }
  13425. }
  13426. else if(sceneCoordinate.y() >= 12 && sceneCoordinate.y() <= 22)
  13427. {
  13428. if(finalSet)
  13429. {
  13430. setFinalValue(scoredValue + 0.05);
  13431. event->accept();
  13432. return;
  13433. }
  13434. }
  13435. }
  13436. @ When handling clicks in the scale area, there is a difference between the
  13437. first click and any subsequent click.
  13438. @<Handle clicks in the scale area@>=
  13439. double relativeX = sceneCoordinate.x() - 16;
  13440. if(initialSet)
  13441. {
  13442. if(relativeX >= 0 && relativeX <= 100)
  13443. {
  13444. setFinalValue(relativeX / 10.0);
  13445. event->accept();
  13446. return;
  13447. }
  13448. }
  13449. else
  13450. {
  13451. if(relativeX >= 0 && relativeX <= 100)
  13452. {
  13453. setInitialValue(relativeX / 10.0);
  13454. event->accept();
  13455. return;
  13456. }
  13457. }
  13458. @* The Vertical Scale.
  13459. \noindent In addition to the horizontal scale, there is also a vertical scale.
  13460. The implementation of this class is in some ways a bit simpler as only one value
  13461. must be retained. While there is no prohibition on using this scale for scored
  13462. values (and this might enable a rather compact representation which might be
  13463. useful in some applications), its intent is for unscored values which are less
  13464. likely to change over time. If the dry aroma of a coffee changes significantly
  13465. during a cupping session, you are most likely waiting far too long to pour the
  13466. water.
  13467. @<Class declarations@>=
  13468. class IntensityControl : public QGraphicsView@/
  13469. {@/
  13470. @[Q_OBJECT@]@;
  13471. @[Q_PROPERTY(double value READ value WRITE setValue)@]@;
  13472. QGraphicsScene scene;
  13473. QGraphicsPolygonItem decrement;
  13474. QGraphicsPolygonItem increment;
  13475. QGraphicsPolygonItem indicator;
  13476. QGraphicsPathItem scaleLine;
  13477. QPolygonF left;
  13478. QPolygonF up;
  13479. QPolygonF down;
  13480. QPainterPath scalePath;
  13481. QBrush theBrush;
  13482. double theValue;
  13483. bool valueSet;
  13484. bool scaleDown;
  13485. public:@/
  13486. IntensityControl();
  13487. double value();
  13488. virtual QSize sizeHint() const;@/
  13489. @[public slots@]:@/
  13490. void setValue(double val);@/
  13491. signals:@/
  13492. void valueChanged(double);@/
  13493. protected:@/
  13494. virtual void mousePressEvent(QMouseEvent *event);
  13495. virtual void mouseReleaseEvent(QMouseEvent *event);@/
  13496. };
  13497. @ Note the similarity between this constructor and the the |ScaleControl|
  13498. constructor.
  13499. @<IntensityControl implementation@>=
  13500. IntensityControl::IntensityControl() : QGraphicsView(NULL, NULL), theValue(-1),
  13501. valueSet(false), scaleDown(false)
  13502. {
  13503. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  13504. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  13505. left << QPointF(0, 0) << QPointF(10, -5) << QPointF(10, 5) << QPointF(0, 0);
  13506. down << QPointF(0, 0) << QPointF(10, 0) << QPointF(5, 10) << QPointF(0, 0);
  13507. up << QPointF(0, 10) << QPointF(10, 10) << QPointF(5, 0) << QPointF(0, 10);
  13508. theBrush.setColor(Qt::blue);
  13509. theBrush.setStyle(Qt::SolidPattern);
  13510. increment.setPolygon(up);
  13511. increment.setBrush(theBrush);
  13512. increment.setPos(0, 0);
  13513. scene.addItem(&increment);
  13514. decrement.setPolygon(down);
  13515. decrement.setBrush(theBrush);
  13516. decrement.setPos(0, 122);
  13517. scene.addItem(&decrement);
  13518. scalePath.moveTo(5, 0);
  13519. scalePath.lineTo(5, 100);
  13520. scalePath.moveTo(0, 0);
  13521. scalePath.lineTo(10, 0);
  13522. scalePath.moveTo(0, 10);
  13523. scalePath.lineTo(10, 10);
  13524. scalePath.moveTo(0, 20);
  13525. scalePath.lineTo(10, 20);
  13526. scalePath.moveTo(0, 30);
  13527. scalePath.lineTo(10, 30);
  13528. scalePath.moveTo(0, 40);
  13529. scalePath.lineTo(10, 40);
  13530. scalePath.moveTo(0, 50);
  13531. scalePath.lineTo(10, 50);
  13532. scalePath.moveTo(0, 60);
  13533. scalePath.lineTo(10, 60);
  13534. scalePath.moveTo(0, 70);
  13535. scalePath.lineTo(10, 70);
  13536. scalePath.moveTo(0, 80);
  13537. scalePath.lineTo(10, 80);
  13538. scalePath.moveTo(0, 90);
  13539. scalePath.lineTo(10, 90);
  13540. scalePath.moveTo(0, 100);
  13541. scalePath.lineTo(10, 100);
  13542. scaleLine.setPath(scalePath);
  13543. scaleLine.setPos(0, 16);
  13544. scene.addItem(&scaleLine);
  13545. setScene(&scene);
  13546. indicator.setPolygon(left);
  13547. indicator.setBrush(theBrush);
  13548. setMinimumSize(sizeHint());
  13549. setMaximumSize(sizeHint());
  13550. }
  13551. @ Once again, the size hint reduces the default size of the widget.
  13552. @<IntensityControl implementation@>=
  13553. QSize IntensityControl::sizeHint() const
  13554. {
  13555. return QSize(25, 160);
  13556. }
  13557. @ To support a more intuitive numerical representation, higher values should map
  13558. to higher positions on the scale. This is contrary to the coordinate system
  13559. provided by Qt, so the code setting the position of the indicator on the scale
  13560. must account for this.
  13561. During testing of this class, I found that it was impossible to select the
  13562. values 0 or 10 either through a click or with the increment or decrement
  13563. controls. Adding two additional execution branches corrects this issue.
  13564. @<IntensityControl implementation@>=
  13565. void IntensityControl::setValue(double val)
  13566. {
  13567. if(val >= 0 && val <= 10)
  13568. {
  13569. theValue = val;
  13570. if(!valueSet)
  13571. {
  13572. scene.addItem(&indicator);
  13573. }
  13574. valueSet = @[true@];
  13575. indicator.setPos(6, (100 - (val * 10)) + 16);
  13576. emit(valueChanged(val));
  13577. }
  13578. else if(val < 1)
  13579. {
  13580. setValue(0);
  13581. }
  13582. else
  13583. {
  13584. setValue(10);
  13585. }
  13586. }
  13587. double IntensityControl::value()
  13588. {
  13589. return theValue;
  13590. }
  13591. @ Mouse event handling is similar as well. The mouse press event simply notes
  13592. that the button has been pressed.
  13593. @<IntensityControl implementation@>=
  13594. void IntensityControl::mousePressEvent(QMouseEvent *event)
  13595. {
  13596. @<Check that the left button was pressed@>@;
  13597. scaleDown = @[true@];
  13598. event->accept();
  13599. }
  13600. @ Since there are fewer clickable areas there are fewer regions to check while
  13601. handling the mouse release event. Just as the |setValue()| method must
  13602. compensate for a mismatch between the scale and the underlying coordinate
  13603. system, so must click handling in the scale area take this into consideration
  13604. when determining which value the click intends.
  13605. @<IntensityControl implementation@>=
  13606. void IntensityControl::mouseReleaseEvent(QMouseEvent *event)
  13607. {
  13608. @<Check that the left button was pressed@>@;
  13609. if(!scaleDown)
  13610. {
  13611. event->ignore();
  13612. return;
  13613. }
  13614. scaleDown = @[false@];
  13615. QPointF sceneCoordinate = mapToScene(event->x(), event->y());
  13616. if(sceneCoordinate.x() >= 0 && sceneCoordinate.x() <= 16)
  13617. {
  13618. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  13619. {
  13620. if(valueSet)
  13621. {
  13622. setValue(theValue + 0.05);
  13623. }
  13624. event->accept();
  13625. return;
  13626. }
  13627. else if(sceneCoordinate.y() >= 122 && sceneCoordinate.y() <= 132)
  13628. {
  13629. if(valueSet)
  13630. {
  13631. setValue(theValue - 0.05);
  13632. }
  13633. event->accept();
  13634. return;
  13635. }
  13636. else if(sceneCoordinate.y() >= 16 && sceneCoordinate.y() <= 116)
  13637. {
  13638. setValue(10 - ((sceneCoordinate.y() - 16) / 10.0));
  13639. event->accept();
  13640. return;
  13641. }
  13642. }
  13643. }
  13644. @* Scripting the Scale Widgets.
  13645. \noindent Scale widgets can be added through the configuration system with
  13646. {\tt <hscale>} and {\tt <vscale>} elements. These can be added to layouts.
  13647. @<Function prototypes for scripting@>=
  13648. void addScaleControlToLayout(QDomElement element,
  13649. QStack<QWidget *> *widgetStack,
  13650. QStack<QLayout *> *layoutStack);
  13651. void addIntensityControlToLayout(QDomElement element,
  13652. QStack<QWidget *> *widgetStack,
  13653. QStack<QLayout *> *layoutStack);
  13654. @ Adding these widgets is done in the same way as adding other widgets.
  13655. @<Functions for scripting@>=
  13656. void addScaleControlToLayout(QDomElement element, QStack<QWidget *> *,
  13657. QStack<QLayout *> *layoutStack)
  13658. {
  13659. ScaleControl *scale = new ScaleControl;
  13660. if(element.hasAttribute("id"))
  13661. {
  13662. scale->setObjectName(element.attribute("id"));
  13663. }
  13664. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  13665. layout->addWidget(scale);
  13666. }
  13667. void addIntensityControlToLayout(QDomElement element, QStack<QWidget *> *,
  13668. QStack<QLayout *> *layoutStack)
  13669. {
  13670. IntensityControl *scale = new IntensityControl;
  13671. if(element.hasAttribute("id"))
  13672. {
  13673. scale->setObjectName(element.attribute("id"));
  13674. }
  13675. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  13676. layout->addWidget(scale);
  13677. }
  13678. @** Device Configuration.
  13679. \noindent Starting in \pn{} 1.4, all supported measurement hardware is
  13680. available from the same build and it is possible to use multiple devices from
  13681. differernt vendors at the same time. In previous versions, there were very few
  13682. available hardware configurations and a small number of example configuration
  13683. documents covered the needs of most people using the software. As more hardware
  13684. is supported and more people with distinct needs start using \pn{}, that
  13685. approach becomes unsustainable and the need for in-program configuration
  13686. becomes increasingly pronounced.
  13687. Device configuration is coupled to configuration of the logging window and
  13688. it is possible to configure multiple different roasters with different hardware
  13689. and other customizations of the logging window specific to a particular
  13690. machine.
  13691. The core of this is the use of an XML document saved with |QSettings| under
  13692. the |"DeviceConfiguration"| key. Within the root {\tt <DeviceConfiguration>}
  13693. element there are two grouping elements: {\tt <devices>} and
  13694. {\tt <references>}. The terminology was developed at a time when it was
  13695. thought that hardware configuration and logging view configuration would be
  13696. decoupled from each other, however the benefits of combining these far
  13697. outweighed the minor loss of flexibility with this approach.
  13698. Within the {\tt <devices>} tag there are arbitrarily many {\tt <node>} tags
  13699. which themselves may contain {\tt <node>} tags nested to any depth. Each of
  13700. these has two attributes, a {\tt name} attribute which specifies the display
  13701. text used to represent that node and a {\tt reference} attribute with a
  13702. unique value. Typica will generate a UUID for each node to use as the unique
  13703. value but this is not strictly required. The {\tt name} attribute does not
  13704. need to be unique and will generally be supplied by the person using the
  13705. software. The top level {\tt node} elements represent a coffee roaster and
  13706. the sub-elements can represent hardware, annotation controls, and possibly
  13707. other configurable features.
  13708. Within the {\tt <references>} tag there are as many {\tt <reference>} tags as
  13709. there are {\tt <node>} tags. Each of these has an {\tt id} attribute which
  13710. matches the {\tt reference} attribute in a {\tt <node>} tag and a {\tt driver}
  13711. attribute which is used to determine which class should be used to interact
  13712. with these settings. In the case of device configuration, this allows a
  13713. determination of which class should be used to generate an editor for settings
  13714. related to that node. Within each {\tt <reference>} tag is an arbitrary number
  13715. of {\tt <attribute>} tags with {\tt name} and {\tt value} attributes. Code for
  13716. providing the settings widgets and device interfaces can use these for any
  13717. desired purpose, but it is common to have one {\tt <attribute>} tag per setting
  13718. appropriate for a given node and possibly more to identify the concept a
  13719. particular node represents.
  13720. The global |Application| object is extended to maintain a |QDomDocument|
  13721. representation of this XML document.
  13722. @<Application private data members@>=
  13723. QDomDocument deviceConfigurationDocument;
  13724. @ Two methods are also provided for interacting with this document. The
  13725. |deviceConfiguration()| method returns a pointer to the private data member,
  13726. loading the XML from |QSettings| if required and creating a new document with
  13727. no {\tt <node>} tags if the document does not exist in settings. The
  13728. |saveDeviceConfiguration()| method serializes the |QDomDocument| to settings.
  13729. @<Device configuration members@>=
  13730. QDomDocument deviceConfiguration();
  13731. @ The method for saving should be a slot so a model representing this data
  13732. can persist changes through the signals and slots mechanism rather than
  13733. requiring the calls to be explicitn.
  13734. @<Extended Application slots@>=
  13735. void saveDeviceConfiguration();
  13736. @ Serializing the current configuration is trivial.
  13737. @<Application Implementation@>=
  13738. void Application::saveDeviceConfiguration()
  13739. {
  13740. QSettings settings;
  13741. settings.setValue("DeviceConfiguration",
  13742. QVariant(deviceConfigurationDocument.toByteArray()));
  13743. }
  13744. @ Producing a pointer to a loaded configuration only slightly more complicated.
  13745. If the configuration has been previously loaded we just return the pointer.
  13746. Otherwise, we attempt to load the document.
  13747. @<Application Implementation@>=
  13748. QDomDocument Application::deviceConfiguration()
  13749. {
  13750. if(deviceConfigurationDocument.isNull())
  13751. {
  13752. @<Load device configuration document from settings@>@;
  13753. }
  13754. return deviceConfigurationDocument;
  13755. }
  13756. @ In most cases a document will already exist in settings, but we must verify
  13757. this and create a new document if it does not exist. We also clear device
  13758. configuration settings if the configuration document is invalid.
  13759. @<Load device configuration document from settings@>=
  13760. QSettings settings;
  13761. QByteArray document = settings.value("DeviceConfiguration").toByteArray();
  13762. QString etext;
  13763. int eline;
  13764. int ecol;
  13765. if(document.length() == 0)
  13766. {
  13767. qDebug() << "Loaded settings length is 0. Creating new configuration.";
  13768. @<Create device configuration document@>@;
  13769. }
  13770. else
  13771. {
  13772. if(!deviceConfigurationDocument.setContent(document, false,
  13773. &etext, &eline, &ecol))
  13774. {
  13775. @<Report configuration loading error@>@;
  13776. @<Create device configuration document@>@;
  13777. }
  13778. }
  13779. @ Rather than generate the empty device configuration programmatically, we keep
  13780. an empty device configuration document as a resource.
  13781. @<Create device configuration document@>=
  13782. QFile emptyDocument(":/resources/xml/EmptyDeviceConfiguration.xml");
  13783. emptyDocument.open(QIODevice::ReadOnly);
  13784. if(!deviceConfigurationDocument.setContent(&emptyDocument, false,
  13785. &etext, &eline, &ecol))
  13786. {
  13787. @<Report configuration loading error@>@;
  13788. }
  13789. else
  13790. {
  13791. saveDeviceConfiguration();
  13792. }
  13793. @ There isn'@q'@>t really anything that can be done if the device configuration data
  13794. is corrupt, but an error message can be produced if the program happens to have
  13795. access to a debugging console.
  13796. @<Report configuration loading error@>=
  13797. qDebug() << QString(tr("An error occurred loading device configuration."));
  13798. qDebug() << QString(tr("Line %1, Column %2")).arg(eline).arg(ecol);
  13799. qDebug() << etext;
  13800. @* Model and view for device configuration hierarchy.
  13801. \noindent When manipulating device configuration data, it can be useful to
  13802. present the device hierarchy in a tree view. To do this, we use two classes to
  13803. produce a tree model. This is slightly extended and modified from an example
  13804. in the Qt documentation.\nfnote{Simple DOM Model Example:\par\indent\pdfURL{%
  13805. http://doc.qt.nokia.com/4.7-snapshot/itemviews-simpledommodel.html}
  13806. {http://doc.qt.nokia.com/4.7-snapshot/itemviews-simpledommodel.html}}
  13807. Our model uses the |DeviceTreeModelNode| class to cache the |QDomNode|
  13808. instances with the data we want.
  13809. @<Class declarations@>=
  13810. class DeviceTreeModelNode
  13811. {
  13812. public:
  13813. DeviceTreeModelNode(QDomNode &node, int row,
  13814. DeviceTreeModelNode *parent = NULL);
  13815. ~DeviceTreeModelNode();
  13816. DeviceTreeModelNode *child(int index);
  13817. DeviceTreeModelNode *parent();
  13818. QDomNode node() const;
  13819. int row();
  13820. private:
  13821. QDomNode domNode;
  13822. QHash<int, DeviceTreeModelNode*> children;
  13823. int rowNumber;
  13824. DeviceTreeModelNode *parentItem;
  13825. };
  13826. @ Implementation of this helper class is trivial.
  13827. @<DeviceTreeModelNode implementation@>=
  13828. DeviceTreeModelNode::DeviceTreeModelNode(QDomNode &node, int row,
  13829. DeviceTreeModelNode *parent)
  13830. : domNode(node), rowNumber(row), parentItem(parent)
  13831. {
  13832. /* Nothing needs to be done here. */
  13833. }
  13834. DeviceTreeModelNode::~DeviceTreeModelNode()
  13835. {
  13836. QHash<int, DeviceTreeModelNode *>::iterator@, i;
  13837. for(i = children.begin(); i != children.end(); i++)
  13838. {
  13839. delete i.value();
  13840. }
  13841. }
  13842. DeviceTreeModelNode *DeviceTreeModelNode::parent()
  13843. {
  13844. return parentItem;
  13845. }
  13846. int DeviceTreeModelNode::row()
  13847. {
  13848. return rowNumber;
  13849. }
  13850. QDomNode DeviceTreeModelNode::node() const
  13851. {
  13852. return domNode;
  13853. }
  13854. DeviceTreeModelNode *DeviceTreeModelNode::child(int index)
  13855. {
  13856. if(children.contains(index))
  13857. {
  13858. return children[index];
  13859. }
  13860. if(index >= 0 && index < domNode.childNodes().count())
  13861. {
  13862. QDomNode childNode = domNode.childNodes().item(index);
  13863. DeviceTreeModelNode *childItem = new DeviceTreeModelNode(childNode,
  13864. index, this);
  13865. children[index] = childItem;
  13866. return childItem;
  13867. }
  13868. return NULL;
  13869. }
  13870. @ The model class provides a single column representation of the {\tt devices}
  13871. section of the device configuration document. It provides methods for editing
  13872. the name of any node, for adding new nodes to the model, for deleting any node
  13873. in the model, and for obtaining the {\tt reference} element corresponding to
  13874. a given node.
  13875. @<Class declarations@>=
  13876. class DeviceTreeModel : public QAbstractItemModel@/
  13877. {@/
  13878. @[Q_OBJECT@]@;
  13879. public:@/
  13880. DeviceTreeModel(QObject *parent = NULL);
  13881. ~DeviceTreeModel();
  13882. QVariant data(const QModelIndex &index, int role) const;
  13883. Qt::ItemFlags flags(const QModelIndex &index) const;
  13884. QVariant headerData(int section, Qt::Orientation orientation,
  13885. int role = Qt::DisplayRole) const;
  13886. QModelIndex index(int row, int column,
  13887. const QModelIndex &parent = QModelIndex()) const;
  13888. QModelIndex parent(const QModelIndex &child) const;
  13889. Q_INVOKABLE int rowCount(const QModelIndex &parent = QModelIndex()) const;
  13890. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  13891. bool setData(const QModelIndex &index, const QVariant &value,
  13892. int role);
  13893. bool removeRows(int row, int count, const QModelIndex &parent);
  13894. QDomElement referenceElement(const QString &id);
  13895. @[public slots@]:@/
  13896. void newNode(const QString &name, const QString &driver,
  13897. const QModelIndex &parent);
  13898. private:@/
  13899. QDomDocument document;
  13900. DeviceTreeModelNode *root;
  13901. QDomNode referenceSection;
  13902. QDomNode treeRoot;
  13903. };
  13904. @ In the constructor we locate the {\tt devices} and {\tt references} sections
  13905. of the passed in document. Our tree of cached |QDomNode| elements starts with
  13906. the former and is expanded as needed.
  13907. @<DeviceTreeModel implementation@>=
  13908. DeviceTreeModel::DeviceTreeModel(QObject *parent)
  13909. : QAbstractItemModel(parent)
  13910. {
  13911. document = AppInstance->deviceConfiguration();
  13912. QDomNodeList elements = document.elementsByTagName("devices");
  13913. if(elements.size() != 1)
  13914. {
  13915. qDebug() << "Unexpected result when loading device map.";
  13916. }
  13917. treeRoot = elements.at(0);
  13918. root = new DeviceTreeModelNode(treeRoot, 0);
  13919. elements = document.elementsByTagName("references");
  13920. if(elements.size() != 1)
  13921. {
  13922. qDebug() << "No references section. Creating.";
  13923. referenceSection = document.createElement("references");
  13924. document.appendChild(referenceSection);
  13925. }
  13926. else
  13927. {
  13928. referenceSection = elements.at(0);
  13929. }
  13930. connect(this, SIGNAL(dataChanged(QModelIndex, QModelIndex)),
  13931. AppInstance, SLOT(saveDeviceConfiguration()));
  13932. connect(this, SIGNAL(modelReset()),
  13933. AppInstance, SLOT(saveDeviceConfiguration()));
  13934. connect(this, SIGNAL(rowsInserted(QModelIndex, int, int)),
  13935. AppInstance, SLOT(saveDeviceConfiguration()));
  13936. }
  13937. @ We only provide a single column for our model, so |columnCount()| can simply
  13938. return a constant. The |rowCount()| method can return a variety of values
  13939. depending on the parent node.
  13940. @<DeviceTreeModel implementation@>=
  13941. int DeviceTreeModel::columnCount(const QModelIndex &) const
  13942. {
  13943. return 1;
  13944. }
  13945. int DeviceTreeModel::rowCount(const QModelIndex &parent) const
  13946. {
  13947. if(parent.column() > 0)
  13948. {
  13949. return 0;
  13950. }
  13951. @<Get parent item from index@>@;
  13952. return parentItem->node().childNodes().count();
  13953. }
  13954. @ If an invalid index is passed as the parent index, we assume the parent to
  13955. be the root element.
  13956. @<Get parent item from index@>=
  13957. DeviceTreeModelNode *parentItem;
  13958. if(!parent.isValid())
  13959. {
  13960. parentItem = root;
  13961. }
  13962. else
  13963. {
  13964. parentItem = static_cast<DeviceTreeModelNode *>(parent.internalPointer());
  13965. }
  13966. @ As seen in |rowCount()|, we keep a pointer to the cached node in our model
  13967. indices.
  13968. @<DeviceTreeModel implementation@>=
  13969. QModelIndex DeviceTreeModel::index(int row, int column,
  13970. const QModelIndex &parent) const
  13971. {
  13972. if(!hasIndex(row, column, parent))
  13973. {
  13974. return QModelIndex();
  13975. }
  13976. @<Get parent item from index@>@;
  13977. DeviceTreeModelNode *childItem = parentItem->child(row);
  13978. if(childItem)
  13979. {
  13980. return createIndex(row, column, childItem);
  13981. }
  13982. return QModelIndex();
  13983. }
  13984. @ We can also request an index for the parent of a given index.
  13985. @<DeviceTreeModel implementation@>=
  13986. QModelIndex DeviceTreeModel::parent(const QModelIndex &child) const
  13987. {
  13988. if(!child.isValid())
  13989. {
  13990. return QModelIndex();
  13991. }
  13992. DeviceTreeModelNode *childItem =
  13993. static_cast<DeviceTreeModelNode *>(child.internalPointer());
  13994. DeviceTreeModelNode *parentItem = childItem->parent();
  13995. if(!parentItem || parentItem == root)
  13996. {
  13997. return QModelIndex();
  13998. }
  13999. return createIndex(parentItem->row(), 0, parentItem);
  14000. }
  14001. @ All items should be enabled, selectable, and editable.
  14002. @<DeviceTreeModel implementation@>=
  14003. Qt::ItemFlags DeviceTreeModel::flags(const QModelIndex &index) const
  14004. {
  14005. if(!index.isValid())
  14006. {
  14007. return 0;
  14008. }
  14009. return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
  14010. }
  14011. @ Each node in the model maintains two pieces of information. One is the
  14012. display value for the node which is held in the {\tt name} attribute of the
  14013. corresponding XML element. The other is a reference ID held in the
  14014. {\tt reference} attribute.
  14015. @<DeviceTreeModel implementation@>=
  14016. QVariant DeviceTreeModel::data(const QModelIndex &index, int role) const
  14017. {
  14018. if(!index.isValid())
  14019. {
  14020. return QVariant();
  14021. }
  14022. if(role != Qt::DisplayRole && role != Qt::UserRole && role != Qt::EditRole)
  14023. {
  14024. return QVariant();
  14025. }
  14026. DeviceTreeModelNode *item =
  14027. static_cast<DeviceTreeModelNode *>(index.internalPointer());
  14028. QDomNode node = item->node();
  14029. QDomElement element = node.toElement();
  14030. switch(role)
  14031. {
  14032. case Qt::DisplayRole:@/
  14033. case Qt::EditRole:@/
  14034. return QVariant(element.attribute("name"));
  14035. case Qt::UserRole:@/
  14036. return QVariant(element.attribute("reference"));
  14037. default:@/
  14038. return QVariant();
  14039. }
  14040. return QVariant();
  14041. }
  14042. @ The reference value is managed by the model and should never be changed. The
  14043. display value for a node is, however, editable. These changes must propagate
  14044. back to the XML document underlying the model.
  14045. @<DeviceTreeModel implementation@>=
  14046. bool DeviceTreeModel::setData(const QModelIndex &index,
  14047. const QVariant &value, int)@;@/
  14048. {@t\1@>@/
  14049. if(!index.isValid())@/
  14050. {@t\1@>@/
  14051. return false;@t\2@>@/
  14052. }@/
  14053. DeviceTreeModelNode *item =
  14054. static_cast<DeviceTreeModelNode *>(index.internalPointer());
  14055. QDomNode node = item->node();
  14056. QDomElement element = node.toElement();
  14057. element.setAttribute("name", value.toString());
  14058. emit dataChanged(index, index);@;
  14059. return true;@t\2@>@/
  14060. }
  14061. @ A custom method is provided for adding new nodes to the model. This generates
  14062. the two XML elements needed for the node. The |name| parameter is the display
  14063. name of the new node, the |driver| parameter is used as the value for the
  14064. {\tt driver} attribute in the {\tt reference} element which will be used to
  14065. determine what classes are used to work with that data.
  14066. @<DeviceTreeModel implementation@>=
  14067. void DeviceTreeModel::newNode(const QString &name, const QString &driver,
  14068. const QModelIndex &parent)
  14069. {
  14070. QString referenceID = QUuid::createUuid().toString();
  14071. @<Get parent item from index@>@;
  14072. QDomNode parentNode = parentItem->node();
  14073. int newRowNumber = rowCount(parent);
  14074. beginInsertRows(parent, newRowNumber, newRowNumber);
  14075. QDomElement deviceElement = document.createElement("node");
  14076. deviceElement.setAttribute("name", name);
  14077. deviceElement.setAttribute("reference", referenceID);
  14078. parentNode.appendChild(deviceElement);
  14079. QDomElement referenceElement = document.createElement("reference");
  14080. referenceElement.setAttribute("id", referenceID);
  14081. referenceElement.setAttribute("driver", driver);
  14082. referenceSection.appendChild(referenceElement);
  14083. endInsertRows();
  14084. }
  14085. @ We can also delete nodes. When deleting a node, both XML elements are
  14086. removed and our node cache is invalidated.
  14087. @<DeviceTreeModel implementation@>=
  14088. bool DeviceTreeModel::removeRows(int row, int count, const QModelIndex &parent)@t\2\2@>@/
  14089. {@t\1@>@/
  14090. @<Get parent item from index@>@;
  14091. QDomNode parentNode = parentItem->node();
  14092. QDomNodeList childNodes = parentNode.childNodes();@;
  14093. if(childNodes.size() < row + count)@/
  14094. {@t\1@>@/
  14095. return false;@t\2@>@/
  14096. }@/
  14097. beginRemoveRows(parent, row, row + count - 1);
  14098. QList<QDomElement> removalList;
  14099. for(int i = row; i < row + count; i++)
  14100. {
  14101. removalList.append(childNodes.at(i).toElement());
  14102. }
  14103. QDomElement element;
  14104. QDomElement reference;
  14105. for(int i = 0; i < count; i++)
  14106. {
  14107. element = removalList.at(i);
  14108. if(element.hasAttribute("reference"))
  14109. {
  14110. reference = referenceElement(element.attribute("reference"));
  14111. if(!reference.isNull())
  14112. {
  14113. referenceSection.removeChild(reference);
  14114. }
  14115. }
  14116. parentNode.removeChild(element);
  14117. }
  14118. endRemoveRows();
  14119. beginResetModel();
  14120. delete root;
  14121. root = new DeviceTreeModelNode(treeRoot, 0);
  14122. endResetModel();@;
  14123. return true;@t\2@>@/
  14124. }
  14125. @ Another custom method obtains the {\tt reference} element for a given
  14126. reference ID.
  14127. @<DeviceTreeModel implementation@>=
  14128. QDomElement DeviceTreeModel::referenceElement(const QString &id)
  14129. {
  14130. QDomNodeList childNodes = referenceSection.childNodes();
  14131. QDomElement element;
  14132. for(int i = 0; i < childNodes.size(); i++)
  14133. {
  14134. element = childNodes.at(i).toElement();
  14135. if(element.hasAttribute("id"))
  14136. {
  14137. if(element.attribute("id") == id)
  14138. {
  14139. return element;
  14140. }
  14141. }
  14142. }
  14143. return QDomElement();
  14144. }
  14145. @ We don'@q'@>t want any headers, so |headerData()| is very simple.
  14146. @<DeviceTreeModel implementation@>=
  14147. QVariant DeviceTreeModel::headerData(int, Qt::Orientation, int) const
  14148. {
  14149. return QVariant();
  14150. }
  14151. @ The destructor destroys the node cache. The destructor for the top level node
  14152. will recursively destroy all child nodes.
  14153. @<DeviceTreeModel implementation@>=
  14154. DeviceTreeModel::~DeviceTreeModel()
  14155. {
  14156. delete root;
  14157. }
  14158. @ Exposing this class to the host environment allows a number of interesting
  14159. possibilities. Setting the model to a combo box, for example, allows the
  14160. selection of top level nodes representing a particular coffee roaster. It is
  14161. also useful to have the ability to traverse a specified sub-tree of the model
  14162. to set up a logging view that matches the configuration for such a selected
  14163. roaster.
  14164. @<Function prototypes for scripting@>=
  14165. QScriptValue constructDeviceTreeModel(QScriptContext *context,
  14166. QScriptEngine *engine);
  14167. void setDeviceTreeModelProperties(QScriptValue value, QScriptEngine *engine);
  14168. void setQAbstractItemModelProperties(QScriptValue value, QScriptEngine *engine);
  14169. QScriptValue DeviceTreeModel_referenceElement(QScriptContext *context,
  14170. QScriptEngine *engine);
  14171. QScriptValue QAbstractItemModel_data(QScriptContext *context, QScriptEngine *engine);
  14172. QScriptValue QAbstractItemModel_index(QScriptContext *context, QScriptEngine *engine);
  14173. QScriptValue QAbstractItemModel_rowCount(QScriptContext *context, QScriptEngine *engine);
  14174. QScriptValue QAbstractItemModel_hasChildren(QScriptContext *context, QScriptEngine *engine);
  14175. @ The constructor is trivial.
  14176. @<Functions for scripting@>=
  14177. QScriptValue constructDeviceTreeModel(QScriptContext *, QScriptEngine *engine)
  14178. {
  14179. QScriptValue object = engine->newQObject(new DeviceTreeModel);
  14180. setDeviceTreeModelProperties(object, engine);
  14181. return object;
  14182. }
  14183. @ As usual the host environment is informed of this constructor.
  14184. @<Set up the scripting engine@>=
  14185. constructor = engine->newFunction(constructDeviceTreeModel);
  14186. value = engine->newQMetaObject(&DeviceTreeModel::staticMetaObject,
  14187. constructor);
  14188. engine->globalObject().setProperty("DeviceTreeModel", value);
  14189. @ A number of properties are set to allow script code to traverse the model.
  14190. Most of these properties are properly members of |QAbstractItemModel| and
  14191. the code is written to allow any models that may be exposed to the host
  14192. environment in the future to make use of these as well. Note that this is not
  14193. a full set of functionality but only what I needed to implement a particular
  14194. feature set.
  14195. @<Functions for scripting@>=
  14196. void setDeviceTreeModelProperties(QScriptValue value, QScriptEngine *engine)
  14197. {
  14198. setQAbstractItemModelProperties(value, engine);
  14199. value.setProperty("referenceElement",
  14200. engine->newFunction(DeviceTreeModel_referenceElement));
  14201. }
  14202. void setQAbstractItemModelProperties(QScriptValue value, QScriptEngine *engine)
  14203. {
  14204. setQObjectProperties(value, engine);
  14205. value.setProperty("data", engine->newFunction(QAbstractItemModel_data));
  14206. value.setProperty("index", engine->newFunction(QAbstractItemModel_index));
  14207. value.setProperty("rowCount", engine->newFunction(QAbstractItemModel_rowCount));
  14208. value.setProperty("hasChildren", engine->newFunction(QAbstractItemModel_hasChildren));
  14209. }
  14210. @ The wrapped call to |referenceElement| does a little more than might be
  14211. expected. Rather than returning a |QDomElement| and leaving it up to script
  14212. code to traverse the sub-tree, we create a |QVariantMap| which in script code
  14213. is translated as an object with the keys as properties of the object containing
  14214. the values of those keys. This is populated by first specifying a {\tt driver}
  14215. key with its value from the {\tt driver} attribute of the {\tt reference} node.
  14216. We then examine the {\tt <attribute>} sub-elements and use the {\tt name}
  14217. attribute as keys and the {\tt value} attribute as values to fill out the rest
  14218. of the map.
  14219. @<Functions for scripting@>=
  14220. QScriptValue DeviceTreeModel_referenceElement(QScriptContext *context,
  14221. QScriptEngine *engine)
  14222. {
  14223. DeviceTreeModel *model = getself<DeviceTreeModel *>(context);
  14224. QDomElement referenceElement = model->referenceElement(argument<QString>(0, context));
  14225. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  14226. QDomElement node;
  14227. QVariantMap retval;
  14228. retval.insert("driver", referenceElement.attribute("driver"));
  14229. for(int i = 0; i < configData.size(); i++)
  14230. {
  14231. node = configData.at(i).toElement();
  14232. retval.insert(node.attribute("name"), node.attribute("value"));
  14233. }
  14234. return engine->toScriptValue(retval);
  14235. }
  14236. QScriptValue QAbstractItemModel_data(QScriptContext *context, QScriptEngine *engine)
  14237. {
  14238. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  14239. QModelIndex index = argument<QModelIndex>(0, context);
  14240. int role = argument<int>(1, context);
  14241. return engine->toScriptValue(model->data(index, role));
  14242. }
  14243. QScriptValue QAbstractItemModel_index(QScriptContext *context, QScriptEngine *engine)
  14244. {
  14245. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  14246. int row = 0;
  14247. int column = 0;
  14248. QModelIndex index;
  14249. if(context->argumentCount() > 1)
  14250. {
  14251. row = argument<int>(0, context);
  14252. column = argument<int>(1, context);
  14253. }
  14254. if(context->argumentCount() > 2)
  14255. {
  14256. index = argument<QModelIndex>(2, context);
  14257. }
  14258. QModelIndex retval = model->index(row, column, index);
  14259. return engine->toScriptValue(retval);
  14260. }
  14261. QScriptValue QAbstractItemModel_rowCount(QScriptContext *context,
  14262. QScriptEngine *)
  14263. {
  14264. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  14265. QModelIndex index;
  14266. if(context->argumentCount() == 1)
  14267. {
  14268. index = argument<QModelIndex>(0, context);
  14269. }
  14270. return QScriptValue(model->rowCount(index));
  14271. }
  14272. QScriptValue QAbstractItemModel_hasChildren(QScriptContext *context,
  14273. QScriptEngine *engine)
  14274. {
  14275. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  14276. QModelIndex index;
  14277. if(context->argumentCount() == 1)
  14278. {
  14279. index = argument<QModelIndex>(0, context);
  14280. }
  14281. return QScriptValue(engine, model->hasChildren(index));
  14282. }
  14283. @ Some additional work is needed to handle |QModelIndex| appropriately. First
  14284. we declare that as a metatype.
  14285. @<Class declarations@>=
  14286. Q_DECLARE_METATYPE(QModelIndex)
  14287. @ Next we need a pair of functions to convert |QModelIndex| to and from script
  14288. values.
  14289. @<Function prototypes for scripting@>=
  14290. QScriptValue QModelIndex_toScriptValue(QScriptEngine *engine, const QModelIndex &index);
  14291. void QModelIndex_fromScriptValue(const QScriptValue &value, QModelIndex &index);
  14292. @ These are implemented thusly.
  14293. @<Functions for scripting@>=
  14294. QScriptValue QModelIndex_toScriptValue(QScriptEngine *engine, const QModelIndex &index)
  14295. {
  14296. QVariant var;
  14297. var.setValue(index);
  14298. QScriptValue object = engine->newVariant(var);
  14299. return object;
  14300. }
  14301. void QModelIndex_fromScriptValue(const QScriptValue &value, QModelIndex &index)
  14302. {
  14303. index = value.toVariant().value<QModelIndex>();
  14304. }
  14305. @ Finally we register this with the engine.
  14306. @<Set up the scripting engine@>=
  14307. qScriptRegisterMetaType(engine, QModelIndex_toScriptValue, QModelIndex_fromScriptValue);
  14308. @* Device Configuration Widgets.
  14309. \noindent Each node in the {\tt devices} section of the |DeviceTreeModel| is
  14310. associated with a {\tt reference} element that provides a driver string which
  14311. can be used to identify the classes used to interact with the device
  14312. configuration data. An example of this is selecting which widget to use when
  14313. selecting a node in a configuration window. These widgets must be registered
  14314. to the appropriate driver string in advance. This is currently handled through
  14315. the |Application| instance, though it would probably be better to split this
  14316. into its own class at some point in the future.
  14317. @<Application private data members@>=
  14318. QHash<QString, QMetaObject> deviceConfigurationWidgets;
  14319. @ Two methods register widgets and retrieve an instance of the appropriate
  14320. widget for a given node in the device configuration model.
  14321. @<Device configuration members@>=
  14322. void registerDeviceConfigurationWidget(QString driver, QMetaObject widget);
  14323. QWidget* deviceConfigurationWidget(DeviceTreeModel *model,
  14324. const QModelIndex &index);
  14325. @ Registration is a simple wrapper around the underlying |QHash|.
  14326. @<Application Implementation@>=
  14327. void Application::registerDeviceConfigurationWidget(QString driver,
  14328. QMetaObject widget)
  14329. {
  14330. deviceConfigurationWidgets.insert(driver, widget);
  14331. }
  14332. @ Obtaining the configuration widget for a given node involves looking up the
  14333. reference element, extracting the driver string, looking up the associated
  14334. meta-object, and returning a new instance of that object.
  14335. As there is no concept of an invalid |QMetaObject| we default to the static
  14336. meta-object for a |QWidget| if a widget for the specified driver string is not
  14337. registered and check for this prior to creating a new instance of the
  14338. configuration widget.
  14339. @<Application Implementation@>=
  14340. QWidget* Application::deviceConfigurationWidget(DeviceTreeModel *model,
  14341. const QModelIndex &index)
  14342. {
  14343. QVariant nodeReference = index.data(Qt::UserRole);
  14344. QDomElement referenceElement = model->referenceElement(
  14345. model->data(index, Qt::UserRole).toString());
  14346. QMetaObject metaObject =
  14347. deviceConfigurationWidgets.value(referenceElement.attribute("driver"),
  14348. QWidget::staticMetaObject);
  14349. QWidget *editor;
  14350. if(metaObject.className() == QWidget::staticMetaObject.className())
  14351. {
  14352. editor = NULL;
  14353. }
  14354. else
  14355. {
  14356. editor = qobject_cast<QWidget *>(
  14357. metaObject.newInstance(Q_ARG(DeviceTreeModel *, model),
  14358. Q_ARG(QModelIndex, index)));
  14359. }
  14360. return editor;
  14361. }
  14362. @ Every node type should have an associated editor and the editors for nodes
  14363. which can have child nodes should be able to handle creating these child nodes.
  14364. This leaves the problem of creating the top level nodes. For this we must have
  14365. a way to register three key pieces of information: the text which should appear
  14366. for selecting a new top level node to add to the configuration, the default
  14367. name for a node of that type, and the registered driver string associated with
  14368. that node type. The most likely use for this information is in constructing a
  14369. menu. |QAction| seems like a good fit, but this cannot pass all of the
  14370. required information. Part of the chosen solution is a |QAction| subclass
  14371. which takes all three pieces of information and provides a new signal to
  14372. supply the information needed to add a new top level node.
  14373. @<Class declarations@>=
  14374. class NodeInserter : public QAction@/
  14375. {@/
  14376. @[Q_OBJECT@]@;
  14377. public:@/
  14378. NodeInserter(const QString &title, const QString &name,
  14379. const QString &driver, QObject *parent = NULL);
  14380. signals:@/
  14381. void triggered(QString name, QString driver);
  14382. @[private slots@]:@/
  14383. void onTriggered();
  14384. private:@/
  14385. QString defaultNodeName;
  14386. QString driverString;
  14387. };
  14388. @ The constructor saves the information that will later be emitted and connects
  14389. the |triggered()| signal from |QAction| to a private slot which emits our new
  14390. |triggered()| signal.
  14391. @<NodeInserter implementation@>=
  14392. NodeInserter::NodeInserter(const QString &title, const QString &name,
  14393. const QString &driver, QObject *parent) :
  14394. QAction(title, parent), defaultNodeName(name), driverString(driver)
  14395. {
  14396. connect(this, SIGNAL(triggered()), this, SLOT(onTriggered()));
  14397. }
  14398. void NodeInserter::onTriggered()
  14399. {
  14400. emit triggered(defaultNodeName, driverString);
  14401. }
  14402. @ An interface for adding top level nodes to the device configuration needs to
  14403. be able to access a list of these actions so we make this available through the
  14404. |Application| instance. Once again, it would be better to split device
  14405. configuration registration data to a separate class and there should be
  14406. accessors around this.
  14407. Note that this terminology was introduced when it was assumed that device
  14408. configuration and logging view configuration would be separate. It is likely
  14409. that a future code cleanup will remove this in favor of handling the top level
  14410. of the device configuration hierarchy (under roaster specification) in the same
  14411. way that sub-nodes are handled.
  14412. @<Device configuration members@>=
  14413. QList<NodeInserter *> topLevelNodeInserters;
  14414. @ With this done, we can now produce a window which allows someone to easily
  14415. edit the device configuration.
  14416. As of version 1.6 this class is no longer a window but just a |QWidget| which
  14417. is inserted into another more general settings window. The name of the class
  14418. should be changed in a future version to reflect this change.
  14419. @<Class declarations@>=
  14420. class DeviceConfigurationWindow : public QWidget
  14421. {
  14422. @[Q_OBJECT@]@;
  14423. public:@/
  14424. DeviceConfigurationWindow();
  14425. @[public slots@]:@/
  14426. void addDevice();
  14427. void removeNode();
  14428. void newSelection(const QModelIndex &index);
  14429. @[private slots@]:@/
  14430. void resizeColumn();
  14431. private:@/
  14432. QDomDocument document;
  14433. DeviceTreeModel *model;
  14434. QTreeView *view;
  14435. QScrollArea *configArea;
  14436. };
  14437. @ This window consists of two main panels separated by a splitter. The left
  14438. panel presents a tree view of the current device configuration and a set of
  14439. controls that allows someone to either add a new top level node to the
  14440. configuration or delete any node in the configuration along with all of its
  14441. child nodes.
  14442. The right panel provides a |QScrollArea|. When a node is selected from the tree
  14443. view, the appropriate configuration widget will be inserted into that area.
  14444. When a configuration widget adds a new node to the device model, the parent
  14445. node (which should be the currently selected node but the code does not assume
  14446. this) is expanded to show the new child node if it has not already been
  14447. expanded.
  14448. @<DeviceConfigurationWindow implementation@>=
  14449. DeviceConfigurationWindow::DeviceConfigurationWindow() : QWidget(NULL),
  14450. view(new QTreeView), configArea(new QScrollArea)
  14451. {
  14452. QSplitter *splitter = new QSplitter;
  14453. QWidget *leftWidget = new QWidget;
  14454. leftWidget->setMinimumWidth(200);
  14455. QVBoxLayout *left = new QVBoxLayout;
  14456. view->setAnimated(true);
  14457. view->setSelectionMode(QAbstractItemView::SingleSelection);
  14458. document = AppInstance->deviceConfiguration();
  14459. model = new DeviceTreeModel;
  14460. view->setModel(model);
  14461. view->setTextElideMode(Qt::ElideNone);
  14462. view->expandAll();
  14463. view->resizeColumnToContents(0);
  14464. connect(model, SIGNAL(modelReset()), view, SLOT(expandAll()));
  14465. QHBoxLayout *treeButtons = new QHBoxLayout;
  14466. QToolButton *addDeviceButton = new QToolButton;
  14467. addDeviceButton->setIcon(QIcon::fromTheme("list-add"));
  14468. addDeviceButton->setToolTip(tr("New Roaster"));
  14469. connect(addDeviceButton, SIGNAL(clicked()),
  14470. this, SLOT(addDevice()));
  14471. QToolButton *removeNodeButton = new QToolButton;
  14472. removeNodeButton->setIcon(QIcon::fromTheme("list-remove"));
  14473. removeNodeButton->setToolTip(tr("Delete Selection"));
  14474. connect(removeNodeButton, SIGNAL(clicked()), this, SLOT(removeNode()));
  14475. treeButtons->addWidget(addDeviceButton);
  14476. treeButtons->addWidget(removeNodeButton);
  14477. left->addWidget(view);
  14478. left->addLayout(treeButtons);
  14479. leftWidget->setLayout(left);
  14480. splitter->addWidget(leftWidget);
  14481. configArea->setMinimumWidth(580);
  14482. configArea->setMinimumHeight(460);
  14483. configArea->setWidgetResizable(true);
  14484. splitter->addWidget(configArea);
  14485. QVBoxLayout *centralLayout = new QVBoxLayout;
  14486. centralLayout->addWidget(splitter);
  14487. setLayout(centralLayout);
  14488. connect(view, SIGNAL(activated(QModelIndex)),
  14489. this, SLOT(newSelection(QModelIndex)));
  14490. connect(view, SIGNAL(clicked(QModelIndex)),
  14491. this, SLOT(newSelection(QModelIndex)));
  14492. connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)),
  14493. view, SLOT(expand(QModelIndex)));
  14494. connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)),
  14495. this, SLOT(resizeColumn()));
  14496. connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int)),
  14497. this, SLOT(resizeColumn()));
  14498. }
  14499. @ Adding a new top level node to the model is just a matter of extracting the
  14500. required information from the signal requesting that addition.
  14501. @<DeviceConfigurationWindow implementation@>=
  14502. void DeviceConfigurationWindow::addDevice()
  14503. {
  14504. model->newNode(tr("New Roaster"), "roaster", QModelIndex());
  14505. }
  14506. @ Removing the currently selected node is also simple.
  14507. @<DeviceConfigurationWindow implementation@>=
  14508. void DeviceConfigurationWindow::removeNode()
  14509. {
  14510. QModelIndex index = view->currentIndex();
  14511. if(index.isValid())
  14512. {
  14513. int row = index.row();
  14514. QModelIndex parent = index.parent();
  14515. model->removeRow(row, parent);
  14516. }
  14517. }
  14518. @ Due to most of the required logic being implemented in
  14519. |Application::deviceConfigurationWidget()|, inserting the proper editor in the
  14520. right area is also trivial.
  14521. @<DeviceConfigurationWindow implementation@>=
  14522. void DeviceConfigurationWindow::newSelection(const QModelIndex &index)
  14523. {
  14524. QWidget *editor = AppInstance->deviceConfigurationWidget(model, index);
  14525. if(editor)
  14526. {
  14527. configArea->setWidget(editor);
  14528. editor->show();
  14529. }
  14530. }
  14531. @ As nodes are added deeper in the device hierarchy or as nodes obtain longer
  14532. names, the nodes names may be elided by default rather than indicate that the
  14533. view can be scrolled horizontally. There has been feedback that this behavior
  14534. is not preferred so instead as the model data changes we expand the column
  14535. instead.
  14536. @<DeviceConfigurationWindow implementation@>=
  14537. void DeviceConfigurationWindow::resizeColumn()
  14538. {
  14539. view->resizeColumnToContents(0);
  14540. }
  14541. @ At least for the initial testing of this feature it will be useful if we can
  14542. instantiate this from the host environment. For this we at least require a
  14543. constructor.
  14544. Now that this widget is available through a more general settings window it may
  14545. be better to remove direct access to this class from the host environment.
  14546. @<Function prototypes for scripting@>=
  14547. QScriptValue constructDeviceConfigurationWindow(QScriptContext *context,
  14548. QScriptEngine *engine);
  14549. @ The constructor is trivial.
  14550. @<Functions for scripting@>=
  14551. QScriptValue constructDeviceConfigurationWindow(QScriptContext *,
  14552. QScriptEngine *engine)
  14553. {
  14554. QScriptValue object = engine->newQObject(new DeviceConfigurationWindow);
  14555. return object;
  14556. }
  14557. @ Finally we inform the host environment of this constructor.
  14558. @<Set up the scripting engine@>=
  14559. constructor = engine->newFunction(constructDeviceConfigurationWindow);
  14560. value = engine->newQMetaObject(&DeviceConfigurationWindow::staticMetaObject,
  14561. constructor);
  14562. engine->globalObject().setProperty("DeviceConfigurationWindow", value);
  14563. @* A Base Class for Device Configuration Widgets.
  14564. \noindent There are certain operations that are very commonly required
  14565. among device configuration widgets. These common elements have been implemented
  14566. in a base class.
  14567. @<Class declarations@>=
  14568. class BasicDeviceConfigurationWidget : public QWidget
  14569. {
  14570. @[Q_OBJECT@]@;
  14571. public:@/
  14572. BasicDeviceConfigurationWidget(DeviceTreeModel *model,
  14573. const QModelIndex &index);
  14574. @[public slots@]:@/
  14575. void insertChildNode(const QString &name, const QString &driver);
  14576. void updateAttribute(const QString &name, const QString &value);
  14577. protected:@/
  14578. DeviceTreeModel *deviceModel;
  14579. QModelIndex currentNode;
  14580. };
  14581. @ The constructor just passes its arguments to a pair of protected data
  14582. members. These are commonly required in subclasses but need not be exposed
  14583. outside of this branch of the object hierarchy.
  14584. @<BasicDeviceConfigurationWidget implementation@>=
  14585. BasicDeviceConfigurationWidget::BasicDeviceConfigurationWidget(
  14586. DeviceTreeModel *model, const QModelIndex &index)
  14587. : QWidget(NULL), deviceModel(model), currentNode(index)
  14588. {
  14589. /* Nothing needs to be done here. */
  14590. }
  14591. @ The |updateAttribute()| method sets the value property of an attribute
  14592. element of a given name that is a child of the current node, creating the
  14593. element if it does not exist.
  14594. @<BasicDeviceConfigurationWidget implementation@>=
  14595. void BasicDeviceConfigurationWidget::updateAttribute(const QString &name,
  14596. const QString &value)
  14597. {
  14598. QDomElement referenceElement = deviceModel->referenceElement(
  14599. deviceModel->data(currentNode, Qt::UserRole).toString());
  14600. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  14601. QDomElement node;
  14602. bool found = @[false@];
  14603. for(int i = 0; i < configData.size(); i++)
  14604. {
  14605. node = configData.at(i).toElement();
  14606. if(node.attribute("name") == name)
  14607. {
  14608. node.setAttribute("value", value);
  14609. found = @[true@];
  14610. break;
  14611. }
  14612. }
  14613. if(!found)
  14614. {
  14615. node = AppInstance->deviceConfiguration().createElement("attribute");
  14616. node.setAttribute("name", name);
  14617. node.setAttribute("value", value);
  14618. referenceElement.appendChild(node);
  14619. }
  14620. AppInstance->saveDeviceConfiguration();
  14621. }
  14622. @ The |insertChildNode()| method constructs a new node with the specified name
  14623. and driver as a child of the current node. Node insertion is a generic
  14624. operation that does not require any knowledge of the configuration options that
  14625. will be presented in that node.
  14626. @<BasicDeviceConfigurationWidget implementation@>=
  14627. void BasicDeviceConfigurationWidget::insertChildNode(const QString &name,
  14628. const QString &driver)
  14629. {
  14630. deviceModel->newNode(name, driver, currentNode);
  14631. }
  14632. @** Configuration of Top Level Roaster Nodes.
  14633. \noindent The first configuration widget required is one for defining a coffee
  14634. roaster. This stores the identification number that will be used for machine
  14635. references in the database and also provides controls for adding all of the
  14636. required child nodes for hardware and configurable elements of the logging
  14637. window that may vary from one machine to the next.
  14638. All of the configuration widgets follow a similar pattern. One important detail
  14639. to note is that these configuration widgets are instantiated through Qt'@q'@>s
  14640. meta-object system. All of these constructors take a |DeviceTreeModel *| and a
  14641. |QModelIndex &| as arguments and they are marked as |Q_INVOKABLE|.
  14642. @<Class declarations@>=
  14643. class RoasterConfWidget : public BasicDeviceConfigurationWidget
  14644. {
  14645. @[Q_OBJECT@]@;
  14646. public:@/
  14647. @[Q_INVOKABLE@]@, RoasterConfWidget(DeviceTreeModel *model,
  14648. const QModelIndex &index);
  14649. @[private slots@]:@/
  14650. void updateRoasterId(int id);
  14651. void updateCapacityCheck(int value);
  14652. void updateCapacity(const QString &value);
  14653. void updateCapacityUnit(const QString &value);
  14654. };
  14655. @ Aside from the ID number used to identify the roaster in the database we also
  14656. need controls to add child nodes. In order to limit the number of options in
  14657. menus for adding child nodes, these are organized into groups that are
  14658. available through different controls.
  14659. @<RoasterConfWidget implementation@>=
  14660. RoasterConfWidget::RoasterConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  14661. : BasicDeviceConfigurationWidget(model, index)
  14662. {
  14663. QVBoxLayout *layout = new QVBoxLayout;
  14664. QPushButton *addDeviceButton = new QPushButton(tr("Add Device"));
  14665. QMenu *deviceMenu = new QMenu;
  14666. NodeInserter *insertAction;
  14667. foreach(insertAction, AppInstance->topLevelNodeInserters)
  14668. {
  14669. connect(insertAction, SIGNAL(triggered(QString, QString)),
  14670. this, SLOT(insertChildNode(QString, QString)));
  14671. deviceMenu->addAction(insertAction);
  14672. }
  14673. addDeviceButton->setMenu(deviceMenu);
  14674. layout->addWidget(addDeviceButton);
  14675. QPushButton *addAnnotationControlButton = new QPushButton(tr("Add Annotation Control"));
  14676. QMenu *annotationMenu = new QMenu;
  14677. NodeInserter *basicButtonInserter = new NodeInserter(tr("Annotation Button"), tr("Annotation Button"), "annotationbutton");
  14678. NodeInserter *countingButtonInserter = new NodeInserter(tr("Counting Button"), tr("Counting Button"), "reconfigurablebutton");
  14679. NodeInserter *spinBoxInserter = new NodeInserter(tr("Numeric Entry"), tr("Numeric Entry"), "annotationspinbox");
  14680. NodeInserter *freeAnnotationInserter = new NodeInserter(tr("Free Text"),
  14681. tr("Free Text"),
  14682. "freeannotation");
  14683. annotationMenu->addAction(basicButtonInserter);
  14684. annotationMenu->addAction(countingButtonInserter);
  14685. annotationMenu->addAction(spinBoxInserter);
  14686. annotationMenu->addAction(freeAnnotationInserter);
  14687. connect(basicButtonInserter, SIGNAL(triggered(QString, QString)),
  14688. this, SLOT(insertChildNode(QString, QString)));
  14689. connect(countingButtonInserter, SIGNAL(triggered(QString, QString)),
  14690. this, SLOT(insertChildNode(QString, QString)));
  14691. connect(spinBoxInserter, SIGNAL(triggered(QString, QString)),
  14692. this, SLOT(insertChildNode(QString, QString)));
  14693. connect(freeAnnotationInserter, SIGNAL(triggered(QString, QString)),
  14694. this, SLOT(insertChildNode(QString, QString)));
  14695. @<Add annotation control node inserters@>@;
  14696. addAnnotationControlButton->setMenu(annotationMenu);
  14697. layout->addWidget(addAnnotationControlButton);
  14698. QPushButton *timersButton = new QPushButton(tr("Extra Timers"));
  14699. QMenu *timersMenu = new QMenu;
  14700. NodeInserter *coolingTimerInserter = new NodeInserter(tr("Cooling Timer"), tr("Cooling Timer"), "coolingtimer");
  14701. NodeInserter *rangeTimerInserter = new NodeInserter(tr("Range Timer"), tr("Range Timer"), "rangetimer");
  14702. NodeInserter *multirangeTimerInserter = new NodeInserter(tr("Multi-Range Timer"), tr("Multi-Range Timer"), "multirangetimer");
  14703. timersMenu->addAction(coolingTimerInserter);
  14704. timersMenu->addAction(rangeTimerInserter);
  14705. timersMenu->addAction(multirangeTimerInserter);
  14706. connect(coolingTimerInserter, SIGNAL(triggered(QString, QString)),
  14707. this, SLOT(insertChildNode(QString, QString)));
  14708. connect(rangeTimerInserter, SIGNAL(triggered(QString, QString)),
  14709. this, SLOT(insertChildNode(QString, QString)));
  14710. connect(multirangeTimerInserter, SIGNAL(triggered(QString, QString)),
  14711. this, SLOT(insertChildNode(QString, QString)));
  14712. timersButton->setMenu(timersMenu);
  14713. layout->addWidget(timersButton);
  14714. QPushButton *advancedButton = new QPushButton(tr("Advanced Features"));
  14715. QMenu *advancedMenu = new QMenu;
  14716. NodeInserter *linearsplineinserter = new NodeInserter(tr("Linear Spline Interpolated Series"), tr("Linear Spline Interpolated Series"), "linearspline");
  14717. advancedMenu->addAction(linearsplineinserter);
  14718. NodeInserter *translationinserter = new NodeInserter(tr("Profile Translation"), tr("Profile Translation"), "translation");
  14719. advancedMenu->addAction(translationinserter);
  14720. connect(linearsplineinserter, SIGNAL(triggered(QString, QString)), this, SLOT(insertChildNode(QString, QString)));
  14721. connect(translationinserter, SIGNAL(triggered(QString, QString)), this, SLOT(insertChildNode(QString, QString)));
  14722. @<Add node inserters to advanced features menu@>@;
  14723. advancedButton->setMenu(advancedMenu);
  14724. layout->addWidget(advancedButton);
  14725. QHBoxLayout *idLayout = new QHBoxLayout;
  14726. QLabel *idLabel = new QLabel(tr("Machine ID for database:"));
  14727. idLayout->addWidget(idLabel);
  14728. QSpinBox *id = new QSpinBox;
  14729. idLayout->addWidget(id);
  14730. idLayout->addStretch();
  14731. layout->addLayout(idLayout);
  14732. QHBoxLayout *capacityLayout = new QHBoxLayout;
  14733. QCheckBox *capacityCheckEnabled = new QCheckBox(tr("Maximum batch size:"));
  14734. QDoubleSpinBox *capacity = new QDoubleSpinBox;
  14735. capacity->setMinimum(0.0);
  14736. capacity->setDecimals(3);
  14737. capacity->setMaximum(999999.999);
  14738. QComboBox *capacityUnit = new QComboBox;
  14739. capacityUnit->addItem("g");
  14740. capacityUnit->addItem("Kg");
  14741. capacityUnit->addItem("oz");
  14742. capacityUnit->addItem("Lb");
  14743. capacityUnit->setCurrentIndex(3);
  14744. capacityLayout->addWidget(capacityCheckEnabled);
  14745. capacityLayout->addWidget(capacity);
  14746. capacityLayout->addWidget(capacityUnit);
  14747. capacityLayout->addStretch();
  14748. layout->addLayout(capacityLayout);
  14749. layout->addStretch();
  14750. @<Get device configuration data for current node@>@;
  14751. for(int i = 0; i < configData.size(); i++)
  14752. {
  14753. node = configData.at(i).toElement();
  14754. if(node.attribute("name") == "databaseid")
  14755. {
  14756. id->setValue(node.attribute("value").toInt());
  14757. }
  14758. else if(node.attribute("name") == "checkcapacity")
  14759. {
  14760. capacityCheckEnabled->setChecked(node.attribute("value") == "true");
  14761. }
  14762. else if(node.attribute("name") == "capacity")
  14763. {
  14764. capacity->setValue(node.attribute("value").toDouble());
  14765. }
  14766. else if(node.attribute("name") == "capacityunit")
  14767. {
  14768. capacityUnit->setCurrentIndex(capacityUnit->findText(node.attribute("value")));
  14769. }
  14770. }
  14771. updateRoasterId(id->value());
  14772. connect(id, SIGNAL(valueChanged(int)), this, SLOT(updateRoasterId(int)));
  14773. connect(capacityCheckEnabled, SIGNAL(stateChanged(int)), this, SLOT(updateCapacityCheck(int)));
  14774. connect(capacity, SIGNAL(valueChanged(QString)), this, SLOT(updateCapacity(QString)));
  14775. connect(capacityUnit, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateCapacityUnit(QString)));
  14776. setLayout(layout);
  14777. }
  14778. @ Iterating over the configuration data associated with the current node is
  14779. required in nearly every configuration widget. The specifics of the loop
  14780. vary, but there is likely a better way to generalize that. Until then,
  14781. obtaining a |QDomNodeList| with the required data to iterate over has been
  14782. split off as its own chunk to reduce the risk of errors associated with typing
  14783. the same code many times.
  14784. @<Get device configuration data for current node@>=
  14785. QDomElement referenceElement =
  14786. model->referenceElement(model->data(index, Qt::UserRole).toString());
  14787. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  14788. QDomElement node;
  14789. @ We need to propagate changes to the configuration fields to the device
  14790. configuration document. The |updateAttribute()| method in the base class
  14791. makes this trivial.
  14792. @<RoasterConfWidget implementation@>=
  14793. void RoasterConfWidget::updateRoasterId(int id)
  14794. {
  14795. updateAttribute("databaseid", QString("%1").arg(id));
  14796. }
  14797. void RoasterConfWidget::updateCapacityCheck(int value)
  14798. {
  14799. updateAttribute("checkcapacity", value == Qt::Checked ? "true" : "false");
  14800. }
  14801. void RoasterConfWidget::updateCapacity(const QString &value)
  14802. {
  14803. updateAttribute("capacity", value);
  14804. }
  14805. void RoasterConfWidget::updateCapacityUnit(const QString &value)
  14806. {
  14807. updateAttribute("capacityunit", value);
  14808. }
  14809. @ Finally we must register the configuration widget so that it can be
  14810. instantiated at the appropriate time.
  14811. @<Register device configuration widgets@>=
  14812. app.registerDeviceConfigurationWidget("roaster", RoasterConfWidget::staticMetaObject);
  14813. @** Configuration for NI-DAQmx Base devices.
  14814. \noindent The primary concern in supporting hardware that communicates through
  14815. NI-DAQmx Base is in configurations using a single NI USB 9211 (for NI-DAQmx
  14816. Base 2.x) or NI USB 9211A (for NI-DAQmx Base 3.x), but if it is reasonable to
  14817. do so I'@q'@>d like to later add support for multiple device configurations and
  14818. limited support for other devices including the ability to use devices with
  14819. voltage inputs for non-temperature measurement data. The top priority, however,
  14820. is in continuing to support hardware that people are already using with Typica.
  14821. In order to more easily implement these future plans, device configuration is
  14822. handled with three configuration tiers. The top level configuration node
  14823. indicates that we are using NI-DAQmx Base. Here we can add a child node
  14824. representing either a NI USB 9211 or NI USB 9211A. From a configuration
  14825. perspective these are identical with the default node name as the only
  14826. difference. From the device configuration we can specify the device identifier
  14827. and add channels to the device. In the channel nodes we specify the
  14828. thermocouple type.
  14829. @<Class declarations@>=
  14830. class NiDaqMxBaseDriverConfWidget : public BasicDeviceConfigurationWidget
  14831. {
  14832. @[Q_OBJECT@]@;
  14833. public:@/
  14834. @[Q_INVOKABLE@]@, NiDaqMxBaseDriverConfWidget(DeviceTreeModel *model,@|
  14835. const QModelIndex &index);
  14836. };
  14837. @ There is very little to configure here so there isn'@q'@>t much for the
  14838. constructor to do. We do need to keep a reference to the node we are
  14839. configuring so that child nodes can later be added. At present, no real
  14840. configuration data other than the existence of the node is required so
  14841. there is no need to read any configuration data here.
  14842. @<NiDaqMxBaseDriverConfWidget implementation@>=
  14843. NiDaqMxBaseDriverConfWidget::NiDaqMxBaseDriverConfWidget(
  14844. DeviceTreeModel *model, const QModelIndex &index) :
  14845. BasicDeviceConfigurationWidget(model, index)
  14846. {
  14847. QHBoxLayout *layout = new QHBoxLayout;
  14848. QToolButton *addDeviceButton = new QToolButton;
  14849. addDeviceButton->setText(tr("Add Device"));
  14850. NodeInserter *add9211 = new NodeInserter("NI USB 9211", "NI USB 9211",
  14851. "nidaqmxbase9211series");
  14852. NodeInserter *add9211a = new NodeInserter("NI USB 9211A", "NI USB 9211A",
  14853. "nidaqmxbase9211series");
  14854. connect(add9211, SIGNAL(triggered(QString, QString)),
  14855. this, SLOT(insertChildNode(QString, QString)));
  14856. connect(add9211a, SIGNAL(triggered(QString, QString)),
  14857. this, SLOT(insertChildNode(QString, QString)));
  14858. QMenu *deviceMenu = new QMenu;
  14859. deviceMenu->addAction(add9211);
  14860. deviceMenu->addAction(add9211a);
  14861. addDeviceButton->setMenu(deviceMenu);
  14862. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  14863. layout->addWidget(addDeviceButton);
  14864. setLayout(layout);
  14865. }
  14866. @ Both the NI USB 9211 and NI USB 9211A are identical from a configuration
  14867. perspective. The only difference is the version of NI-DAQmx Base required for
  14868. use. As the API does not provide a way of determining which version is
  14869. installed, ensuring that the appropriate software is installed without
  14870. conflicts is left as an exercise for the person attempting to use \pn{}.
  14871. @<Class declarations@>=
  14872. class NiDaqMxBase9211ConfWidget : public BasicDeviceConfigurationWidget
  14873. {
  14874. Q_OBJECT
  14875. public:
  14876. Q_INVOKABLE NiDaqMxBase9211ConfWidget(DeviceTreeModel *device,
  14877. const QModelIndex &index);
  14878. private slots:
  14879. void addChannel();
  14880. void updateDeviceId(const QString &newId);
  14881. };
  14882. @ There are two controls required in a configuration widget for this device.
  14883. The first is the device identifier (for example, "Dev1"), the second is a
  14884. button for adding channels to the device. On a generic device we would also
  14885. need to set the clock rate, but with this hardware it is possible to determine
  14886. the maximum clock rate from the channels defined.
  14887. @<NiDaqMxBase9211ConfWidget implementation@>=
  14888. NiDaqMxBase9211ConfWidget::NiDaqMxBase9211ConfWidget(DeviceTreeModel *model,
  14889. const QModelIndex &index)
  14890. : BasicDeviceConfigurationWidget(model, index)
  14891. {
  14892. QVBoxLayout *layout = new QVBoxLayout;
  14893. QHBoxLayout *deviceIdLayout = new QHBoxLayout;
  14894. QLabel *label = new QLabel(tr("Device ID:"));
  14895. QLineEdit *deviceId = new QLineEdit;
  14896. deviceIdLayout->addWidget(label);
  14897. deviceIdLayout->addWidget(deviceId);
  14898. QPushButton *addChannelButton = new QPushButton(tr("Add Channel"));
  14899. layout->addLayout(deviceIdLayout);
  14900. layout->addWidget(addChannelButton);
  14901. @<Get device configuration data for current node@>@;
  14902. for(int i = 0; i < configData.size(); i++)
  14903. {
  14904. node = configData.at(i).toElement();
  14905. if(node.attribute("name") == "deviceID")
  14906. {
  14907. deviceId->setText(node.attribute("value", "Dev1"));
  14908. break;
  14909. }
  14910. }
  14911. updateDeviceId(deviceId->text());
  14912. connect(addChannelButton, SIGNAL(clicked()),
  14913. this, SLOT(addChannel()));
  14914. connect(deviceId, SIGNAL(textEdited(QString)),
  14915. this, SLOT(updateDeviceId(QString)));
  14916. setLayout(layout);
  14917. }
  14918. @ Updating the attribute tag under the reference element associated with the
  14919. current node is handled in the base class so we just need to pass in the
  14920. appropriate name value pair.
  14921. @<NiDaqMxBase9211ConfWidget implementation@>=
  14922. void NiDaqMxBase9211ConfWidget::updateDeviceId(const QString &newId)
  14923. {
  14924. updateAttribute("deviceID", newId);
  14925. }
  14926. @ Adding channels is just like adding any other sort of node.
  14927. @<NiDaqMxBase9211ConfWidget implementation@>=
  14928. void NiDaqMxBase9211ConfWidget::addChannel()
  14929. {
  14930. insertChildNode(tr("Thermocouple channel"), "ni9211seriestc");
  14931. }
  14932. @ Finally, we need a configuration widget to handle our thermocouple channels.
  14933. Ordinarily we would need three pieces of information for each channel. First
  14934. there is the thermocouple channel. Previously this was left implied by the
  14935. order of requests for a new channel, but more flexible configuration options
  14936. become possible with a more explicit specification. Since this widget is device
  14937. specific, all of the options can be easily enumerated to match markings on the
  14938. device. Next is the thermocouple type. Many options are supported, but I would
  14939. like to ensure that the most commonly used choices are listed first. The other
  14940. piece of information that DAQmx or DAQmx Base require is the measurement unit.
  14941. As all of Typica'@q'@>s internal operations are in Fahrenheit there is no need to
  14942. make this configurable so long as everything else that can display temperature
  14943. measurements can perform the appropriate conversions.
  14944. Note that as there are no configuration differences between the various
  14945. device combinations using an NI 9211 module with regard to thermocouple channel
  14946. configuration, we can use this widget with all device combinations that make
  14947. use of such a module.
  14948. @<Class declarations@>=
  14949. class Ni9211TcConfWidget : public BasicDeviceConfigurationWidget
  14950. {@/
  14951. @[Q_OBJECT@]@;
  14952. public:@/
  14953. Q_INVOKABLE@,@, Ni9211TcConfWidget(DeviceTreeModel *device,
  14954. const QModelIndex &index);
  14955. @[private slots@]:@/
  14956. void updateThermocoupleType(const QString &type);
  14957. void updateColumnName(const QString &name);
  14958. void updateHidden(bool hidden);
  14959. };
  14960. @ This follows the same pattern of previous device configuration widgets. The
  14961. constructor provides the required configuration controls and slot methods
  14962. catch configuration changes and update the underlying XML document
  14963. appropriately.
  14964. @<Ni9211TcConfWidget implementation@>=
  14965. Ni9211TcConfWidget::Ni9211TcConfWidget(DeviceTreeModel *model,
  14966. const QModelIndex &index) :
  14967. BasicDeviceConfigurationWidget(model, index)
  14968. {
  14969. QFormLayout *layout = new QFormLayout;
  14970. QLineEdit *columnName = new QLineEdit;
  14971. layout->addRow(tr("Column Name:"), columnName);
  14972. QComboBox *typeSelector = new QComboBox;
  14973. typeSelector->addItem("J");
  14974. typeSelector->addItem("K");
  14975. typeSelector->addItem("T");
  14976. typeSelector->addItem("B");
  14977. typeSelector->addItem("E");
  14978. typeSelector->addItem("N");
  14979. typeSelector->addItem("R");
  14980. typeSelector->addItem("S");
  14981. layout->addRow(tr("Thermocouple Type:"), typeSelector);
  14982. QCheckBox *hideSeries = new QCheckBox("Hide this channel");
  14983. layout->addRow(hideSeries);
  14984. setLayout(layout);
  14985. @<Get device configuration data for current node@>@;
  14986. for(int i = 0; i < configData.size(); i++)
  14987. {
  14988. node = configData.at(i).toElement();
  14989. if(node.attribute("name") == "type")
  14990. {
  14991. typeSelector->setCurrentIndex(
  14992. typeSelector->findText(node.attribute("value")));
  14993. }
  14994. else if(node.attribute("name") == "columnname")
  14995. {
  14996. columnName->setText(node.attribute("value"));
  14997. }
  14998. else if(node.attribute("name") == "hidden")
  14999. {
  15000. hideSeries->setChecked(node.attribute("value") == "true");
  15001. }
  15002. }
  15003. updateThermocoupleType(typeSelector->currentText());
  15004. updateColumnName(columnName->text());
  15005. updateHidden(hideSeries->isChecked());
  15006. connect(typeSelector, SIGNAL(currentIndexChanged(QString)),
  15007. this, SLOT(updateThermocoupleType(QString)));
  15008. connect(columnName, SIGNAL(textEdited(QString)), this, SLOT(updateColumnName(QString)));
  15009. connect(hideSeries, SIGNAL(toggled(bool)), this, SLOT(updateHidden(bool)));
  15010. }
  15011. @ Two slots are used to pass configuration changes back to the underlying XML
  15012. representation.
  15013. @<Ni9211TcConfWidget implementation@>=
  15014. void Ni9211TcConfWidget::updateThermocoupleType(const QString &type)
  15015. {
  15016. updateAttribute("type", type);
  15017. }
  15018. void Ni9211TcConfWidget::updateColumnName(const QString &name)
  15019. {
  15020. updateAttribute("columnname", name);
  15021. }
  15022. void Ni9211TcConfWidget::updateHidden(bool hidden)
  15023. {
  15024. updateAttribute("hidden", hidden ? "true" : "false");
  15025. }
  15026. @ These three widgets need to be registered so the configuration widget can
  15027. instantiate them when the nodes are selected.
  15028. @<Register device configuration widgets@>=
  15029. app.registerDeviceConfigurationWidget("nidaqmxbase",
  15030. NiDaqMxBaseDriverConfWidget::staticMetaObject);
  15031. app.registerDeviceConfigurationWidget("nidaqmxbase9211series",
  15032. NiDaqMxBase9211ConfWidget::staticMetaObject);
  15033. app.registerDeviceConfigurationWidget("ni9211seriestc",
  15034. Ni9211TcConfWidget::staticMetaObject);
  15035. @ Furthermore, we should create the NodeInserter objects for adding top level
  15036. nodes to the configuration. Preferably we would only allow top level nodes to
  15037. be inserted when all prerequisite software is available.
  15038. @<Register top level device configuration nodes@>=
  15039. NodeInserter *inserter = new NodeInserter(tr("NI DAQmx Base Device"),
  15040. tr("NI DAQmx Base"),
  15041. "nidaqmxbase", NULL);
  15042. topLevelNodeInserters.append(inserter);
  15043. @** Configuration of NI-DAQmx devices.
  15044. \noindent The other main class of hardware currently supported in Typica is a
  15045. small set of devices that require NI-DAQmx. This includes a few combinations of
  15046. the NI 9211 in different carriers and the NI USB TC01. Additional hardware may
  15047. be added to this set in the future.
  15048. The approach here is very similar to the approach used to configure NI-DAQmx
  15049. Base devices, starting with a widget for adding child device nodes.
  15050. @<Class declarations@>=
  15051. class NiDaqMxDriverConfWidget : public BasicDeviceConfigurationWidget
  15052. {
  15053. @[Q_OBJECT@]@;
  15054. public:
  15055. @[Q_INVOKABLE@]@, NiDaqMxDriverConfWidget(DeviceTreeModel *model,
  15056. const QModelIndex &index);
  15057. };
  15058. @ Under our driver node we want to have the ability to insert device specific
  15059. child nodes.
  15060. @<NiDaqMxDriverConfWidget implementation@>=
  15061. NiDaqMxDriverConfWidget::NiDaqMxDriverConfWidget(DeviceTreeModel *model,
  15062. const QModelIndex &index)
  15063. : BasicDeviceConfigurationWidget(model, index)
  15064. {
  15065. QHBoxLayout *layout = new QHBoxLayout;
  15066. QToolButton *addDeviceButton = new QToolButton;
  15067. addDeviceButton->setText(tr("Add Device"));
  15068. NodeInserter *add9211a = new NodeInserter("NI USB 9211A", "NI USB 9211A",
  15069. "nidaqmx9211series");
  15070. NodeInserter *addtc01 = new NodeInserter("NI USB TC01", "NI USB TC01",
  15071. "nidaqmxtc01");
  15072. connect(add9211a, SIGNAL(triggered(QString, QString)),
  15073. this, SLOT(insertChildNode(QString, QString)));
  15074. connect(addtc01, SIGNAL(triggered(QString, QString)),
  15075. this, SLOT(insertChildNode(QString, QString)));
  15076. QMenu *deviceMenu = new QMenu;
  15077. deviceMenu->addAction(add9211a);
  15078. deviceMenu->addAction(addtc01);
  15079. addDeviceButton->setMenu(deviceMenu);
  15080. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  15081. layout->addWidget(addDeviceButton);
  15082. setLayout(layout);
  15083. }
  15084. @ Devices based on the 9211 module are essentially the same aside from device
  15085. naming convention. Configuring these is very similar to configuring similar
  15086. devices when using NI-DAQmx Base.
  15087. @<Class declarations@>=
  15088. class NiDaqMx9211ConfWidget : public BasicDeviceConfigurationWidget
  15089. {
  15090. @[Q_OBJECT@]@;
  15091. public:@/
  15092. @[Q_INVOKABLE@]@, NiDaqMx9211ConfWidget(DeviceTreeModel *model,
  15093. const QModelIndex &index);
  15094. @[private slots@]:@/
  15095. void addChannel();
  15096. void updateDeviceId(const QString &newId);
  15097. };
  15098. @ Implementation is essentially identical to the NI-DAQmx Base class. It is
  15099. likely that there will be differences if this is ever extended to support
  15100. automatic detection of connected hardware. While NI-DAQmx Base does not
  15101. provide a way to query device identifiers, it uses a consistent naming scheme
  15102. by which device identifiers can be discovered. While NI-DAQmx lacks the same
  15103. consistency in device identifiers, it does provide a way to query that
  15104. information.
  15105. @<NiDaqMx9211ConfWidget implementation@>=
  15106. NiDaqMx9211ConfWidget::NiDaqMx9211ConfWidget(DeviceTreeModel *model,
  15107. const QModelIndex &index)
  15108. : BasicDeviceConfigurationWidget(model, index)
  15109. {
  15110. QVBoxLayout *layout = new QVBoxLayout;
  15111. QHBoxLayout *deviceIdLayout = new QHBoxLayout;
  15112. QLabel *label = new QLabel(tr("Device ID:"));
  15113. QLineEdit *deviceId = new QLineEdit;
  15114. deviceIdLayout->addWidget(label);
  15115. deviceIdLayout->addWidget(deviceId);
  15116. QPushButton *addChannelButton = new QPushButton(tr("Add Channel"));
  15117. layout->addLayout(deviceIdLayout);
  15118. layout->addWidget(addChannelButton);
  15119. @<Get device configuration data for current node@>@;
  15120. for(int i = 0; i < configData.size(); i++)
  15121. {
  15122. node = configData.at(i).toElement();
  15123. if(node.attribute("name") == "deviceID")
  15124. {
  15125. deviceId->setText(node.attribute("value","Dev1"));
  15126. break;
  15127. }
  15128. }
  15129. updateDeviceId(deviceId->text());
  15130. connect(addChannelButton, SIGNAL(clicked()), this, SLOT(addChannel()));
  15131. connect(deviceId, SIGNAL(textEdited(QString)),
  15132. this, SLOT(updateDeviceId(QString)));
  15133. setLayout(layout);
  15134. }
  15135. void NiDaqMx9211ConfWidget::updateDeviceId(const QString &newId)
  15136. {
  15137. updateAttribute("deviceID", newId);
  15138. }
  15139. void NiDaqMx9211ConfWidget::addChannel()
  15140. {
  15141. insertChildNode(tr("Thermocouple channel"), "ni9211seriestc");
  15142. }
  15143. @ There is no need to create a configuration widget specific to the 9211 module
  15144. used in NI-DAQmx. The widget already used for NI-DAQmx Base can be used without
  15145. modification.
  15146. Configuring Typica for use with the NI USB-TC01 can be slightly simplified as
  15147. the device only has a single thermocouple channel. We can configure this without
  15148. requiring another node.
  15149. @<Class declarations@>=
  15150. class NiDaqMxTc01ConfWidget : public BasicDeviceConfigurationWidget
  15151. {
  15152. @[Q_OBJECT@]@;
  15153. public:@/
  15154. @[Q_INVOKABLE@]@, NiDaqMxTc01ConfWidget(DeviceTreeModel *model,
  15155. const QModelIndex &index);
  15156. @[private slots@]:@/
  15157. void updateDeviceId(const QString &newId);
  15158. void updateThermocoupleType(const QString &type);
  15159. void updateColumnName(const QString &name);
  15160. void updateHidden(bool hidden);
  15161. };
  15162. @ The implementation is similar to the other configuration widgets.
  15163. @<NiDaqMxTc01ConfWidget implementation@>=
  15164. NiDaqMxTc01ConfWidget::NiDaqMxTc01ConfWidget(DeviceTreeModel *model,
  15165. const QModelIndex &index)
  15166. : BasicDeviceConfigurationWidget(model, index)
  15167. {
  15168. QFormLayout *layout = new QFormLayout;
  15169. QLineEdit *deviceId = new QLineEdit;
  15170. layout->addRow(tr("Device ID:"), deviceId);
  15171. QLineEdit *columnName = new QLineEdit;
  15172. layout->addRow(tr("Column Name:"), columnName);
  15173. QComboBox *typeSelector = new QComboBox;
  15174. typeSelector->addItem("J");
  15175. typeSelector->addItem("K");
  15176. typeSelector->addItem("T");
  15177. typeSelector->addItem("B");
  15178. typeSelector->addItem("E");
  15179. typeSelector->addItem("N");
  15180. typeSelector->addItem("R");
  15181. typeSelector->addItem("S");
  15182. layout->addRow(tr("Thermocouple Type:"), typeSelector);
  15183. QCheckBox *hideSeries = new QCheckBox(tr("Hide this channel"));
  15184. layout->addRow(hideSeries);
  15185. @<Get device configuration data for current node@>@;
  15186. for(int i = 0; i < configData.size(); i++)
  15187. {
  15188. node = configData.at(i).toElement();
  15189. if(node.attribute("name") == "deviceID")
  15190. {
  15191. deviceId->setText(node.attribute("value"));
  15192. }
  15193. else if(node.attribute("name") == "type")
  15194. {
  15195. typeSelector->setCurrentIndex(typeSelector->findText(node.attribute("value")));
  15196. }
  15197. else if(node.attribute("name") == "columnname")
  15198. {
  15199. columnName->setText(node.attribute("value"));
  15200. }
  15201. else if(node.attribute("name") == "hidden")
  15202. {
  15203. hideSeries->setChecked(node.attribute("value") == "true");
  15204. }
  15205. }
  15206. updateDeviceId(deviceId->text());
  15207. updateThermocoupleType(typeSelector->currentText());
  15208. updateColumnName(columnName->text());
  15209. updateHidden(hideSeries->isChecked());
  15210. connect(deviceId, SIGNAL(textEdited(QString)), this, SLOT(updateDeviceId(QString)));
  15211. connect(typeSelector, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateThermocoupleType(QString)));
  15212. connect(columnName, SIGNAL(textEdited(QString)), this, SLOT(updateColumnName(QString)));
  15213. setLayout(layout);
  15214. connect(hideSeries, SIGNAL(toggled(bool)), this, SLOT(updateHidden(bool)));
  15215. }
  15216. void NiDaqMxTc01ConfWidget::updateDeviceId(const QString &newId)
  15217. {
  15218. updateAttribute("deviceID", newId);
  15219. }
  15220. void NiDaqMxTc01ConfWidget::updateThermocoupleType(const QString &type)
  15221. {
  15222. updateAttribute("type", type);
  15223. }
  15224. void NiDaqMxTc01ConfWidget::updateColumnName(const QString &name)
  15225. {
  15226. updateAttribute("columnname", name);
  15227. }
  15228. void NiDaqMxTc01ConfWidget::updateHidden(bool hidden)
  15229. {
  15230. updateAttribute("hidden", hidden ? "true" : "false");
  15231. }
  15232. @ These configuration widgets need to be registered so they can be instantiated
  15233. in response to node selections.
  15234. @<Register device configuration widgets@>=
  15235. app.registerDeviceConfigurationWidget("nidaqmx", NiDaqMxDriverConfWidget::staticMetaObject);
  15236. app.registerDeviceConfigurationWidget("nidaqmx9211series", NiDaqMx9211ConfWidget::staticMetaObject);
  15237. app.registerDeviceConfigurationWidget("nidaqmxtc01", NiDaqMxTc01ConfWidget::staticMetaObject);
  15238. @ A |NodeInserter| for the driver configuration widget is also needed. Note that
  15239. at present NI DAQmx is only available on Windows so we do not bother to show
  15240. the option on other platforms. It would be generally preferable to replace this
  15241. with a check at runtime to determine if the required library exists. That could
  15242. be done with anything that requires third party installed code, leaving by
  15243. default only those options which have no external dependencies.
  15244. @<Register top level device configuration nodes@>=
  15245. #ifdef Q_OS_WIN32
  15246. inserter = new NodeInserter(tr("NI DAQmx Device"), tr("NI DAQmx"), "nidaqmx", NULL);
  15247. topLevelNodeInserters.append(inserter);
  15248. #endif
  15249. @** Configuration of Serial Port Devices.
  15250. \noindent It is possible to communicate with a number of devices through a
  15251. serial port. To do this, the appropriate settings for opening the port are
  15252. required and the communications protocol understood by the device must be
  15253. known. Serial port communications are provided by QextSerialPort. That
  15254. project was released under the MIT license.\nfnote{See the license text for
  15255. more information.} Additional headers are required.
  15256. @<Header files to include@>=
  15257. #include "qextserialport.h"
  15258. #include "qextserialenumerator.h"
  15259. @ Some custom widgets are provided which allow selecting the relevant
  15260. connection options from combo boxes. First there is a widget for selecting
  15261. the desired serial port. The drop down is pre-populated with any serial ports
  15262. that could be automatically detected, but the field can also be edited to
  15263. other values as may be required if the hardware is not connected during
  15264. configuration.
  15265. @<Class declarations@>=
  15266. class PortSelector : public QComboBox
  15267. {
  15268. Q_OBJECT
  15269. public:
  15270. PortSelector(QWidget *parent = NULL);
  15271. private slots:
  15272. void addDevice(QextPortInfo port);
  15273. private:
  15274. QextSerialEnumerator *lister;
  15275. };
  15276. @ The implementation is trivial.
  15277. @<PortSelector implementation@>=
  15278. PortSelector::PortSelector(QWidget *parent) : QComboBox(parent),
  15279. lister(new QextSerialEnumerator)
  15280. {
  15281. QList<QextPortInfo> ports = QextSerialEnumerator::getPorts();
  15282. QextPortInfo port;
  15283. foreach(port, ports)
  15284. {
  15285. #ifdef Q_OS_WIN32
  15286. addItem(port.portName);
  15287. #else
  15288. addItem(port.physName);
  15289. #endif
  15290. }
  15291. lister->setUpNotifications();
  15292. connect(lister, SIGNAL(deviceDiscovered(QextPortInfo)),
  15293. this, SLOT(addDevice(QextPortInfo)));
  15294. setEditable(true);
  15295. }
  15296. void PortSelector::addDevice(QextPortInfo port)
  15297. {
  15298. addItem(port.portName);
  15299. }
  15300. @ Next is a widget which allows selecting the baud rate. Only rates supported
  15301. by the current operating system are available to select.
  15302. A later version of QextSerialPort than is used by \pn{} provides a helper
  15303. class which can be used more conveniently to create this sort of control. As
  15304. this is not yet available to \pn{}, we instead copy the |enum| specifying
  15305. the appropriate values into the class and use Qt'@q'@>s meta-object system to
  15306. populate the combo box based on the values in that |enum|.
  15307. @<Class declarations@>=
  15308. class BaudSelector : public QComboBox
  15309. {
  15310. Q_OBJECT
  15311. Q_ENUMS(BaudRateType)
  15312. public:
  15313. BaudSelector(QWidget *parent = NULL);
  15314. enum BaudRateType
  15315. {
  15316. #if defined(Q_OS_UNIX) || defined(qdoc)
  15317. BAUD50 = 50, //POSIX ONLY
  15318. BAUD75 = 75, //POSIX ONLY
  15319. BAUD134 = 134, //POSIX ONLY
  15320. BAUD150 = 150, //POSIX ONLY
  15321. BAUD200 = 200, //POSIX ONLY
  15322. BAUD1800 = 1800, //POSIX ONLY
  15323. #if defined(B76800) || defined(qdoc)
  15324. BAUD76800 = 76800, //POSIX ONLY
  15325. #endif
  15326. #if (defined(B230400) && defined(B4000000)) || defined(qdoc)
  15327. BAUD230400 = 230400, //POSIX ONLY
  15328. BAUD460800 = 460800, //POSIX ONLY
  15329. BAUD500000 = 500000, //POSIX ONLY
  15330. BAUD576000 = 576000, //POSIX ONLY
  15331. BAUD921600 = 921600, //POSIX ONLY
  15332. BAUD1000000 = 1000000, //POSIX ONLY
  15333. BAUD1152000 = 1152000, //POSIX ONLY
  15334. BAUD1500000 = 1500000, //POSIX ONLY
  15335. BAUD2000000 = 2000000, //POSIX ONLY
  15336. BAUD2500000 = 2500000, //POSIX ONLY
  15337. BAUD3000000 = 3000000, //POSIX ONLY
  15338. BAUD3500000 = 3500000, //POSIX ONLY
  15339. BAUD4000000 = 4000000, //POSIX ONLY
  15340. #endif
  15341. #endif
  15342. #if defined(Q_OS_WIN) || defined(qdoc)
  15343. BAUD14400 = 14400, //WINDOWS ONLY
  15344. BAUD56000 = 56000, //WINDOWS ONLY
  15345. BAUD128000 = 128000, //WINDOWS ONLY
  15346. BAUD256000 = 256000, //WINDOWS ONLY
  15347. #endif
  15348. BAUD110 = 110,
  15349. BAUD300 = 300,
  15350. BAUD600 = 600,
  15351. BAUD1200 = 1200,
  15352. BAUD2400 = 2400,
  15353. BAUD4800 = 4800,
  15354. BAUD9600 = 9600,
  15355. BAUD19200 = 19200,
  15356. BAUD38400 = 38400,
  15357. BAUD57600 = 57600,
  15358. BAUD115200 = 115200
  15359. };
  15360. };
  15361. @ As the |enum| values are identical to the baud rates represented, we only
  15362. the numeric values, ignoring the names which are rather ugly.
  15363. @<BaudSelector implementation@>=
  15364. BaudSelector::BaudSelector(QWidget *parent) : QComboBox(parent)
  15365. {
  15366. QMetaObject meta = BaudSelector::staticMetaObject;
  15367. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("BaudRateType"));
  15368. for(int i = 0; i < type.keyCount(); i++)
  15369. {
  15370. addItem(QString("%1").arg(type.value(i)));
  15371. }
  15372. }
  15373. @ This same technique is used in a widget for selecting parity.
  15374. @<Class declarations@>=
  15375. class ParitySelector : public QComboBox
  15376. {
  15377. Q_OBJECT
  15378. Q_ENUMS(ParityType)
  15379. public:
  15380. ParitySelector(QWidget *parent = NULL);
  15381. enum ParityType
  15382. {
  15383. PAR_NONE,
  15384. PAR_ODD,
  15385. PAR_EVEN,
  15386. #if defined(Q_OS_WIN) || defined(qdoc)
  15387. PAR_MARK, //WINDOWS ONLY
  15388. #endif
  15389. PAR_SPACE
  15390. };
  15391. };
  15392. @ Implementation is similar to |BaudSelector| but as the values have no
  15393. apparent relation to what is represented we present the value names, placing
  15394. the corresponding value in the user data space associated with each entry.
  15395. The names here are ugly and not amenable to localization so this approach
  15396. should be reconsidered later.
  15397. @<ParitySelector implementation@>=
  15398. ParitySelector::ParitySelector(QWidget *parent) : QComboBox(parent)
  15399. {
  15400. QMetaObject meta = ParitySelector::staticMetaObject;
  15401. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("ParityType"));
  15402. for(int i = 0; i < type.keyCount(); i++)
  15403. {
  15404. addItem(QString(type.key(i)), QVariant(type.value(i)));
  15405. }
  15406. }
  15407. @ Similarly, we have a widget for selecting a method for flow control.
  15408. @<Class declarations@>=
  15409. class FlowSelector : public QComboBox
  15410. {
  15411. @[Q_OBJECT@]@;
  15412. @[Q_ENUMS(FlowType)@]@;
  15413. public:@/
  15414. FlowSelector(QWidget *parent = NULL);
  15415. enum FlowType
  15416. {
  15417. FLOW_OFF,
  15418. FLOW_HARDWARE,
  15419. FLOW_XONXOFF
  15420. };
  15421. };
  15422. @ Implementation follows the same pattern as in |ParitySelector|.
  15423. @<FlowSelector implementation@>=
  15424. FlowSelector::FlowSelector(QWidget *parent) : QComboBox(parent)
  15425. {
  15426. QMetaObject meta = FlowSelector::staticMetaObject;
  15427. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("FlowType"));
  15428. for(int i = 0; i < type.keyCount(); i++)
  15429. {
  15430. addItem(QString(type.key(i)), QVariant(type.value(i)));
  15431. }
  15432. }
  15433. @ We assume that the number of data bits will always be 8, though it may be
  15434. useful to later provide a control for selecting this for use with other devices
  15435. where this may not be assumed or for the sake of completion. This only leaves
  15436. specifying the number of stop bits.
  15437. @<Class declarations@>=
  15438. class StopSelector : public QComboBox
  15439. {
  15440. @[Q_OBJECT@]@;
  15441. @[Q_ENUMS(StopBitsType)@]@;
  15442. public:@/
  15443. StopSelector(QWidget *parent = NULL);
  15444. enum StopBitsType
  15445. {
  15446. STOP_1,
  15447. #if defined(Q_OS_WIN) || defined(qdoc)
  15448. STOP_1_5, //WINDOWS ONLY
  15449. #endif
  15450. STOP_2
  15451. };
  15452. };
  15453. @ Implementation should be familiar by now.
  15454. @<StopSelector implementation@>=
  15455. StopSelector::StopSelector(QWidget *parent) : QComboBox(parent)
  15456. {
  15457. QMetaObject meta = StopSelector::staticMetaObject;
  15458. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("StopBitsType"));
  15459. for(int i = 0; i < type.keyCount(); i++)
  15460. {
  15461. addItem(QString(type.key(i)), QVariant(type.value(i)));
  15462. }
  15463. }
  15464. @** Configuration of Serial Devices Using Modbus RTU.
  15465. \noindent The following sections contain the details of older code related to
  15466. Modbus RTU support. While the various selector widgets are shared with the new
  15467. code, the configuration widgets and device interfaces are being replaced.
  15468. One protocol that is used across a broad class of devices is called
  15469. Modbus RTU. This protocol allows multiple devices to be chained together on a
  15470. two wire bus which can be connected to a single serial port. The communication
  15471. protocol involves a single message which is sent from a master device (in this
  15472. case the computer running Typica) to a slave device (the device we would like
  15473. to obtain information from) which is followed by a response message from the
  15474. slave to the master. After a brief wait the master can then send another
  15475. message to any slave on the bus and this process repeats. Every outgoing
  15476. message provides a station address to identify which slave on the bus should
  15477. respond, a function code to identify which of a broad class of operations has
  15478. been requested, the required data for the function specified, and a cyclic
  15479. redundancy check to validate the message.
  15480. @** A Spin Box with Hexadecimal Representation.
  15481. \noindent Common convention for communications documentation for devices that
  15482. use Modbus RTU is that relative addresses are specified in hexadecimal
  15483. representation. In order to simplify initial device configuration, it would be
  15484. best that input widgets both accept input in base 16 and display values as a
  15485. four digit hexadecimal value.
  15486. @<Class declarations@>=
  15487. class ShortHexSpinBox : public QSpinBox
  15488. {
  15489. @[Q_OBJECT@]@;
  15490. public:@/
  15491. ShortHexSpinBox(QWidget *parent = NULL);
  15492. virtual QValidator::State validate(QString &input, int &pos) const;@/
  15493. protected:@/
  15494. virtual int valueFromText(const QString &text) const;
  15495. virtual QString textFromValue(int value) const;@/
  15496. };
  15497. @ For this we can set some new defaults in the constructor and must override
  15498. three methods.
  15499. @<ShortHexSpinBox implementation@>=
  15500. ShortHexSpinBox::ShortHexSpinBox(QWidget *parent) : QSpinBox(parent)
  15501. {
  15502. setMinimum(0);
  15503. setMaximum(0xFFFF);
  15504. setPrefix("0x");
  15505. setMinimumWidth(65);
  15506. }
  15507. QValidator::State ShortHexSpinBox::validate(QString &input, int &) const
  15508. {
  15509. if(input.size() == 2)
  15510. {
  15511. return QValidator::Intermediate;
  15512. }
  15513. bool okay;
  15514. input.toInt(&okay, 16);
  15515. if(okay)
  15516. {
  15517. return QValidator::Acceptable;
  15518. }
  15519. return QValidator::Invalid;
  15520. }
  15521. int ShortHexSpinBox::valueFromText(const QString &text) const
  15522. {
  15523. return text.toInt(NULL, 16);
  15524. }
  15525. QString ShortHexSpinBox::textFromValue(int value) const
  15526. {
  15527. QString retval;
  15528. retval.setNum(value, 16);
  15529. while(retval.size() < 4)
  15530. {
  15531. retval.prepend("0");
  15532. }
  15533. return retval.toUpper();
  15534. }
  15535. @** Configuration Widgets for Modbus RTU Devices.
  15536. \noindent While the top level configuration widgets seen so far have not had
  15537. any configuration details beyond the ability to add devices under the driver,
  15538. in the case of a serial port with Modbus RTU devices it is reasonable to
  15539. provide the connection details which will be shared by all devices on the bus.
  15540. @<Class declarations@>=
  15541. class ModbusRtuPortConfWidget : public BasicDeviceConfigurationWidget
  15542. {
  15543. @[Q_OBJECT@]@;
  15544. public:
  15545. @[Q_INVOKABLE@]@, ModbusRtuPortConfWidget(DeviceTreeModel *model,
  15546. const QModelIndex &index);
  15547. @[private slots@]:@/
  15548. void updatePort(const QString &newPort);
  15549. void updateBaudRate(const QString &newRate);
  15550. void updateParity(const QString &newParity);
  15551. void updateFlowControl(const QString &newFlow);
  15552. void updateStopBits(const QString &newStopBits);
  15553. };
  15554. @ Aside from the extra information compared with other configuration widgets
  15555. previously described, there is nothing surprising about the implementation.
  15556. @<ModbusRtuPortConfWidget implementation@>=
  15557. ModbusRtuPortConfWidget::ModbusRtuPortConfWidget(DeviceTreeModel *model,
  15558. const QModelIndex &index)
  15559. : BasicDeviceConfigurationWidget(model, index)
  15560. {
  15561. QFormLayout *layout = new QFormLayout;
  15562. QToolButton *addDeviceButton = new QToolButton;
  15563. addDeviceButton->setText(tr("Add Device"));
  15564. NodeInserter *addModbusRtuDevice = new NodeInserter("Modbus RTU Device",
  15565. "Modbus RTU Device",
  15566. "modbusrtudevice");
  15567. connect(addModbusRtuDevice, SIGNAL(triggered(QString, QString)),
  15568. this, SLOT(insertChildNode(QString, QString)));
  15569. QMenu *deviceMenu = new QMenu;
  15570. deviceMenu->addAction(addModbusRtuDevice);
  15571. addDeviceButton->setMenu(deviceMenu);
  15572. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  15573. layout->addRow(QString(), addDeviceButton);
  15574. PortSelector *port = new PortSelector;
  15575. layout->addRow(tr("Port:"), port);
  15576. connect(port, SIGNAL(currentIndexChanged(QString)),
  15577. this, SLOT(updatePort(QString)));
  15578. connect(port, SIGNAL(editTextChanged(QString)),
  15579. this, SLOT(updatePort(QString)));
  15580. BaudSelector *rate = new BaudSelector;
  15581. layout->addRow(tr("Baud:"), rate);
  15582. connect(rate, SIGNAL(currentIndexChanged(QString)),
  15583. this, SLOT(updateBaudRate(QString)));
  15584. ParitySelector *parity = new ParitySelector;
  15585. layout->addRow(tr("Parity:"), parity);
  15586. connect(parity, SIGNAL(currentIndexChanged(QString)),
  15587. this, SLOT(updateParity(QString)));
  15588. FlowSelector *flow = new FlowSelector;
  15589. layout->addRow(tr("Flow Control:"), flow);
  15590. connect(flow, SIGNAL(currentIndexChanged(QString)),
  15591. this, SLOT(updateFlowControl(QString)));
  15592. StopSelector *stop = new StopSelector;
  15593. layout->addRow(tr("Stop Bits:"), stop);
  15594. connect(stop, SIGNAL(currentIndexChanged(QString)),
  15595. this, SLOT(updateStopBits(QString)));
  15596. @<Get device configuration data for current node@>@;
  15597. for(int i = 0; i < configData.size(); i++)
  15598. {
  15599. node = configData.at(i).toElement();
  15600. if(node.attribute("name") == "port")
  15601. {
  15602. int j = port->findText(node.attribute("value"));
  15603. if(j >= 0)
  15604. {
  15605. port->setCurrentIndex(j);
  15606. }
  15607. else
  15608. {
  15609. port->insertItem(0, node.attribute("value"));
  15610. port->setCurrentIndex(0);
  15611. }
  15612. }
  15613. else if(node.attribute("name") == "baudrate")
  15614. {
  15615. rate->setCurrentIndex(rate->findText(node.attribute("value")));
  15616. }
  15617. else if(node.attribute("name") == "parity")
  15618. {
  15619. parity->setCurrentIndex(parity->findText(node.attribute("value")));
  15620. }
  15621. else if(node.attribute("name") == "flowcontrol")
  15622. {
  15623. flow->setCurrentIndex(flow->findText(node.attribute("value")));
  15624. }
  15625. else if(node.attribute("name") == "stopbits")
  15626. {
  15627. stop->setCurrentIndex(stop->findText(node.attribute("value")));
  15628. }
  15629. }
  15630. updatePort(port->currentText());
  15631. updateBaudRate(rate->currentText());
  15632. updateParity(parity->currentText());
  15633. updateFlowControl(flow->currentText());
  15634. updateStopBits(stop->currentText());
  15635. setLayout(layout);
  15636. }
  15637. void ModbusRtuPortConfWidget::updatePort(const QString &newPort)
  15638. {
  15639. updateAttribute("port", newPort);
  15640. }
  15641. void ModbusRtuPortConfWidget::updateBaudRate(const QString &newRate)
  15642. {
  15643. updateAttribute("baudrate", newRate);
  15644. }
  15645. void ModbusRtuPortConfWidget::updateParity(const QString &newParity)
  15646. {
  15647. updateAttribute("parity", newParity);
  15648. }
  15649. void ModbusRtuPortConfWidget::updateFlowControl(const QString &newFlow)
  15650. {
  15651. updateAttribute("flowcontrol", newFlow);
  15652. }
  15653. void ModbusRtuPortConfWidget::updateStopBits(const QString &newStopBits)
  15654. {
  15655. updateAttribute("stopbits", newStopBits);
  15656. }
  15657. @ From here we need to provide a widget for configuring a particular device.
  15658. At a minimum this would require setting the station number to a value between
  15659. 0 and 255. Zero is typically the broadcast address which reaches all devices
  15660. on the bus and is not generally recommended for use except in particular
  15661. circumstances. There are, however, a number of settings that influence all of
  15662. the currently supported child nodes and these settings are in the device
  15663. configuration widget instead of requiring that information to be duplicated
  15664. across multiple child nodes.
  15665. The Modbus RTU protocol is very general in scope and leaves many of the
  15666. details of how to do certain things up to the manufacturer. For rudimentary
  15667. support of devices using this protocol, the documentation for several devices
  15668. was consulted and a test rig with one device was set up. There are a number of
  15669. assumptions made for this initial support and to better support additional
  15670. device classes it may become necessary to expand on what is provided initially.
  15671. The primary focus presently is on the use of PID controllers as temperature
  15672. indicators with the ability to modify a set value in the case where this is
  15673. used as a controller rather than just a display.
  15674. All of the devices studied prior to adding this support made use of scaled
  15675. integer representation. In order to correctly determine the measured process
  15676. value it is necessary to know the unit of the measurement and the position of
  15677. the decimal point. It is generally possible to query this information, however
  15678. it may be useful to provide a way to specify fixed values in the event that a
  15679. device exposes these details in a way that is incompatible with my assumptions.
  15680. @<Class declarations@>=
  15681. class ModbusRtuDeviceConfWidget : public BasicDeviceConfigurationWidget
  15682. {
  15683. @[Q_OBJECT@]@;
  15684. public:@/
  15685. @[Q_INVOKABLE@]@, ModbusRtuDeviceConfWidget(DeviceTreeModel *model,
  15686. const QModelIndex &index);
  15687. @[private slots@]:@/
  15688. void updateStationNumber(int newStation);
  15689. void updateFixedUnit(bool newFixed);
  15690. void updateFixedDecimal(bool newFixed);
  15691. void updateUnit(const QString &newUnit);
  15692. void updateUnitAddress(int newAddress);
  15693. void updateValueF(int newValue);
  15694. void updateValueC(int newValue);
  15695. void updatePrecisionAddress(int newAddress);
  15696. void updatePrecisionValue(int newValue);
  15697. private:@/
  15698. QStackedLayout *unitSpecificationLayout;
  15699. QStackedLayout *decimalSpecificationLayout;
  15700. };
  15701. @ This widget has a number of differences from previous configuration widgets.
  15702. Perhaps most significantly there are controls which do not provide a text based
  15703. signal on state change. We also set certain controls as disabled when the
  15704. provided values are not relevant to operations such as when switching between
  15705. fixed decimal position and looking up decimal position from the device. Aside
  15706. from these details the widget operates according to the same principles as the
  15707. other widgets already seen.
  15708. @<ModbusRtuDeviceConfWidget implementation@>=
  15709. ModbusRtuDeviceConfWidget::ModbusRtuDeviceConfWidget(DeviceTreeModel *model,
  15710. const QModelIndex &index)
  15711. : BasicDeviceConfigurationWidget(model, index),
  15712. unitSpecificationLayout(new QStackedLayout),
  15713. decimalSpecificationLayout(new QStackedLayout)
  15714. {
  15715. QVBoxLayout *layout = new QVBoxLayout;
  15716. QToolButton *addChannelButton = new QToolButton;
  15717. addChannelButton->setText(tr("Add Channel"));
  15718. NodeInserter *addTemperaturePV = new NodeInserter("Temperature Process Value",
  15719. "Temperature Process Value",
  15720. "modbustemperaturepv");
  15721. NodeInserter *addTemperatureSV = new NodeInserter("Temperature Set Value",
  15722. "Temperature Set Value",
  15723. "modbustemperaturesv");
  15724. connect(addTemperaturePV, SIGNAL(triggered(QString, QString)),
  15725. this, SLOT(insertChildNode(QString, QString)));
  15726. connect(addTemperatureSV, SIGNAL(triggered(QString, QString)),
  15727. this, SLOT(insertChildNode(QString, QString)));
  15728. QMenu *channelMenu = new QMenu;
  15729. channelMenu->addAction(addTemperaturePV);
  15730. channelMenu->addAction(addTemperatureSV);
  15731. addChannelButton->setMenu(channelMenu);
  15732. addChannelButton->setPopupMode(QToolButton::InstantPopup);
  15733. layout->addWidget(addChannelButton);
  15734. QHBoxLayout *stationLayout = new QHBoxLayout;
  15735. QLabel *stationLabel = new QLabel(tr("Station:"));
  15736. QSpinBox *stationNumber = new QSpinBox;
  15737. stationNumber->setMinimum(0);
  15738. stationNumber->setMaximum(255);
  15739. stationLayout->addWidget(stationLabel);
  15740. stationLayout->addWidget(stationNumber);
  15741. layout->addLayout(stationLayout);
  15742. QCheckBox *fixedUnit = new QCheckBox(tr("Fixed Temperature Unit"));
  15743. layout->addWidget(fixedUnit);
  15744. QWidget *fixedUnitPlaceholder = new QWidget(this);
  15745. QHBoxLayout *fixedUnitLayout = new QHBoxLayout;
  15746. QLabel *fixedUnitLabel = new QLabel(tr("Temperature Unit:"));
  15747. QComboBox *fixedUnitSelector = new QComboBox;
  15748. fixedUnitSelector->addItem("Fahrenheit");
  15749. fixedUnitSelector->addItem("Celsius");
  15750. fixedUnitLayout->addWidget(fixedUnitLabel);
  15751. fixedUnitLayout->addWidget(fixedUnitSelector);
  15752. fixedUnitPlaceholder->setLayout(fixedUnitLayout);
  15753. unitSpecificationLayout->addWidget(fixedUnitPlaceholder);
  15754. QWidget *queriedUnitPlaceholder = new QWidget(this);
  15755. QFormLayout *queriedUnitLayout = new QFormLayout;
  15756. ShortHexSpinBox *unitAddress = new ShortHexSpinBox;
  15757. queriedUnitLayout->addRow(tr("Function 0x03 Unit Address:"), unitAddress);
  15758. QSpinBox *valueF = new QSpinBox;
  15759. valueF->setMinimum(0);
  15760. valueF->setMaximum(65535);
  15761. queriedUnitLayout->addRow(tr("Value for Fahrenheit"), valueF);
  15762. QSpinBox *valueC = new QSpinBox;
  15763. valueC->setMinimum(0);
  15764. valueC->setMaximum(65535);
  15765. queriedUnitLayout->addRow(tr("Value for Celsius"), valueC);
  15766. queriedUnitPlaceholder->setLayout(queriedUnitLayout);
  15767. unitSpecificationLayout->addWidget(queriedUnitPlaceholder);
  15768. layout->addLayout(unitSpecificationLayout);
  15769. QCheckBox *fixedPrecision = new QCheckBox(tr("Fixed Precision"));
  15770. layout->addWidget(fixedPrecision);
  15771. QWidget *fixedPrecisionPlaceholder = new QWidget(this);
  15772. QFormLayout *fixedPrecisionLayout = new QFormLayout;
  15773. QSpinBox *fixedPrecisionValue = new QSpinBox;
  15774. fixedPrecisionValue->setMinimum(0);
  15775. fixedPrecisionValue->setMaximum(9);
  15776. fixedPrecisionLayout->addRow("Places after the decimal point:",
  15777. fixedPrecisionValue);
  15778. fixedPrecisionPlaceholder->setLayout(fixedPrecisionLayout);
  15779. decimalSpecificationLayout->addWidget(fixedPrecisionPlaceholder);
  15780. QWidget *queriedPrecisionPlaceholder = new QWidget(this);
  15781. QFormLayout *queriedPrecisionLayout = new QFormLayout;
  15782. ShortHexSpinBox *precisionAddress = new ShortHexSpinBox;
  15783. queriedPrecisionLayout->addRow("Function 0x03 Decimal Position Address:",
  15784. precisionAddress);
  15785. queriedPrecisionPlaceholder->setLayout(queriedPrecisionLayout);
  15786. decimalSpecificationLayout->addWidget(queriedPrecisionPlaceholder);
  15787. layout->addLayout(decimalSpecificationLayout);
  15788. @<Get device configuration data for current node@>@;
  15789. for(int i = 0; i < configData.size(); i++)
  15790. {
  15791. node = configData.at(i).toElement();
  15792. if(node.attribute("name") == "station")
  15793. {
  15794. stationNumber->setValue(node.attribute("value").toInt());
  15795. }
  15796. else if(node.attribute("name") == "fixedunit")
  15797. {
  15798. if(node.attribute("value") == "true")
  15799. {
  15800. fixedUnit->setCheckState(Qt::Checked);
  15801. }
  15802. else if(node.attribute("value") == "false")
  15803. {
  15804. fixedUnit->setCheckState(Qt::Unchecked);
  15805. }
  15806. }
  15807. else if(node.attribute("name") == "fixedprecision")
  15808. {
  15809. fixedPrecisionValue->setValue(node.attribute("value").toInt());
  15810. }
  15811. else if(node.attribute("name") == "unit")
  15812. {
  15813. fixedUnitSelector->setCurrentIndex(fixedUnitSelector->findText(node.attribute("value")));
  15814. }
  15815. else if(node.attribute("name") == "unitaddress")
  15816. {
  15817. unitAddress->setValue(node.attribute("value").toInt());
  15818. }
  15819. else if(node.attribute("name") == "fvalue")
  15820. {
  15821. valueF->setValue(node.attribute("value").toInt());
  15822. }
  15823. else if(node.attribute("name") == "cvalue")
  15824. {
  15825. valueC->setValue(node.attribute("value").toInt());
  15826. }
  15827. else if(node.attribute("name") == "precisionaddress")
  15828. {
  15829. precisionAddress->setValue(node.attribute("value").toInt());
  15830. }
  15831. else if(node.attribute("name") == "precision")
  15832. {
  15833. fixedPrecisionValue->setValue(node.attribute("value").toInt());
  15834. }
  15835. }
  15836. updateStationNumber(stationNumber->value());
  15837. updateFixedUnit(fixedUnit->isChecked());
  15838. updateFixedDecimal(fixedPrecision->isChecked());
  15839. updateUnit(fixedUnitSelector->currentText());
  15840. updateUnitAddress(unitAddress->value());
  15841. updateValueF(valueF->value());
  15842. updateValueC(valueC->value());
  15843. updatePrecisionAddress(precisionAddress->value());
  15844. updatePrecisionValue(fixedPrecisionValue->value());
  15845. connect(stationNumber, SIGNAL(valueChanged(int)),
  15846. this, SLOT(updateStationNumber(int)));
  15847. connect(fixedUnitSelector, SIGNAL(currentIndexChanged(QString)),
  15848. this, SLOT(updateUnit(QString)));
  15849. connect(unitAddress, SIGNAL(valueChanged(int)),
  15850. this, SLOT(updateUnitAddress(int)));
  15851. connect(valueF, SIGNAL(valueChanged(int)),
  15852. this, SLOT(updateValueF(int)));
  15853. connect(valueC, SIGNAL(valueChanged(int)),
  15854. this, SLOT(updateValueC(int)));
  15855. connect(fixedUnit, SIGNAL(toggled(bool)),
  15856. this, SLOT(updateFixedUnit(bool)));
  15857. connect(fixedPrecision, SIGNAL(toggled(bool)),
  15858. this, SLOT(updateFixedDecimal(bool)));
  15859. connect(fixedPrecisionValue, SIGNAL(valueChanged(int)),
  15860. this, SLOT(updatePrecisionValue(int)));
  15861. connect(precisionAddress, SIGNAL(valueChanged(int)),
  15862. this, SLOT(updatePrecisionAddress(int)));
  15863. setLayout(layout);
  15864. }
  15865. void ModbusRtuDeviceConfWidget::updateStationNumber(int newStation)
  15866. {
  15867. updateAttribute("station", QString("%1").arg(newStation));
  15868. }
  15869. void ModbusRtuDeviceConfWidget::updateFixedUnit(bool newFixed)
  15870. {
  15871. if(newFixed)
  15872. {
  15873. unitSpecificationLayout->setCurrentIndex(0);
  15874. updateAttribute("fixedunit", "true");
  15875. }
  15876. else
  15877. {
  15878. unitSpecificationLayout->setCurrentIndex(1);
  15879. updateAttribute("fixedunit", "false");
  15880. }
  15881. }
  15882. void ModbusRtuDeviceConfWidget::updateFixedDecimal(bool newFixed)
  15883. {
  15884. if(newFixed)
  15885. {
  15886. decimalSpecificationLayout->setCurrentIndex(0);
  15887. updateAttribute("fixedprecision", "true");
  15888. }
  15889. else
  15890. {
  15891. decimalSpecificationLayout->setCurrentIndex(1);
  15892. updateAttribute("fixedprecision", "false");
  15893. }
  15894. }
  15895. void ModbusRtuDeviceConfWidget::updateUnit(const QString &newUnit)
  15896. {
  15897. updateAttribute("unit", newUnit);
  15898. }
  15899. void ModbusRtuDeviceConfWidget::updateUnitAddress(int newAddress)
  15900. {
  15901. updateAttribute("unitaddress", QString("%1").arg(newAddress));
  15902. }
  15903. void ModbusRtuDeviceConfWidget::updateValueF(int newValue)
  15904. {
  15905. updateAttribute("fvalue", QString("%1").arg(newValue));
  15906. }
  15907. void ModbusRtuDeviceConfWidget::updateValueC(int newValue)
  15908. {
  15909. updateAttribute("cvalue", QString("%1").arg(newValue));
  15910. }
  15911. void ModbusRtuDeviceConfWidget::updatePrecisionAddress(int newAddress)
  15912. {
  15913. updateAttribute("precisionaddress", QString("%1").arg(newAddress));
  15914. }
  15915. void ModbusRtuDeviceConfWidget::updatePrecisionValue(int newValue)
  15916. {
  15917. updateAttribute("precision", QString("%1").arg(newValue));
  15918. }
  15919. @ Initial Modbus RTU support is very limited and only considers temperature
  15920. process and set values. While in some cases it would be possible to cleverly
  15921. adapt this support to broader categories this is an area that must be extended
  15922. later to cover at least unitless control values and on/off status values. It
  15923. would be ideal to cover a broad range of useful properties. To read process
  15924. values we need to know the address that the current process value can be read
  15925. from.
  15926. @<Class declarations@>=
  15927. class ModbusRtuDeviceTPvConfWidget : public BasicDeviceConfigurationWidget
  15928. {
  15929. @[Q_OBJECT@]@/
  15930. public:@/
  15931. @[Q_INVOKABLE@]@, ModbusRtuDeviceTPvConfWidget(DeviceTreeModel *model,
  15932. const QModelIndex &index);
  15933. @[private slots@]:@/
  15934. void updateAddress(int newAddress);
  15935. };
  15936. @ This requires only a single field to store the address to query the current
  15937. process value.
  15938. @<ModbusRtuDeviceTPvConfWidget implementation@>=
  15939. ModbusRtuDeviceTPvConfWidget::ModbusRtuDeviceTPvConfWidget(DeviceTreeModel *model,
  15940. const QModelIndex &index)
  15941. : BasicDeviceConfigurationWidget(model, index)
  15942. {
  15943. QFormLayout *layout = new QFormLayout;
  15944. ShortHexSpinBox *address = new ShortHexSpinBox;
  15945. layout->addRow(tr("Function 0x04 Process Value Address"), address);
  15946. @<Get device configuration data for current node@>@;
  15947. for(int i = 0; i < configData.size(); i++)
  15948. {
  15949. node = configData.at(i).toElement();
  15950. if(node.attribute("name") == "address")
  15951. {
  15952. address->setValue(node.attribute("value").toInt());
  15953. break;
  15954. }
  15955. }
  15956. updateAddress(address->value());
  15957. connect(address, SIGNAL(valueChanged(int)), this, SLOT(updateAddress(int)));
  15958. setLayout(layout);
  15959. }
  15960. void ModbusRtuDeviceTPvConfWidget::updateAddress(int newAddress)
  15961. {
  15962. updateAttribute("address", QString("%1").arg(newAddress));
  15963. }
  15964. @ Set values are slightly more complicated as we may want either a fixed range
  15965. or the ability to query the device for its current allowed range, but nothing
  15966. is here that hasn'@q'@>t been seen elsewhere.
  15967. @<Class declarations@>=
  15968. class ModbusRtuDeviceTSvConfWidget : public BasicDeviceConfigurationWidget@/
  15969. {@/
  15970. @[Q_OBJECT@]@;
  15971. public:@/
  15972. Q_INVOKABLE@, ModbusRtuDeviceTSvConfWidget(DeviceTreeModel *model,
  15973. const QModelIndex &index);
  15974. @[private slots@]:@/
  15975. void updateReadAddress(int newAddress);
  15976. void updateWriteAddress(int newAddress);
  15977. void updateFixedRange(bool fixed);
  15978. void updateLower(const QString &lower);
  15979. void updateUpper(const QString &upper);
  15980. void updateLowerAddress(int newAddress);
  15981. void updateUpperAddress(int newAddress);@/
  15982. private:@/
  15983. QStackedLayout *boundsLayout;
  15984. };
  15985. @ Upper and lower bounds when operating on a fixed range are still subject to
  15986. decimal position rules in the parent node. It may be a good idea to enforce
  15987. this, however at present the person configuring the system is trusted to know
  15988. what they are doing.
  15989. @<ModbusRtuDeviceTSvConfWidget implementation@>=
  15990. ModbusRtuDeviceTSvConfWidget::ModbusRtuDeviceTSvConfWidget(DeviceTreeModel *model,
  15991. const QModelIndex &index)
  15992. : BasicDeviceConfigurationWidget(model, index), boundsLayout(new QStackedLayout)
  15993. {
  15994. QVBoxLayout *layout = new QVBoxLayout;
  15995. QFormLayout *addressLayout = new QFormLayout;
  15996. ShortHexSpinBox *readAddress = new ShortHexSpinBox;
  15997. ShortHexSpinBox *writeAddress = new ShortHexSpinBox;
  15998. addressLayout->addRow(tr("Function 0x04 Read Set Value Address:"), readAddress);
  15999. addressLayout->addRow(tr("Function 0x06 Write Set Value Address:"), writeAddress);
  16000. layout->addLayout(addressLayout);
  16001. QCheckBox *fixedRange = new QCheckBox(tr("Fixed Set Value Range"));
  16002. layout->addWidget(fixedRange);
  16003. QWidget *queriedRangePlaceholder = new QWidget(this);
  16004. QFormLayout *queriedRangeLayout = new QFormLayout;
  16005. ShortHexSpinBox *lowerAddress = new ShortHexSpinBox;
  16006. ShortHexSpinBox *upperAddress = new ShortHexSpinBox;
  16007. queriedRangeLayout->addRow(tr("Function 0x03 Minimum Set Value Address"),
  16008. lowerAddress);
  16009. queriedRangeLayout->addRow(tr("Function 0x03 Maximum Set Value Address"),
  16010. upperAddress);
  16011. queriedRangePlaceholder->setLayout(queriedRangeLayout);
  16012. boundsLayout->addWidget(queriedRangePlaceholder);
  16013. QWidget *fixedRangePlaceholder = new QWidget(this);
  16014. QFormLayout *fixedRangeLayout = new QFormLayout;
  16015. QLineEdit *fixedLower = new QLineEdit;
  16016. QLineEdit *fixedUpper = new QLineEdit;
  16017. fixedRangeLayout->addRow(tr("Minimum Set Value:"), fixedLower);
  16018. fixedRangeLayout->addRow(tr("Maximum Set Value:"), fixedUpper);
  16019. fixedRangePlaceholder->setLayout(fixedRangeLayout);
  16020. boundsLayout->addWidget(fixedRangePlaceholder);
  16021. layout->addLayout(boundsLayout);
  16022. @<Get device configuration data for current node@>@;
  16023. for(int i = 0; i < configData.size(); i++)
  16024. {
  16025. node = configData.at(i).toElement();
  16026. if(node.attribute("name") == "readaddress")
  16027. {
  16028. readAddress->setValue(node.attribute("value").toInt());
  16029. }
  16030. else if(node.attribute("name") == "writeaddress")
  16031. {
  16032. writeAddress->setValue(node.attribute("value").toInt());
  16033. }
  16034. else if(node.attribute("name") == "fixedrange")
  16035. {
  16036. if(node.attribute("value") == "true")
  16037. {
  16038. fixedRange->setCheckState(Qt::Checked);
  16039. }
  16040. else if(node.attribute("value") == "false")
  16041. {
  16042. fixedRange->setCheckState(Qt::Unchecked);
  16043. }
  16044. }
  16045. else if(node.attribute("name") == "fixedlower")
  16046. {
  16047. fixedLower->setText(node.attribute("value"));
  16048. }
  16049. else if(node.attribute("name") == "fixedupper")
  16050. {
  16051. fixedUpper->setText(node.attribute("value"));
  16052. }
  16053. else if(node.attribute("name") == "loweraddress")
  16054. {
  16055. lowerAddress->setValue(node.attribute("value").toInt());
  16056. }
  16057. else if(node.attribute("name") == "upperaddress")
  16058. {
  16059. upperAddress->setValue(node.attribute("value").toInt());
  16060. }
  16061. }
  16062. updateReadAddress(readAddress->value());
  16063. updateWriteAddress(writeAddress->value());
  16064. updateFixedRange(fixedRange->isChecked());
  16065. updateLower(fixedLower->text());
  16066. updateUpper(fixedUpper->text());
  16067. updateLowerAddress(lowerAddress->value());
  16068. updateUpperAddress(upperAddress->value());
  16069. connect(readAddress, SIGNAL(valueChanged(int)),
  16070. this, SLOT(updateReadAddress(int)));
  16071. connect(writeAddress, SIGNAL(valueChanged(int)),
  16072. this, SLOT(updateWriteAddress(int)));
  16073. connect(fixedRange, SIGNAL(toggled(bool)), this, SLOT(updateFixedRange(bool)));
  16074. connect(fixedLower, SIGNAL(textChanged(QString)),
  16075. this, SLOT(updateLower(QString)));
  16076. connect(fixedUpper, SIGNAL(textChanged(QString)),
  16077. this, SLOT(updateUpper(QString)));
  16078. connect(lowerAddress, SIGNAL(valueChanged(int)),
  16079. this, SLOT(updateLowerAddress(int)));
  16080. connect(upperAddress, SIGNAL(valueChanged(int)),
  16081. this, SLOT(updateUpperAddress(int)));
  16082. setLayout(layout);
  16083. }
  16084. void ModbusRtuDeviceTSvConfWidget::updateReadAddress(int newAddress)
  16085. {
  16086. updateAttribute("readaddress", QString("%1").arg(newAddress));
  16087. }
  16088. void ModbusRtuDeviceTSvConfWidget::updateWriteAddress(int newAddress)
  16089. {
  16090. updateAttribute("writeaddress", QString("%1").arg(newAddress));
  16091. }
  16092. void ModbusRtuDeviceTSvConfWidget::updateFixedRange(bool fixed)
  16093. {
  16094. if(fixed)
  16095. {
  16096. updateAttribute("fixedrange", "true");
  16097. boundsLayout->setCurrentIndex(1);
  16098. }
  16099. else
  16100. {
  16101. updateAttribute("fixedrange", "false");
  16102. boundsLayout->setCurrentIndex(0);
  16103. }
  16104. }
  16105. void ModbusRtuDeviceTSvConfWidget::updateLower(const QString &lower)
  16106. {
  16107. updateAttribute("fixedlower", lower);
  16108. }
  16109. void ModbusRtuDeviceTSvConfWidget::updateUpper(const QString &upper)
  16110. {
  16111. updateAttribute("fixedupper", upper);
  16112. }
  16113. void ModbusRtuDeviceTSvConfWidget::updateLowerAddress(int newAddress)
  16114. {
  16115. updateAttribute("loweraddress", QString("%1").arg(newAddress));
  16116. }
  16117. void ModbusRtuDeviceTSvConfWidget::updateUpperAddress(int newAddress)
  16118. {
  16119. updateAttribute("upperaddress", QString("%1").arg(newAddress));
  16120. }
  16121. @ The configuration widgets need to be registered.
  16122. @<Register device configuration widgets@>=
  16123. app.registerDeviceConfigurationWidget("modbusrtuport", ModbusRtuPortConfWidget::staticMetaObject);
  16124. app.registerDeviceConfigurationWidget("modbusrtudevice", ModbusRtuDeviceConfWidget::staticMetaObject);
  16125. app.registerDeviceConfigurationWidget("modbustemperaturepv", ModbusRtuDeviceTPvConfWidget::staticMetaObject);
  16126. app.registerDeviceConfigurationWidget("modbustemperaturesv", ModbusRtuDeviceTSvConfWidget::staticMetaObject);
  16127. @ A |NodeInserter| for the driver configuration widget is also needed. Note
  16128. that this is temporarily disabled. These configuration widgets will become
  16129. useful when I rearchitect the Modbus RTU support in a future release.
  16130. @<Register top level device configuration nodes@>=
  16131. #if 0
  16132. inserter = new NodeInserter(tr("Modbus RTU Port"), tr("Modbus RTU Port"), "modbusrtuport", NULL);
  16133. topLevelNodeInserters.append(inserter);
  16134. #endif
  16135. @** Configuration of Annotation Controls.
  16136. \noindent Aside from the details of hardware devices, the logging view must
  16137. also be able to set up log annotation controls. A few different control types
  16138. are offered. These include simple push buttons which insert a fixed annotation
  16139. when activated, push buttons which insert a value that includes a number which
  16140. is incremented every time the button is pressed, free text entry fields, and
  16141. numeric entry fields.
  16142. The basic push button control should allow configuration of both the button
  16143. text and the annotation text.
  16144. @<Class declarations@>=
  16145. class AnnotationButtonConfWidget : public BasicDeviceConfigurationWidget
  16146. {
  16147. @[Q_OBJECT@]@;
  16148. public:@/
  16149. @[Q_INVOKABLE@]@, AnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  16150. @[private slots@]:@/
  16151. void updateButtonText(const QString &text);
  16152. void updateAnnotationText(const QString &text);
  16153. };
  16154. @ The constructor sets up the controls for editing this data.
  16155. @<AnnotationButtonConfWidget implementation@>=
  16156. AnnotationButtonConfWidget::AnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  16157. : BasicDeviceConfigurationWidget(model, index)
  16158. {
  16159. QFormLayout *layout = new QFormLayout;
  16160. QLineEdit *buttonTextEdit = new QLineEdit;
  16161. QLineEdit *annotationTextEdit = new QLineEdit;
  16162. layout->addRow(tr("Button Text:"), buttonTextEdit);
  16163. layout->addRow(tr("Annotation Text:"), annotationTextEdit);
  16164. @<Get device configuration data for current node@>@;
  16165. for(int i = 0; i < configData.size(); i++)
  16166. {
  16167. node = configData.at(i).toElement();
  16168. if(node.attribute("name") == "buttontext")
  16169. {
  16170. buttonTextEdit->setText(node.attribute("value"));
  16171. }
  16172. else if(node.attribute("name") == "annotationtext")
  16173. {
  16174. annotationTextEdit->setText(node.attribute("value"));
  16175. }
  16176. }
  16177. updateButtonText(buttonTextEdit->text());
  16178. updateAnnotationText(annotationTextEdit->text());
  16179. connect(buttonTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateButtonText(QString)));
  16180. connect(annotationTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateAnnotationText(QString)));
  16181. setLayout(layout);
  16182. }
  16183. @ The slots are implemented trivially.
  16184. @<AnnotationButtonConfWidget implementation@>=
  16185. void AnnotationButtonConfWidget::updateButtonText(const QString &text)
  16186. {
  16187. updateAttribute("buttontext", text);
  16188. }
  16189. void AnnotationButtonConfWidget::updateAnnotationText(const QString &text)
  16190. {
  16191. updateAttribute("annotationtext", text);
  16192. }
  16193. @ The control must be registered.
  16194. @<Register device configuration widgets@>=
  16195. app.registerDeviceConfigurationWidget("annotationbutton", AnnotationButtonConfWidget::staticMetaObject);
  16196. @ Closely related to the previous control is one which provides parameterized
  16197. text. Technically this is not needed as both this and the previous
  16198. configuration control map to the same widget in the logging view and
  16199. parameterized annotation text can be used with either. The reason for
  16200. separating these is to indicate that it should be possible to change the text
  16201. and reset the number without altering the default configuration or requiring a
  16202. reinitialization of the logging view.
  16203. @<Class declarations@>=
  16204. class ReconfigurableAnnotationButtonConfWidget : public BasicDeviceConfigurationWidget@/
  16205. {@/
  16206. @[Q_OBJECT@]@;
  16207. public:@/
  16208. Q_INVOKABLE ReconfigurableAnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  16209. @[private slots@]:@/
  16210. void updateButtonText(const QString &text);
  16211. void updateAnnotationText(const QString &text);
  16212. };
  16213. @ The key difference in implementation is the addition of some documentation on
  16214. how to specify a numeric placeholder in the annotation text.
  16215. @<AnnotationButtonConfWidget implementation@>=
  16216. ReconfigurableAnnotationButtonConfWidget::ReconfigurableAnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  16217. : BasicDeviceConfigurationWidget(model, index)
  16218. {
  16219. QFormLayout *layout = new QFormLayout;
  16220. QLineEdit *buttonTextEdit = new QLineEdit;
  16221. QLineEdit *annotationTextEdit = new QLineEdit;
  16222. layout->addRow(tr("Button Text:"), buttonTextEdit);
  16223. layout->addRow(tr("Annotation Text:"), annotationTextEdit);
  16224. @<Get device configuration data for current node@>@;
  16225. for(int i = 0; i < configData.size(); i++)
  16226. {
  16227. node = configData.at(i).toElement();
  16228. if(node.attribute("name") == "buttontext")
  16229. {
  16230. buttonTextEdit->setText(node.attribute("value"));
  16231. }
  16232. else if(node.attribute("name") == "annotationtext")
  16233. {
  16234. annotationTextEdit->setText(node.attribute("value"));
  16235. }
  16236. }
  16237. updateButtonText(buttonTextEdit->text());
  16238. updateAnnotationText(annotationTextEdit->text());
  16239. connect(buttonTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateButtonText(QString)));
  16240. connect(annotationTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateAnnotationText(QString)));
  16241. QTextEdit *documentation = new QTextEdit;
  16242. 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."));
  16243. documentation->setReadOnly(true);
  16244. layout->addRow("", documentation);
  16245. setLayout(layout);
  16246. }
  16247. void ReconfigurableAnnotationButtonConfWidget::updateButtonText(const QString &text)
  16248. {
  16249. updateAttribute("buttontext", text);
  16250. }
  16251. void ReconfigurableAnnotationButtonConfWidget::updateAnnotationText(const QString &text)
  16252. {
  16253. updateAttribute("annotationtext", text);
  16254. }
  16255. @ The control must be registered as usual.
  16256. @<Register device configuration widgets@>=
  16257. app.registerDeviceConfigurationWidget("reconfigurablebutton", ReconfigurableAnnotationButtonConfWidget::staticMetaObject);
  16258. @ While it is generally better to have all measurements logged automatically,
  16259. many roasters would like to keep track of infrequently altered control
  16260. variables which have not been set up for automated logging. A reading from the
  16261. manometer after a fuel adjustment, for example, is frequently not available by
  16262. automated means. In cases such as this, providing for numeric annotation entry
  16263. may be desired. The |AnnotationSpinBox| provides for this. There are a few
  16264. details that are important in this. First is a label to better indicate to the
  16265. operator what values in this control represent. The range of allowed values and
  16266. the number of decimal places is important. This control also allows the
  16267. specification of text to precede and/or follow the numeric value and this must
  16268. be configurable.
  16269. @<Class declarations@>=
  16270. class NoteSpinConfWidget : public BasicDeviceConfigurationWidget
  16271. {
  16272. @[Q_OBJECT@]@;
  16273. public:@/
  16274. @[Q_INVOKABLE@]@, NoteSpinConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  16275. @[private slots@]:@/
  16276. void updateLabel(const QString &text);
  16277. void updateMinimum(const QString &minimum);
  16278. void updateMaximum(const QString &maximum);
  16279. void updatePrecision(int precision);
  16280. void updatePretext(const QString &text);
  16281. void updatePosttext(const QString &text);
  16282. };
  16283. @ There is nothing new in the implementation of note.
  16284. @<NoteSpinConfWidget implementation@>=
  16285. NoteSpinConfWidget::NoteSpinConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  16286. : BasicDeviceConfigurationWidget(model, index)
  16287. {
  16288. QFormLayout *layout = new QFormLayout;
  16289. QLineEdit *labelEdit = new QLineEdit;
  16290. layout->addRow(tr("Control Label: "), labelEdit);
  16291. QLineEdit *minimumEdit = new QLineEdit;
  16292. layout->addRow(tr("Minimum Value: "), minimumEdit);
  16293. QLineEdit *maximumEdit = new QLineEdit;
  16294. layout->addRow(tr("Maximum Value: "), maximumEdit);
  16295. QSpinBox *precisionEdit = new QSpinBox;
  16296. precisionEdit->setMinimum(0);
  16297. precisionEdit->setMaximum(9);
  16298. layout->addRow(tr("Precision"), precisionEdit);
  16299. QLineEdit *pretext = new QLineEdit;
  16300. layout->addRow(tr("Prefix text"), pretext);
  16301. QLineEdit *posttext = new QLineEdit;
  16302. layout->addRow(tr("Suffix text"), posttext);
  16303. @<Get device configuration data for current node@>@;
  16304. for(int i = 0; i < configData.size(); i++)
  16305. {
  16306. node = configData.at(i).toElement();
  16307. if(node.attribute("name") == "label")
  16308. {
  16309. labelEdit->setText(node.attribute("value"));
  16310. }
  16311. else if(node.attribute("name") == "minimum")
  16312. {
  16313. minimumEdit->setText(node.attribute("value"));
  16314. }
  16315. else if(node.attribute("name") == "maximum")
  16316. {
  16317. maximumEdit->setText(node.attribute("value"));
  16318. }
  16319. else if(node.attribute("name") == "precision")
  16320. {
  16321. precisionEdit->setValue(node.attribute("value").toInt());
  16322. }
  16323. else if(node.attribute("name") == "pretext")
  16324. {
  16325. pretext->setText(node.attribute("value"));
  16326. }
  16327. else if(node.attribute("name") == "posttext")
  16328. {
  16329. posttext->setText(node.attribute("value"));
  16330. }
  16331. }
  16332. updateLabel(labelEdit->text());
  16333. updateMinimum(minimumEdit->text());
  16334. updateMaximum(maximumEdit->text());
  16335. updatePrecision(precisionEdit->value());
  16336. updatePretext(pretext->text());
  16337. updatePosttext(posttext->text());
  16338. connect(labelEdit, SIGNAL(textEdited(QString)), this, SLOT(updateLabel(QString)));
  16339. connect(minimumEdit, SIGNAL(textEdited(QString)), this, SLOT(updateMinimum(QString)));
  16340. connect(maximumEdit, SIGNAL(textEdited(QString)), this, SLOT(updateMaximum(QString)));
  16341. connect(precisionEdit, SIGNAL(valueChanged(int)), this, SLOT(updatePrecision(int)));
  16342. connect(pretext, SIGNAL(textEdited(QString)), this, SLOT(updatePretext(QString)));
  16343. connect(posttext, SIGNAL(textEdited(QString)), this, SLOT(updatePosttext(QString)));
  16344. setLayout(layout);
  16345. }
  16346. void NoteSpinConfWidget::updateLabel(const QString &text)
  16347. {
  16348. updateAttribute("label", text);
  16349. }
  16350. void NoteSpinConfWidget::updateMinimum(const QString &minimum)
  16351. {
  16352. updateAttribute("minimum", minimum);
  16353. }
  16354. void NoteSpinConfWidget::updateMaximum(const QString &maximum)
  16355. {
  16356. updateAttribute("maximum", maximum);
  16357. }
  16358. void NoteSpinConfWidget::updatePrecision(int precision)
  16359. {
  16360. updateAttribute("precision", QString("%1").arg(precision));
  16361. }
  16362. void NoteSpinConfWidget::updatePretext(const QString &text)
  16363. {
  16364. updateAttribute("pretext", text);
  16365. }
  16366. void NoteSpinConfWidget::updatePosttext(const QString &text)
  16367. {
  16368. updateAttribute("posttext", text);
  16369. }
  16370. @ Configuration widget registration is as usual.
  16371. @<Register device configuration widgets@>=
  16372. app.registerDeviceConfigurationWidget("annotationspinbox", NoteSpinConfWidget::staticMetaObject);
  16373. @i freeannotation.w
  16374. @i settings.w
  16375. @** Communicating with a Device through Modbus RTU.
  16376. \noindent The classes described here need to be further generalized to support
  16377. communications with multiple devices on the same port. The interface is based
  16378. on the |DAQ| class but extended to support additional functionality.
  16379. @<Class declarations@>=
  16380. class ModbusRTUDevice : public QObject
  16381. {
  16382. @[Q_OBJECT@]@;
  16383. public:@/
  16384. ModbusRTUDevice(DeviceTreeModel *model, const QModelIndex &index);
  16385. ~ModbusRTUDevice();
  16386. void queueMessage(QByteArray request, QObject *object, const char *callback);
  16387. @[Q_INVOKABLE@,@, double@]@, SVLower();@t\2\2@>@/
  16388. @[Q_INVOKABLE@,@, double@]@, SVUpper();@t\2\2@>@/
  16389. @[Q_INVOKABLE@,@, int@]@, decimals();@t\2\2@>@/
  16390. QList<Channel*> channels;@/
  16391. @[public slots@]:@/
  16392. void outputSV(double sv);@/
  16393. signals:@/
  16394. void SVLowerChanged(double);
  16395. void SVUpperChanged(double);
  16396. void SVDecimalChanged(int);
  16397. void queueEmpty();@/
  16398. @[private slots@]:@/
  16399. void dataAvailable();
  16400. void sendNextMessage();
  16401. void decimalResponse(QByteArray response);
  16402. void unitResponse(QByteArray response);
  16403. void svlResponse(QByteArray response);
  16404. void svuResponse(QByteArray response);
  16405. void requestMeasurement();
  16406. void mResponse(QByteArray response);
  16407. void ignore(QByteArray response);
  16408. void timeout();@/
  16409. private:@/
  16410. QextSerialPort *port;
  16411. QByteArray responseBuffer;
  16412. QList<QByteArray> messageQueue;
  16413. QList<QObject *> retObjQueue;
  16414. QList<char *> callbackQueue;
  16415. quint16 calculateCRC(QByteArray data);
  16416. QTimer *messageDelayTimer;
  16417. QTimer *commTimeout;
  16418. int delayTime;
  16419. char station;
  16420. int decimalPosition;
  16421. int valueF;
  16422. int valueC;
  16423. bool unitIsF;
  16424. double outputSVLower;
  16425. double outputSVUpper;
  16426. QByteArray outputSVStub;
  16427. QByteArray pvStub;
  16428. QByteArray svStub;
  16429. QByteArray mStub;
  16430. quint16 pvaddress;
  16431. quint16 svaddress;
  16432. bool svenabled;
  16433. bool readingsv;
  16434. double savedpv;
  16435. bool waiting;
  16436. };
  16437. @ The constructor reads its configuration from the configuration sub-tree of the
  16438. port node. This was adapted from a prototype implementation which used
  16439. |QSettings| to store this data. Note that this will only process the first
  16440. device specified on the port, the first process value on that device, and the
  16441. first set value on that device. A much more versatile architecture has been
  16442. planned for a future release which allows multiple devices per bus and
  16443. arbitrarily many monitored addresses per device. Communications are initiated
  16444. immediately upon construction.
  16445. @<ModbusRTUDevice implementation@>=
  16446. ModbusRTUDevice::ModbusRTUDevice(DeviceTreeModel *model,@| const QModelIndex &index)
  16447. : QObject(NULL), messageDelayTimer(new QTimer), commTimeout(new QTimer), unitIsF(@[true@]), readingsv(@[false@]),
  16448. waiting(@[false@])@/
  16449. {@/
  16450. QDomElement portReferenceElement = model->referenceElement(model->data(index,
  16451. Qt::UserRole).toString());
  16452. QDomNodeList portConfigData = portReferenceElement.elementsByTagName("attribute");
  16453. QDomElement node;
  16454. QVariantMap attributes;
  16455. for(int i = 0; i < portConfigData.size(); i++)
  16456. {
  16457. node = portConfigData.at(i).toElement();
  16458. attributes.insert(node.attribute("name"), node.attribute("value"));
  16459. }
  16460. port = new QextSerialPort(attributes.value("port").toString(),
  16461. QextSerialPort::EventDriven);
  16462. int baudRate = attributes.value("baud").toInt();
  16463. port->setBaudRate((BaudRateType)baudRate);
  16464. double temp = ((double)(1) / (double)(baudRate)) * 48;
  16465. delayTime = (int)(temp * 3000);
  16466. messageDelayTimer->setSingleShot(true);
  16467. commTimeout->setSingleShot(true);
  16468. connect(messageDelayTimer, SIGNAL(timeout()), this, SLOT(sendNextMessage()));
  16469. connect(commTimeout, SIGNAL(timeout()), this, SLOT(timeout()));
  16470. port->setDataBits(DATA_8);
  16471. port->setParity((ParityType)attributes.value("parity").toInt());
  16472. port->setStopBits((StopBitsType)attributes.value("stop").toInt());
  16473. port->setFlowControl((FlowType)attributes.value("flow").toInt());
  16474. connect(port, SIGNAL(readyRead()), this, SLOT(dataAvailable()));
  16475. port->open(QIODevice::ReadWrite);
  16476. station = (char)attributes.value("station").toInt();
  16477. if(attributes.value("decimalQuery") == "true")
  16478. {
  16479. decimalPosition = 0;
  16480. QByteArray message;
  16481. message.append(station);
  16482. message.append((char)0x03);
  16483. quint16 address = (quint16)attributes.value("decimalAddress").toInt();
  16484. char *addressBytes = (char*)&address;
  16485. message.append(addressBytes[1]);
  16486. message.append(addressBytes[0]);
  16487. message.append((char)0x00);
  16488. message.append((char)0x01);
  16489. queueMessage(message, this, "decimalResponse(QByteArray)");
  16490. }
  16491. else
  16492. {
  16493. decimalPosition = attributes.value("decimalPosition").toInt();
  16494. }
  16495. valueF = attributes.value("valueF").toInt();
  16496. valueC = attributes.value("valueC").toInt();
  16497. if(attributes.value("unitQuery") == "true")
  16498. {
  16499. QByteArray message;
  16500. message.append(station);
  16501. message.append((char)0x03);
  16502. quint16 address = (quint16)attributes.value("unitAddress").toInt();
  16503. char *addressBytes = (char*)&address;
  16504. message.append(addressBytes[1]);
  16505. message.append(addressBytes[0]);
  16506. message.append((char)0x00);
  16507. message.append((char)0x01);
  16508. queueMessage(message, this, "unitResponse(QByteArray)");
  16509. }
  16510. else
  16511. {
  16512. if(attributes.value("fixedUnit") == "Celsius")
  16513. {
  16514. unitIsF = @[false@];
  16515. }
  16516. }
  16517. if(attributes.value("sVWritable") == "true")
  16518. {
  16519. if(attributes.value("deviceLimit") == "true")
  16520. {
  16521. QByteArray lmessage;
  16522. lmessage.append(station);
  16523. lmessage.append((char)0x03);
  16524. quint16 laddress = (quint16)attributes.value("sVLowerAddr").toInt();
  16525. char *addressBytes = (char*)&laddress;
  16526. lmessage.append(addressBytes[1]);
  16527. lmessage.append(addressBytes[0]);
  16528. lmessage.append((char)0x00);
  16529. lmessage.append((char)0x01);
  16530. queueMessage(lmessage, this, "svlResponse(QByteArray)");
  16531. QByteArray umessage;
  16532. umessage.append(station);
  16533. umessage.append((char)0x03);
  16534. quint16 uaddress = (quint16)attributes.value("sVUpperAddr").toInt();
  16535. addressBytes = (char*)&uaddress;
  16536. umessage.append(addressBytes[1]);
  16537. umessage.append(addressBytes[0]);
  16538. umessage.append((char)0x00);
  16539. umessage.append((char)0x01);
  16540. queueMessage(umessage, this, "svuResponse(QByteArray)");
  16541. }
  16542. else
  16543. {
  16544. outputSVLower = attributes.value("sVLower").toDouble();
  16545. outputSVUpper = attributes.value("sVUpper").toDouble();
  16546. }
  16547. outputSVStub.append(station);
  16548. outputSVStub.append((char)0x06);
  16549. quint16 address = (quint16)attributes.value("sVOutputAddr").toInt();
  16550. char *addressBytes = (char*)&address;
  16551. outputSVStub.append(addressBytes[1]);
  16552. outputSVStub.append(addressBytes[0]);
  16553. }
  16554. Channel *pv = new Channel;
  16555. channels.append(pv);
  16556. pvStub.append(station);
  16557. pvStub.append((char)0x04);
  16558. pvaddress = (quint16)attributes.value("pVAddress").toInt();
  16559. char *pvac = (char*)&pvaddress;
  16560. pvStub.append(pvac[1]);
  16561. pvStub.append(pvac[0]);
  16562. pvStub.append((char)0x00);
  16563. pvStub.append((char)0x01);
  16564. svenabled = attributes.value("sVEnabled").toBool();
  16565. if(svenabled)
  16566. {
  16567. Channel *sv = new Channel;
  16568. channels.append(sv);
  16569. svStub.append(station);
  16570. svStub.append((char)0x04);
  16571. svaddress = (quint16)attributes.value("sVReadAddress").toInt();
  16572. char *svac = (char*)&svaddress;
  16573. svStub.append(svac[1]);
  16574. svStub.append(svac[0]);
  16575. svStub.append((char)0x00);
  16576. svStub.append((char)0x01);
  16577. if(svaddress - pvaddress == 1)
  16578. {
  16579. mStub.append(station);
  16580. mStub.append((char)0x04);
  16581. mStub.append(pvac[1]);
  16582. mStub.append(pvac[0]);
  16583. mStub.append((char)0x00);
  16584. mStub.append((char)0x02);
  16585. }
  16586. }
  16587. connect(this, SIGNAL(queueEmpty()), this, SLOT(requestMeasurement()));
  16588. requestMeasurement();
  16589. }
  16590. double ModbusRTUDevice::SVLower()
  16591. {
  16592. return outputSVLower;
  16593. }
  16594. double ModbusRTUDevice::SVUpper()
  16595. {
  16596. return outputSVUpper;
  16597. }
  16598. int ModbusRTUDevice::decimals()
  16599. {
  16600. return decimalPosition;
  16601. }
  16602. void ModbusRTUDevice::decimalResponse(QByteArray response)
  16603. {
  16604. quint16 temp;
  16605. char *tchar = (char*)&temp;
  16606. tchar[1] = response.at(3);
  16607. tchar[0] = response.at(4);
  16608. decimalPosition = temp;
  16609. emit SVDecimalChanged(decimalPosition);
  16610. }
  16611. void ModbusRTUDevice::unitResponse(QByteArray response)
  16612. {
  16613. quint16 temp;
  16614. char *tchar = (char*)&temp;
  16615. tchar[1] = response.at(3);
  16616. tchar[0] = response.at(4);
  16617. int value = temp;
  16618. if(value == valueF)
  16619. {
  16620. unitIsF = @[true@];
  16621. }
  16622. else
  16623. {
  16624. unitIsF = @[false@];
  16625. }
  16626. }
  16627. void ModbusRTUDevice::svlResponse(QByteArray response)
  16628. {
  16629. quint16 temp;
  16630. char *tchar = (char*)&temp;
  16631. tchar[1] = response.at(3);
  16632. tchar[0] = response.at(4);
  16633. outputSVLower = (double)temp;
  16634. for(int i = 0; i < decimalPosition; i++)
  16635. {
  16636. outputSVLower /= 10;
  16637. }
  16638. emit SVLowerChanged(outputSVLower);
  16639. }
  16640. void ModbusRTUDevice::svuResponse(QByteArray response)
  16641. {
  16642. quint16 temp;
  16643. char *tchar = (char*)&temp;
  16644. tchar[1] = response.at(3);
  16645. tchar[0] = response.at(4);
  16646. outputSVUpper = (double)temp;
  16647. for(int i = 0; i < decimalPosition; i++)
  16648. {
  16649. outputSVUpper /= 10;
  16650. }
  16651. emit SVUpperChanged(outputSVUpper);
  16652. }
  16653. void ModbusRTUDevice::requestMeasurement()
  16654. {
  16655. if(mStub.length() > 0)
  16656. {
  16657. queueMessage(mStub, this, "mResponse(QByteArray)");
  16658. }
  16659. else
  16660. {
  16661. queueMessage(pvStub, this, "mResponse(QByteArray)");
  16662. if(svenabled)
  16663. {
  16664. queueMessage(svStub, this, "mResponse(QByteArray)");
  16665. }
  16666. }
  16667. }
  16668. void ModbusRTUDevice::mResponse(QByteArray response)
  16669. {
  16670. QTime time = QTime::currentTime();
  16671. if(response.at(2) == 0x04)
  16672. {
  16673. @<Process PV and SV@>@;
  16674. }
  16675. else
  16676. {
  16677. @<Process PV or SV@>@;
  16678. }
  16679. }
  16680. @ There are two ways that we might request measurement data. All of the
  16681. devices I'@q'@>ve seen documented provide function 0x4 addresses for PV and SV
  16682. such that SV can be obtained from the address immediately after the address
  16683. from which we obtain PV. In this case we request both values at the same time.
  16684. @<Process PV and SV@>=
  16685. quint16 pv;
  16686. quint16 sv;
  16687. char *pvBytes = (char*)&pv;
  16688. char *svBytes = (char*)&sv;
  16689. pvBytes[1] = response.at(3);
  16690. pvBytes[0] = response.at(4);
  16691. svBytes[1] = response.at(5);
  16692. svBytes[0] = response.at(6);
  16693. double pvOut = (double)pv;
  16694. double svOut = (double)sv;
  16695. for(int i = 0; i < decimalPosition; i++)
  16696. {
  16697. pvOut /= 10;
  16698. svOut /= 10;
  16699. }
  16700. if(!unitIsF)
  16701. {
  16702. pvOut = pvOut * 9 / 5 + 32;
  16703. svOut = svOut * 9 / 5 + 32;
  16704. }
  16705. Measurement pvm(pvOut, time, Units::Fahrenheit);
  16706. Measurement svm(svOut, time, Units::Fahrenheit);
  16707. channels.at(0)->input(pvm);
  16708. channels.at(1)->input(svm);
  16709. @ When not measuring PV and SV at the same time, there are two possibilities.
  16710. One possibility is that SV is not enabled and we will only be reading from PV.
  16711. The other possibility is that we are alternating between reading PV and SV.
  16712. @<Process PV or SV@>=
  16713. quint16 value;
  16714. char *valueBytes = (char*)&value;
  16715. valueBytes[1] = response.at(3);
  16716. valueBytes[0] = response.at(4);
  16717. double valueOut = (double)value;
  16718. for(int i = 0; i < decimalPosition; i++)
  16719. {
  16720. valueOut /= 10;
  16721. }
  16722. if(!unitIsF)
  16723. {
  16724. valueOut = valueOut * 9 / 5 + 32;
  16725. }
  16726. if(!svenabled)
  16727. {
  16728. Measurement vm(valueOut, time, Units::Fahrenheit);
  16729. channels.at(0)->input(vm);
  16730. }
  16731. else
  16732. {
  16733. if(readingsv)
  16734. {
  16735. Measurement pvm(savedpv, time, Units::Fahrenheit);
  16736. Measurement svm(valueOut, time, Units::Fahrenheit);
  16737. channels.at(0)->input(pvm);
  16738. channels.at(1)->input(svm);
  16739. readingsv = false;
  16740. }
  16741. else
  16742. {
  16743. savedpv = valueOut;
  16744. readingsv = true;
  16745. }
  16746. }
  16747. @ The destructor should close the port.
  16748. @<ModbusRTUDevice implementation@>=
  16749. ModbusRTUDevice::~ModbusRTUDevice()
  16750. {
  16751. commTimeout->stop();
  16752. messageDelayTimer->stop();
  16753. port->close();
  16754. }
  16755. @ When data is available it should be read into a buffer. The start of the
  16756. buffer should always be the start of a response and there should never be
  16757. more than one response in the buffer at a time. It is, however, likely that
  16758. this buffer will have incomplete data. This means that we must determine when
  16759. the full response is available before passing the complete response along to
  16760. the appropriate method. If the response has not been received in full, nothing
  16761. is done. We'@q'@>ll be notified of more data shortly.
  16762. When the message we see the response for was queued, a callback was also
  16763. registered to handle the response. Once we have the complete message, we pass
  16764. the response along to the callback that was registered for that message,
  16765. remove the message and callback information from the message queue, and start
  16766. a timer which will trigger sending the next message after a safe amount of
  16767. time has passed.
  16768. If a response is received with an invalid CRC, we do not pass that message
  16769. out. Instead, the message handling queues are kept as they are and the previous
  16770. command will be sent again once the message delay timer is finished.
  16771. @<ModbusRTUDevice implementation@>=
  16772. void ModbusRTUDevice::dataAvailable()
  16773. {
  16774. if(messageDelayTimer->isActive())
  16775. {
  16776. messageDelayTimer->stop();
  16777. }
  16778. responseBuffer.append(port->readAll());
  16779. @<Check Modbus RTU message size@>@;
  16780. commTimeout->stop();
  16781. if(calculateCRC(responseBuffer) == 0)
  16782. {
  16783. QObject *object = retObjQueue.at(0);
  16784. char *method = callbackQueue.at(0);
  16785. QMetaMethod metamethod = @| object->metaObject()->
  16786. method(object->metaObject()->
  16787. indexOfMethod(@|QMetaObject::normalizedSignature(method)));
  16788. metamethod.invoke(object, Qt::QueuedConnection,
  16789. Q_ARG(QByteArray, responseBuffer));
  16790. messageQueue.removeAt(0);
  16791. retObjQueue.removeAt(0);
  16792. callbackQueue.removeAt(0);
  16793. }
  16794. else
  16795. {
  16796. qDebug() << "CRC failed";
  16797. }
  16798. messageDelayTimer->start(delayTime);
  16799. waiting = @[false@];
  16800. responseBuffer.clear();
  16801. }
  16802. @ In Modbus RTU, a response message starts with one byte identifying the device
  16803. the message was sent from, one byte indicating the function, a variable number
  16804. of bytes with the response data, and two bytes used to verify that the response
  16805. was correctly received. In the event of a normal response, messages will be at
  16806. least six bytes long, but in the event of an error it is possible for a message
  16807. to be five bytes long.
  16808. Messages with a function number of 0x01 or 0x02 will be 6 bytes in length.
  16809. Messages with a function number of 0x03 or 0x04 will be at least 7 bytes in
  16810. length with the total length determined by the sum of 5 and the value in the
  16811. fifth byte. Messages with a function number of 0x05, 0x06, or 0x10 will be 8
  16812. bytes in length. Messages with a function number greater than 0x80 will be five
  16813. bytes in length.
  16814. @<Check Modbus RTU message size@>=
  16815. if(responseBuffer.size() < 5)
  16816. {
  16817. return;
  16818. }
  16819. switch(responseBuffer.at(1))
  16820. {
  16821. case 0x01:
  16822. case 0x02:
  16823. if(responseBuffer.size() < 6)
  16824. {
  16825. return;
  16826. }
  16827. responseBuffer = responseBuffer.left(6);
  16828. break;
  16829. case 0x03:
  16830. case 0x04:
  16831. if(responseBuffer.size() < 5 + responseBuffer.at(2))
  16832. {
  16833. return;
  16834. }
  16835. responseBuffer = responseBuffer.left(5 + responseBuffer.at(2));
  16836. break;
  16837. case 0x05:
  16838. case 0x06:
  16839. case 0x10:
  16840. if(responseBuffer.size() < 8)
  16841. {
  16842. return;
  16843. }
  16844. responseBuffer = responseBuffer.left(8);
  16845. break;
  16846. }
  16847. @ When sending and receiving messages, it is necessary to calculate a 16 bit
  16848. cyclic redundancy check code. The algorithm used to calculate this is specified
  16849. by the Modbus RTU protocol documentation. When sending a message, |data| should
  16850. be the message to send except for the CRC bytes which will be appended once
  16851. this method calculates them. When receiving a message, passing the complete
  16852. message back through this method should result in a return value of |0|. Any
  16853. other value indicates an error.
  16854. @<ModbusRTUDevice implementation@>=
  16855. quint16 ModbusRTUDevice::calculateCRC(QByteArray data)
  16856. {
  16857. quint16 retval = 0xFFFF;
  16858. int i = 0;
  16859. while(i < data.size())
  16860. {
  16861. retval ^= 0x00FF & (quint16)data.at(i);
  16862. for(int j = 0; j < 8; j++)
  16863. {
  16864. if(retval & 1)
  16865. {
  16866. retval = (retval >> 1) ^ 0xA001;
  16867. }
  16868. else
  16869. {
  16870. retval >>= 1;
  16871. }
  16872. }
  16873. i++;
  16874. }
  16875. return retval;
  16876. }
  16877. @ When preparing an instance of ModbusRTUDevice, several messages may need to
  16878. be sent to the device in order to determine important details such as how
  16879. measurement data should be interpreted. During normal operation, messages
  16880. might be sent interactively between regular messages to acquire data. When
  16881. queueing a message, we also specify an object and method the response should be
  16882. sent to.
  16883. @<ModbusRTUDevice implementation@>=
  16884. void ModbusRTUDevice::queueMessage(QByteArray request, QObject *object,
  16885. const char *callback)
  16886. {
  16887. messageQueue.append(request);
  16888. retObjQueue.append(object);
  16889. callbackQueue.append(const_cast<char*>(callback));
  16890. if(messageQueue.size() == 1 && !(messageDelayTimer->isActive()))
  16891. {
  16892. sendNextMessage();
  16893. }
  16894. }
  16895. void ModbusRTUDevice::sendNextMessage()
  16896. {
  16897. if(messageQueue.size() > 0 && !waiting)
  16898. {
  16899. QByteArray message = messageQueue.at(0);
  16900. quint16 crc = calculateCRC(message);
  16901. char *check = (char*)&crc;
  16902. message.append(check[0]);
  16903. message.append(check[1]);
  16904. port->write(message);
  16905. commTimeout->start(2000);
  16906. messageDelayTimer->start(delayTime);
  16907. waiting = @[true@];
  16908. }
  16909. else
  16910. {
  16911. emit queueEmpty();
  16912. }
  16913. }
  16914. void ModbusRTUDevice::outputSV(double value)
  16915. {
  16916. for(int i = 0; i < decimalPosition; i++)
  16917. {
  16918. value *= 10;
  16919. }
  16920. quint16 outval = (quint16)value;
  16921. QByteArray message(outputSVStub);
  16922. char *valBytes = (char*)&outval;
  16923. message.append(valBytes[1]);
  16924. message.append(valBytes[0]);
  16925. queueMessage(message, this, "ignore(QByteArray)");
  16926. }
  16927. @ We don'@q'@>t care about the response when sending a new SV.
  16928. @<ModbusRTUDevice implementation@>=
  16929. void ModbusRTUDevice::ignore(QByteArray)
  16930. {
  16931. return;
  16932. }
  16933. @ Sometimes a communications failure will occur in which a response to a
  16934. command is never received. To reset communications we set a timer whenever a
  16935. command is sent and stop that once a full response is received. If the timer
  16936. times out, we should clear the response buffer and attempt to re-establish
  16937. communications. Currently this timeout is hard coded at 2 seconds, however
  16938. this should be configurable and smaller values may well be acceptable.
  16939. @<ModbusRTUDevice implementation@>=
  16940. void ModbusRTUDevice::timeout()
  16941. {
  16942. qDebug() << "Communications timeout.";
  16943. responseBuffer.clear();
  16944. waiting = false;
  16945. messageDelayTimer->start();
  16946. }
  16947. @ This class must be exposed to the host environment.
  16948. @<Function prototypes for scripting@>=
  16949. QScriptValue constructModbusRTUDevice(QScriptContext *context, QScriptEngine *engine);
  16950. QScriptValue ModbusRTUDevice_pVChannel(QScriptContext *context, QScriptEngine *engine);
  16951. QScriptValue ModbusRTUDevice_sVChannel(QScriptContext *context, QScriptEngine *engine);
  16952. void setModbusRTUDeviceProperties(QScriptValue value, QScriptEngine *engine);
  16953. @ The host environment is informed of the constructor.
  16954. @<Set up the scripting engine@>=
  16955. constructor = engine->newFunction(constructModbusRTUDevice);
  16956. value = engine->newQMetaObject(&ModbusRTUDevice::staticMetaObject, constructor);
  16957. engine->globalObject().setProperty("ModbusRTUDevice", value);
  16958. @ The constructor takes the configuration model and the index to the device of
  16959. interest as arguments rather than provide a large number of property setters to
  16960. handle initialization.
  16961. @<Functions for scripting@>=
  16962. QScriptValue constructModbusRTUDevice(QScriptContext *context, QScriptEngine *engine)
  16963. {
  16964. QScriptValue object;
  16965. if(context->argumentCount() == 2)
  16966. {
  16967. object = engine->newQObject(new ModbusRTUDevice(argument<DeviceTreeModel *>(0, context),
  16968. argument<QModelIndex>(1, context)),
  16969. QScriptEngine::ScriptOwnership);
  16970. setModbusRTUDeviceProperties(object, engine);
  16971. }
  16972. else
  16973. {
  16974. context->throwError("Incorrect number of arguments passed to "@|
  16975. "ModbusRTUDevice constructor. This takes the configuration model "@|
  16976. "and an index.");
  16977. }
  16978. return object;
  16979. }
  16980. @ The host environment needs a way to gain access to the channel objects.
  16981. @<Functions for scripting@>=
  16982. QScriptValue ModbusRTUDevice_pVChannel(QScriptContext *context, QScriptEngine *engine)
  16983. {
  16984. ModbusRTUDevice *self = getself<ModbusRTUDevice *>(context);
  16985. QScriptValue object;
  16986. if(self)
  16987. {
  16988. if(self->channels.size() > 0)
  16989. {
  16990. object = engine->newQObject(self->channels.at(0));
  16991. setChannelProperties(object, engine);
  16992. }
  16993. }
  16994. return object;
  16995. }
  16996. QScriptValue ModbusRTUDevice_sVChannel(QScriptContext *context, QScriptEngine *engine)
  16997. {
  16998. ModbusRTUDevice *self = getself<ModbusRTUDevice *>(context);
  16999. QScriptValue object;
  17000. if(self)
  17001. {
  17002. if(self->channels.size() > 1)
  17003. {
  17004. object = engine->newQObject(self->channels.at(1));
  17005. setChannelProperties(object, engine);
  17006. }
  17007. }
  17008. return object;
  17009. }
  17010. @ These methods are set as properties when the object is created.
  17011. @<Functions for scripting@>=
  17012. void setModbusRTUDeviceProperties(QScriptValue value, QScriptEngine *engine)
  17013. {
  17014. setQObjectProperties(value, engine);
  17015. value.setProperty("pVChannel", engine->newFunction(ModbusRTUDevice_pVChannel));
  17016. value.setProperty("sVChannel", engine->newFunction(ModbusRTUDevice_sVChannel));
  17017. }
  17018. @* Modbus RTU device configuration widget.
  17019. \noindent This class was minimally adapted from a prototype implementation to
  17020. use the new configuration system introduced in \pn{} 1.4.
  17021. With all of the custom widgets for specifying a device configuration in place,
  17022. we can proceed to combine these in a form. As all of the options might use more
  17023. screen space than is available we make this scrollable. Some reorganization of
  17024. this will be done prior to release to enable the use of multiple devices on the
  17025. port which may obviate the need for this, but as there are those who prefer to
  17026. have a small screen it may be better to leave the scroll area in place even
  17027. after such a change.
  17028. @<Class declarations@>=
  17029. class ModbusConfigurator : public BasicDeviceConfigurationWidget
  17030. {
  17031. @[Q_OBJECT@]@;
  17032. public:@/
  17033. Q_INVOKABLE@,@, ModbusConfigurator(DeviceTreeModel *model, const QModelIndex &index);@/
  17034. @[private slots@]:@/
  17035. void updatePort(const QString &newPort);
  17036. void updateBaudRate(const QString &newRate);
  17037. void updateParity(const QString &newParity);
  17038. void updateFlowControl(const QString &newFlow);
  17039. void updateStopBits(const QString &newStopBits);
  17040. void updateStation(int station);
  17041. void updateFixedDecimal(bool fixed);
  17042. void updateDecimalAddress(int address);
  17043. void updateDecimalPosition(int position);
  17044. void updateFixedUnit(bool fixed);
  17045. void updateUnitAddress(int address);
  17046. void updateValueForF(int value);
  17047. void updateValueForC(int value);
  17048. void updateUnit(const QString &newUnit);
  17049. void updatePVAddress(int address);
  17050. void updateSVEnabled(bool enabled);
  17051. void updateSVReadAddress(int address);
  17052. void updateDeviceLimit(bool query);
  17053. void updateSVLowerAddress(int address);
  17054. void updateSVUpperAddress(int address);
  17055. void updateSVLower(double value);
  17056. void updateSVUpper(double value);
  17057. void updateSVWritable(bool canWriteSV);
  17058. void updateSVWriteAddress(int address);
  17059. void updatePVColumnName(const QString &name);
  17060. void updateSVColumnName(const QString &name);
  17061. void updatePVHidden(bool hidden);
  17062. void updateSVHidden(bool hidden);@/
  17063. private:@/
  17064. PortSelector *port;
  17065. BaudSelector *baud;
  17066. ParitySelector *parity;
  17067. FlowSelector *flow;
  17068. StopSelector *stop;
  17069. QSpinBox *station;
  17070. QCheckBox *decimalQuery;
  17071. ShortHexSpinBox *decimalAddress;
  17072. QSpinBox *decimalPosition;
  17073. QCheckBox *unitQuery;
  17074. ShortHexSpinBox *unitAddress;
  17075. QSpinBox *valueF;
  17076. QSpinBox *valueC;
  17077. QComboBox *fixedUnit;
  17078. ShortHexSpinBox *pVAddress;
  17079. QCheckBox *sVEnabled;
  17080. ShortHexSpinBox *sVReadAddress;
  17081. QCheckBox *deviceLimit;
  17082. ShortHexSpinBox *sVLowerAddr;
  17083. ShortHexSpinBox *sVUpperAddr;
  17084. QDoubleSpinBox *sVLower;
  17085. QDoubleSpinBox *sVUpper;
  17086. QCheckBox *sVWritable;
  17087. ShortHexSpinBox *sVOutputAddr;
  17088. QLineEdit *pVColumnName;
  17089. QLineEdit *sVColumnName;
  17090. };
  17091. @ Implementation.
  17092. @<ModbusConfigurator implementation@>=
  17093. ModbusConfigurator::ModbusConfigurator(DeviceTreeModel *model, const QModelIndex &index)
  17094. : BasicDeviceConfigurationWidget(model, index),
  17095. port(new PortSelector), baud(new BaudSelector), parity(new ParitySelector),
  17096. flow(new FlowSelector), stop(new StopSelector), station(new QSpinBox),
  17097. decimalQuery(new QCheckBox(tr("Enable"))),
  17098. decimalAddress(new ShortHexSpinBox), decimalPosition(new QSpinBox),
  17099. unitQuery(new QCheckBox(tr("Enable"))),
  17100. unitAddress(new ShortHexSpinBox), valueF(new QSpinBox),
  17101. valueC(new QSpinBox), fixedUnit(new QComboBox),
  17102. pVAddress(new ShortHexSpinBox),
  17103. sVEnabled(new QCheckBox(tr("Enable"))),
  17104. sVReadAddress(new ShortHexSpinBox),
  17105. deviceLimit(new QCheckBox(tr("Enable"))),
  17106. sVLowerAddr(new ShortHexSpinBox), sVUpperAddr(new ShortHexSpinBox),
  17107. sVLower(new QDoubleSpinBox), sVUpper(new QDoubleSpinBox),
  17108. sVWritable(new QCheckBox(tr("Enable"))),
  17109. sVOutputAddr(new ShortHexSpinBox),
  17110. pVColumnName(new QLineEdit), sVColumnName(new QLineEdit)
  17111. {
  17112. QHBoxLayout *layout = new QHBoxLayout;
  17113. QWidget *form = new QWidget;
  17114. QHBoxLayout *masterLayout = new QHBoxLayout;
  17115. QVBoxLayout *portAndDeviceLayout = new QVBoxLayout;
  17116. QVBoxLayout *seriesLayout = new QVBoxLayout;
  17117. QFormLayout *serialSection = new QFormLayout;
  17118. serialSection->addRow(QString(tr("Port:")), port);
  17119. serialSection->addRow(QString(tr("Baud rate:")), baud);
  17120. serialSection->addRow(QString(tr("Parity:")), parity);
  17121. serialSection->addRow(QString(tr("Flow control:")), flow);
  17122. serialSection->addRow(QString(tr("Stop bits:")), stop);
  17123. QGroupBox *serialSectionBox = new QGroupBox(tr("Serial Port Configuration"));
  17124. serialSectionBox->setLayout(serialSection);
  17125. portAndDeviceLayout->addWidget(serialSectionBox);
  17126. QFormLayout *deviceSection = new QFormLayout;
  17127. station->setMinimum(1);
  17128. station->setMaximum(255);
  17129. decimalPosition->setMinimum(0);
  17130. decimalPosition->setMaximum(9);
  17131. valueF->setMinimum(0);
  17132. valueF->setMaximum(0xFFFF);
  17133. valueC->setMinimum(0);
  17134. valueC->setMaximum(0xFFFF);
  17135. fixedUnit->addItem(tr("Fahrenheit"), QVariant(QString("F")));
  17136. fixedUnit->addItem(tr("Celsius"), QVariant(QString("C")));
  17137. deviceSection->addRow(tr("Station:"), station);
  17138. deviceSection->addRow(tr("Decimal position from device:"), decimalQuery);
  17139. deviceSection->addRow(tr("Decimal position relative address:"), decimalAddress);
  17140. deviceSection->addRow(tr("Fixed decimal position:"), decimalPosition);
  17141. deviceSection->addRow(tr("Measurement unit from device:"), unitQuery);
  17142. deviceSection->addRow(tr("Current unit relative address:"), unitAddress);
  17143. deviceSection->addRow(tr("Value for Fahrenheit:"), valueF);
  17144. deviceSection->addRow(tr("Value for Celsius:"), valueC);
  17145. deviceSection->addRow(tr("Fixed unit:"), fixedUnit);
  17146. QGroupBox *deviceSectionBox = new QGroupBox(tr("Device Configuration"));
  17147. deviceSectionBox->setLayout(deviceSection);
  17148. portAndDeviceLayout->addWidget(deviceSectionBox);
  17149. QFormLayout *pVSection = new QFormLayout;
  17150. pVSection->addRow(tr("Value relative address:"), pVAddress);
  17151. pVSection->addRow(tr("PV column name:"), pVColumnName);
  17152. QCheckBox *pVHideBox = new QCheckBox(tr("Hide this channel"));
  17153. pVSection->addRow(pVHideBox);
  17154. QGroupBox *processValueBox = new QGroupBox(tr("Process Value"));
  17155. processValueBox->setLayout(pVSection);
  17156. seriesLayout->addWidget(processValueBox);
  17157. QFormLayout *sVSection = new QFormLayout;
  17158. sVLower->setDecimals(1);
  17159. sVLower->setMinimum(0.0);
  17160. sVLower->setMaximum(999.9);
  17161. sVUpper->setDecimals(1);
  17162. sVUpper->setMinimum(0.0);
  17163. sVUpper->setMaximum(999.9);
  17164. sVSection->addRow(tr("Set value:"), sVEnabled);
  17165. sVSection->addRow(tr("Read relative address:"), sVReadAddress);
  17166. sVSection->addRow(tr("SV column name:"), sVColumnName);
  17167. sVSection->addRow(tr("Limits from device:"), deviceLimit);
  17168. sVSection->addRow(tr("Lower limit relative address:"), sVLowerAddr);
  17169. sVSection->addRow(tr("Upper limit relative address:"), sVUpperAddr);
  17170. sVSection->addRow(tr("Lower limit:"), sVLower);
  17171. sVSection->addRow(tr("Upper limit:"), sVUpper);
  17172. sVSection->addRow(tr("Output set value:"), sVWritable);
  17173. sVSection->addRow(tr("Output relative address:"), sVOutputAddr);
  17174. QCheckBox *sVHideBox = new QCheckBox(tr("Hide this channel"));
  17175. sVSection->addRow(sVHideBox);
  17176. QGroupBox *setValueBox = new QGroupBox(tr("Set Value"));
  17177. setValueBox->setLayout(sVSection);
  17178. seriesLayout->addWidget(setValueBox);
  17179. masterLayout->addLayout(portAndDeviceLayout);
  17180. masterLayout->addLayout(seriesLayout);
  17181. form->setLayout(masterLayout);
  17182. @<Get device configuration data for current node@>@;
  17183. for(int i = 0; i < configData.size(); i++)
  17184. {
  17185. node = configData.at(i).toElement();
  17186. if(node.attribute("name") == "port")
  17187. {
  17188. QString portname = node.attribute("value");
  17189. int idx = port->findText(portname);
  17190. if(idx >= 0)
  17191. {
  17192. port->setCurrentIndex(idx);
  17193. }
  17194. else
  17195. {
  17196. port->addItem(portname);
  17197. }
  17198. }
  17199. else if(node.attribute("name") == "baud")
  17200. {
  17201. baud->setCurrentIndex(baud->findText(node.attribute("value")));
  17202. }
  17203. else if(node.attribute("name") == "parity")
  17204. {
  17205. parity->setCurrentIndex(parity->findData(node.attribute("value")));
  17206. }
  17207. else if(node.attribute("name") == "flow")
  17208. {
  17209. flow->setCurrentIndex(flow->findData(node.attribute("value")));
  17210. }
  17211. else if(node.attribute("name") == "stop")
  17212. {
  17213. stop->setCurrentIndex(stop->findData(node.attribute("value")));
  17214. }
  17215. else if(node.attribute("name") == "station")
  17216. {
  17217. station->setValue(node.attribute("value").toInt());
  17218. }
  17219. else if(node.attribute("name") == "decimalQuery")
  17220. {
  17221. if(node.attribute("value") == "true")
  17222. {
  17223. decimalQuery->setChecked(true);
  17224. }
  17225. else
  17226. {
  17227. decimalQuery->setChecked(false);
  17228. }
  17229. }
  17230. else if(node.attribute("name") == "decimalAddress")
  17231. {
  17232. decimalAddress->setValue(node.attribute("value").toInt());
  17233. }
  17234. else if(node.attribute("name") == "decimalPosition")
  17235. {
  17236. decimalPosition->setValue(node.attribute("value").toInt());
  17237. }
  17238. else if(node.attribute("name") == "unitQuery")
  17239. {
  17240. if(node.attribute("value") == "true")
  17241. {
  17242. unitQuery->setChecked(true);
  17243. }
  17244. else
  17245. {
  17246. unitQuery->setChecked(false);
  17247. }
  17248. }
  17249. else if(node.attribute("name") == "unitAddress")
  17250. {
  17251. unitAddress->setValue(node.attribute("value").toInt());
  17252. }
  17253. else if(node.attribute("name") == "valueF")
  17254. {
  17255. valueF->setValue(node.attribute("value").toInt());
  17256. }
  17257. else if(node.attribute("name") == "valueC")
  17258. {
  17259. valueC->setValue(node.attribute("value").toInt());
  17260. }
  17261. else if(node.attribute("name") == "fixedUnit")
  17262. {
  17263. fixedUnit->setCurrentIndex(fixedUnit->findText(node.attribute("value")));
  17264. }
  17265. else if(node.attribute("name") == "pVAddress")
  17266. {
  17267. pVAddress->setValue(node.attribute("value").toInt());
  17268. }
  17269. else if(node.attribute("name") == "sVEnabled")
  17270. {
  17271. if(node.attribute("value") == "true")
  17272. {
  17273. sVEnabled->setChecked(true);
  17274. }
  17275. else
  17276. {
  17277. sVEnabled->setChecked(false);
  17278. }
  17279. }
  17280. else if(node.attribute("name") == "sVReadAddress")
  17281. {
  17282. sVReadAddress->setValue(node.attribute("value").toInt());
  17283. }
  17284. else if(node.attribute("name") == "deviceLimit")
  17285. {
  17286. if(node.attribute("value") == "true")
  17287. {
  17288. deviceLimit->setChecked(true);
  17289. }
  17290. else
  17291. {
  17292. deviceLimit->setChecked(false);
  17293. }
  17294. }
  17295. else if(node.attribute("name") == "sVLowerAddr")
  17296. {
  17297. sVLowerAddr->setValue(node.attribute("value").toInt());
  17298. }
  17299. else if(node.attribute("name") == "sVUpperAddr")
  17300. {
  17301. sVUpperAddr->setValue(node.attribute("value").toInt());
  17302. }
  17303. else if(node.attribute("name") == "sVLower")
  17304. {
  17305. sVLower->setValue(node.attribute("value").toDouble());
  17306. }
  17307. else if(node.attribute("name") == "sVUpper")
  17308. {
  17309. sVUpper->setValue(node.attribute("value").toDouble());
  17310. }
  17311. else if(node.attribute("name") == "sVWritable")
  17312. {
  17313. if(node.attribute("value") == "true")
  17314. {
  17315. sVWritable->setChecked(true);
  17316. }
  17317. else
  17318. {
  17319. sVWritable->setChecked(false);
  17320. }
  17321. }
  17322. else if(node.attribute("name") == "sVOutputAddr")
  17323. {
  17324. sVOutputAddr->setValue(node.attribute("value").toInt());
  17325. }
  17326. else if(node.attribute("name") == "pvcolname")
  17327. {
  17328. pVColumnName->setText(node.attribute("value"));
  17329. }
  17330. else if(node.attribute("name") == "svcolname")
  17331. {
  17332. sVColumnName->setText(node.attribute("value"));
  17333. }
  17334. else if(node.attribute("name") == "pvhidden")
  17335. {
  17336. pVHideBox->setChecked(node.attribute("value") == "true");
  17337. }
  17338. else if(node.attribute("name") == "svhidden")
  17339. {
  17340. sVHideBox->setChecked(node.attribute("value") == "true");
  17341. }
  17342. }
  17343. updatePort(port->currentText());
  17344. updateBaudRate(baud->currentText());
  17345. updateParity(parity->itemData(parity->currentIndex()).toString());
  17346. updateFlowControl(flow->itemData(flow->currentIndex()).toString());
  17347. updateStopBits(stop->itemData(stop->currentIndex()).toString());
  17348. updateStation(station->value());
  17349. updateFixedDecimal(decimalQuery->isChecked());
  17350. updateDecimalAddress(decimalAddress->value());
  17351. updateDecimalPosition(decimalPosition->value());
  17352. updateFixedUnit(unitQuery->isChecked());
  17353. updateUnitAddress(unitAddress->value());
  17354. updateValueForF(valueF->value());
  17355. updateValueForC(valueC->value());
  17356. updateUnit(fixedUnit->currentText());
  17357. updatePVAddress(pVAddress->value());
  17358. updateSVEnabled(sVEnabled->isChecked());
  17359. updateSVReadAddress(sVReadAddress->value());
  17360. updateDeviceLimit(deviceLimit->isChecked());
  17361. updateSVLowerAddress(sVLowerAddr->value());
  17362. updateSVUpperAddress(sVUpperAddr->value());
  17363. updateSVLower(sVLower->value());
  17364. updateSVUpper(sVUpper->value());
  17365. updateSVWritable(sVWritable->isChecked());
  17366. updateSVWriteAddress(sVOutputAddr->value());
  17367. updatePVColumnName(pVColumnName->text());
  17368. updateSVColumnName(sVColumnName->text());
  17369. updatePVHidden(pVHideBox->isChecked());
  17370. updateSVHidden(sVHideBox->isChecked());
  17371. connect(port, SIGNAL(currentIndexChanged(QString)), this, SLOT(updatePort(QString)));
  17372. connect(port, SIGNAL(editTextChanged(QString)), this, SLOT(updatePort(QString)));
  17373. connect(baud, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateBaudRate(QString)));
  17374. connect(parity, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateParity(QString)));
  17375. connect(flow, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateFlowControl(QString)));
  17376. connect(stop, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateStopBits(QString)));
  17377. connect(station, SIGNAL(valueChanged(int)), this, SLOT(updateStation(int)));
  17378. connect(decimalQuery, SIGNAL(toggled(bool)), this, SLOT(updateFixedDecimal(bool)));
  17379. connect(decimalAddress, SIGNAL(valueChanged(int)), this, SLOT(updateDecimalAddress(int)));
  17380. connect(decimalPosition, SIGNAL(valueChanged(int)), this, SLOT(updateDecimalPosition(int)));
  17381. connect(unitQuery, SIGNAL(toggled(bool)), this, SLOT(updateFixedUnit(bool)));
  17382. connect(unitAddress, SIGNAL(valueChanged(int)), this, SLOT(updateUnitAddress(int)));
  17383. connect(valueF, SIGNAL(valueChanged(int)), this, SLOT(updateValueForF(int)));
  17384. connect(valueC, SIGNAL(valueChanged(int)), this, SLOT(updateValueForC(int)));
  17385. connect(fixedUnit, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateUnit(QString)));
  17386. connect(pVAddress, SIGNAL(valueChanged(int)), this, SLOT(updatePVAddress(int)));
  17387. connect(sVEnabled, SIGNAL(toggled(bool)), this, SLOT(updateSVEnabled(bool)));
  17388. connect(sVReadAddress, SIGNAL(valueChanged(int)), this, SLOT(updateSVReadAddress(int)));
  17389. connect(deviceLimit, SIGNAL(toggled(bool)), this, SLOT(updateDeviceLimit(bool)));
  17390. connect(sVLowerAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVLowerAddress(int)));
  17391. connect(sVUpperAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVUpperAddress(int)));
  17392. connect(sVLower, SIGNAL(valueChanged(double)), this, SLOT(updateSVLower(double)));
  17393. connect(sVUpper, SIGNAL(valueChanged(double)), this, SLOT(updateSVUpper(double)));
  17394. connect(sVWritable, SIGNAL(toggled(bool)), this, SLOT(updateSVWritable(bool)));
  17395. connect(sVOutputAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVWriteAddress(int)));
  17396. connect(pVColumnName, SIGNAL(textEdited(QString)), this, SLOT(updatePVColumnName(QString)));
  17397. connect(sVColumnName, SIGNAL(textEdited(QString)), this, SLOT(updateSVColumnName(QString)));
  17398. connect(pVHideBox, SIGNAL(toggled(bool)), this, SLOT(updatePVHidden(bool)));
  17399. connect(sVHideBox, SIGNAL(toggled(bool)), this, SLOT(updateSVHidden(bool)));
  17400. layout->addWidget(form);
  17401. setLayout(layout);
  17402. }
  17403. void ModbusConfigurator::updatePort(const QString &newPort)
  17404. {
  17405. updateAttribute("port", newPort);
  17406. }
  17407. void ModbusConfigurator::updateBaudRate(const QString &newRate)
  17408. {
  17409. updateAttribute("baud", newRate);
  17410. }
  17411. void ModbusConfigurator::updateParity(const QString &)
  17412. {
  17413. updateAttribute("parity", parity->itemData(parity->currentIndex()).toString());
  17414. }
  17415. void ModbusConfigurator::updateFlowControl(const QString &)
  17416. {
  17417. updateAttribute("flow", flow->itemData(flow->currentIndex()).toString());
  17418. }
  17419. void ModbusConfigurator::updateStopBits(const QString &)
  17420. {
  17421. updateAttribute("stop", stop->itemData(stop->currentIndex()).toString());
  17422. }
  17423. void ModbusConfigurator::updateStation(int station)
  17424. {
  17425. updateAttribute("station", QString("%1").arg(station));
  17426. }
  17427. void ModbusConfigurator::updateFixedDecimal(bool fixed)
  17428. {
  17429. updateAttribute("decimalQuery", fixed ? "true" : "false");
  17430. }
  17431. void ModbusConfigurator::updateDecimalAddress(int address)
  17432. {
  17433. updateAttribute("decimalAddress", QString("%1").arg(address));
  17434. }
  17435. void ModbusConfigurator::updateDecimalPosition(int position)
  17436. {
  17437. updateAttribute("decimalPosition", QString("%1").arg(position));
  17438. }
  17439. void ModbusConfigurator::updateFixedUnit(bool fixed)
  17440. {
  17441. updateAttribute("unitQuery", fixed ? "true" : "false");
  17442. }
  17443. void ModbusConfigurator::updateUnitAddress(int address)
  17444. {
  17445. updateAttribute("unitAddress", QString("%1").arg(address));
  17446. }
  17447. void ModbusConfigurator::updateValueForF(int value)
  17448. {
  17449. updateAttribute("valueF", QString("%1").arg(value));
  17450. }
  17451. void ModbusConfigurator::updateValueForC(int value)
  17452. {
  17453. updateAttribute("valueC", QString("%1").arg(value));
  17454. }
  17455. void ModbusConfigurator::updateUnit(const QString &newUnit)
  17456. {
  17457. updateAttribute("fixedUnit", newUnit);
  17458. }
  17459. void ModbusConfigurator::updatePVAddress(int address)
  17460. {
  17461. updateAttribute("pVAddress", QString("%1").arg(address));
  17462. }
  17463. void ModbusConfigurator::updateSVEnabled(bool enabled)
  17464. {
  17465. updateAttribute("sVEnabled", enabled ? "true" : "false");
  17466. }
  17467. void ModbusConfigurator::updateSVReadAddress(int address)
  17468. {
  17469. updateAttribute("sVReadAddress", QString("%1").arg(address));
  17470. }
  17471. void ModbusConfigurator::updateDeviceLimit(bool query)
  17472. {
  17473. updateAttribute("deviceLimit", query ? "true" : "false");
  17474. }
  17475. void ModbusConfigurator::updateSVLowerAddress(int address)
  17476. {
  17477. updateAttribute("sVLowerAddr", QString("%1").arg(address));
  17478. }
  17479. void ModbusConfigurator::updateSVUpperAddress(int address)
  17480. {
  17481. updateAttribute("sVUpperAddr", QString("%1").arg(address));
  17482. }
  17483. void ModbusConfigurator::updateSVLower(double value)
  17484. {
  17485. updateAttribute("sVLower", QString("%1").arg(value));
  17486. }
  17487. void ModbusConfigurator::updateSVUpper(double value)
  17488. {
  17489. updateAttribute("sVUpper", QString("%1").arg(value));
  17490. }
  17491. void ModbusConfigurator::updateSVWritable(bool canWriteSV)
  17492. {
  17493. updateAttribute("sVWritable", canWriteSV ? "true" : "false");
  17494. }
  17495. void ModbusConfigurator::updateSVWriteAddress(int address)
  17496. {
  17497. updateAttribute("sVOutputAddr", QString("%1").arg(address));
  17498. }
  17499. void ModbusConfigurator::updatePVColumnName(const QString &name)
  17500. {
  17501. updateAttribute("pvcolname", name);
  17502. }
  17503. void ModbusConfigurator::updateSVColumnName(const QString &name)
  17504. {
  17505. updateAttribute("svcolname", name);
  17506. }
  17507. void ModbusConfigurator::updatePVHidden(bool hidden)
  17508. {
  17509. updateAttribute("pvhidden", hidden ? "true" : "false");
  17510. }
  17511. void ModbusConfigurator::updateSVHidden(bool hidden)
  17512. {
  17513. updateAttribute("svhidden", hidden ? "true" : "false");
  17514. }
  17515. @ This is registered with the configuration system.
  17516. @<Register device configuration widgets@>=
  17517. app.registerDeviceConfigurationWidget("modbusrtu", ModbusConfigurator::staticMetaObject);
  17518. @ A |NodeInserter| for the driver configuration widget is also needed.
  17519. @<Register top level device configuration nodes@>=
  17520. inserter = new NodeInserter(tr("Modbus RTU Device"), tr("Modbus RTU Device"), "modbusrtu", NULL);
  17521. topLevelNodeInserters.append(inserter);
  17522. @i modbus.w
  17523. @i unsupportedserial.w
  17524. @i phidgets.w
  17525. @i phidget22.w
  17526. @* Configuration widget for a calibrated data series.
  17527. \noindent This control is used for adding a |LinearSplineInterpolator| to the
  17528. logging view.
  17529. @<Class declarations@>=
  17530. class LinearSplineInterpolationConfWidget : public BasicDeviceConfigurationWidget
  17531. {
  17532. @[Q_OBJECT@]@/
  17533. public:@/
  17534. @[Q_INVOKABLE@]@, LinearSplineInterpolationConfWidget(DeviceTreeModel *model,
  17535. const QModelIndex &index);
  17536. @[private slots@]:@/
  17537. void updateSourceColumn(const QString &source);
  17538. void updateDestinationColumn(const QString &dest);
  17539. void updateKnots();
  17540. private:@/
  17541. SaltModel *tablemodel;
  17542. };
  17543. @ This is configured by specifying a source column name, a destination column
  17544. name, and a two column table. Note that while we only have one widget handling
  17545. the mapping data, we store each column of the table in its own attribute.
  17546. @<LinearSplineInterpolationConfWidget implementation@>=
  17547. LinearSplineInterpolationConfWidget::LinearSplineInterpolationConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  17548. : BasicDeviceConfigurationWidget(model, index), tablemodel(new SaltModel(2))
  17549. {
  17550. QFormLayout *layout = new QFormLayout;
  17551. QLineEdit *source = new QLineEdit;
  17552. layout->addRow(tr("Source column name:"), source);
  17553. QLineEdit *destination = new QLineEdit;
  17554. layout->addRow(tr("Destination column name:"), destination);
  17555. tablemodel->setHeaderData(0, Qt::Horizontal, "Input");
  17556. tablemodel->setHeaderData(1, Qt::Horizontal, "Output");
  17557. QTableView *mappingTable = new QTableView;
  17558. mappingTable->setModel(tablemodel);
  17559. NumericDelegate *delegate = new NumericDelegate;
  17560. mappingTable->setItemDelegate(delegate);
  17561. layout->addRow(tr("Mapping data:"), mappingTable);
  17562. @<Get device configuration data for current node@>@;
  17563. for(int i = 0; i < configData.size(); i++)
  17564. {
  17565. node = configData.at(i).toElement();
  17566. if(node.attribute("name") == "source")
  17567. {
  17568. source->setText(node.attribute("value"));
  17569. }
  17570. else if(node.attribute("name") == "destination")
  17571. {
  17572. destination->setText(node.attribute("value"));
  17573. }
  17574. else if(node.attribute("name") == "sourcevalues")
  17575. {
  17576. @<Convert numeric array literal to list@>@;
  17577. int column = 0;
  17578. @<Populate model column from list@>@;
  17579. }
  17580. else if(node.attribute("name") == "destinationvalues")
  17581. {
  17582. @<Convert numeric array literal to list@>@;
  17583. int column = 1;
  17584. @<Populate model column from list@>@;
  17585. }
  17586. }
  17587. updateSourceColumn(source->text());
  17588. updateDestinationColumn(destination->text());
  17589. updateKnots();
  17590. connect(source, SIGNAL(textEdited(QString)), this, SLOT(updateSourceColumn(QString)));
  17591. connect(destination, SIGNAL(textEdited(QString)), this, SLOT(updateDestinationColumn(QString)));
  17592. connect(tablemodel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(updateKnots()));
  17593. setLayout(layout);
  17594. }
  17595. @ The saved data will have come from a previous call to
  17596. |SaltModel::arrayLiteral()| to repopulate the model we need to strip off the
  17597. the start and end of the strings and split them back into separate elements.
  17598. @<Convert numeric array literal to list@>=
  17599. QString data = node.attribute("value");
  17600. if(data.length() > 3)
  17601. {
  17602. data.chop(2);
  17603. data = data.remove(0, 2);
  17604. }
  17605. QStringList itemList = data.split(",");
  17606. @ Once the saved string has been split, the values can be inserted into the
  17607. model.
  17608. @<Populate model column from list@>=
  17609. for(int j = 0; j < itemList.size(); j++)
  17610. {
  17611. tablemodel->setData(tablemodel->index(j, column),
  17612. QVariant(itemList.at(j).toDouble()),
  17613. Qt::DisplayRole);
  17614. }
  17615. @ When data in the table is changed we simply overwrite any previously saved
  17616. data with the current data.
  17617. @<LinearSplineInterpolationConfWidget implementation@>=
  17618. void LinearSplineInterpolationConfWidget::updateKnots()
  17619. {
  17620. updateAttribute("sourcevalues", tablemodel->arrayLiteral(0, Qt::DisplayRole));
  17621. updateAttribute("destinationvalues", tablemodel->arrayLiteral(1, Qt::DisplayRole));
  17622. }
  17623. void LinearSplineInterpolationConfWidget::updateSourceColumn(const QString &source)
  17624. {
  17625. updateAttribute("source", source);
  17626. }
  17627. void LinearSplineInterpolationConfWidget::updateDestinationColumn(const QString &dest)
  17628. {
  17629. updateAttribute("destination", dest);
  17630. }
  17631. @ The widget is registered with the configuration system.
  17632. @<Register device configuration widgets@>=
  17633. app.registerDeviceConfigurationWidget("linearspline", LinearSplineInterpolationConfWidget::staticMetaObject);
  17634. @* Additional Timers.
  17635. \noindent \pn{} 1.6.4 adds support for more timer indicators than just the
  17636. default batch timer. Three new timer types are supported. The first is a
  17637. cooling timer. This is a timer that is initially set to 0, but at the end of a
  17638. batch this is set to a configured time and starts counting down. There are no
  17639. data logging requirements and this is purely a convenience feature, but one
  17640. that supports product and personnel safety best practices as it helps to
  17641. eliminate the practice of a person reaching into the cooling tray as it
  17642. agitates to test if the coffee has cooled.
  17643. @<Class declarations@>=
  17644. class CoolingTimerConfWidget : public BasicDeviceConfigurationWidget
  17645. {
  17646. @[Q_OBJECT@]@/
  17647. public:@/
  17648. @[Q_INVOKABLE@]@, CoolingTimerConfWidget(DeviceTreeModel *model,
  17649. const QModelIndex &index);
  17650. @[private slots@]:@/
  17651. void updateResetTime(QTime time);
  17652. };
  17653. @ The only configurable detail is the vaue the timer should reset to. For this
  17654. a |QTimeEdit| is fine.
  17655. @<CoolingTimerConfWidget implementation@>=
  17656. CoolingTimerConfWidget::CoolingTimerConfWidget(DeviceTreeModel *model,
  17657. const QModelIndex &index)
  17658. : BasicDeviceConfigurationWidget(model, index)
  17659. {
  17660. QHBoxLayout *layout = new QHBoxLayout;
  17661. QLabel *label = new QLabel(tr("Cooling Time: "));
  17662. QTimeEdit *editor = new QTimeEdit;
  17663. editor->setDisplayFormat("mm:ss");
  17664. @<Get device configuration data for current node@>@;
  17665. for(int i = 0; i < configData.size(); i++)
  17666. {
  17667. node = configData.at(i).toElement();
  17668. if(node.attribute("name") == "reset")
  17669. {
  17670. editor->setTime(QTime::fromString(node.attribute("value"), "mm:ss"));
  17671. }
  17672. }
  17673. updateResetTime(editor->time());
  17674. connect(editor, SIGNAL(timeChanged(QTime)),
  17675. this, SLOT(updateResetTime(QTime)));
  17676. layout->addWidget(label);
  17677. layout->addWidget(editor);
  17678. setLayout(layout);
  17679. }
  17680. void CoolingTimerConfWidget::updateResetTime(QTime time)
  17681. {
  17682. updateAttribute("reset", time.toString("mm:ss"));
  17683. }
  17684. @ The widget is registered with the configuration system.
  17685. @<Register device configuration widgets@>=
  17686. app.registerDeviceConfigurationWidget("coolingtimer",
  17687. CoolingTimerConfWidget::staticMetaObject);
  17688. @ The implementation chunk for now is in the main source file.
  17689. @<Class implementations@>=
  17690. @<CoolingTimerConfWidget implementation@>
  17691. @ The other two timer types are intended for measuring ranges of interest
  17692. within a batch. These have more configuration options. First is the range
  17693. timer. Someone setting this up needs to decide how the timer is started.
  17694. Sensible options include starting the timer at the start of the batch,
  17695. starting the timer when a button is pressed, or starting the timer when a set
  17696. point is reached on the ascent of a named data series. Stopping the timer is
  17697. also a configurable concern. This will be stopped at the end of the batch,
  17698. but it might be stopped sooner on reaching some threshold or when a button is
  17699. pressed. There are also questions of how the information is persisted with the
  17700. roasting records.
  17701. @<Class declarations@>=
  17702. class RangeTimerConfWidget : public BasicDeviceConfigurationWidget
  17703. {
  17704. @[Q_OBJECT@]@;
  17705. public:@/
  17706. @[Q_INVOKABLE@]@, RangeTimerConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  17707. @[private slots@]:@/
  17708. void updateStartButtonText(const QString &text);
  17709. void updateStopButtonText(const QString &text);
  17710. void updateStartColumnName(const QString &text);
  17711. void updateStopColumnName(const QString &text);
  17712. void updateStartValue(const QString &text);
  17713. void updateStopValue(const QString &text);
  17714. void updateStartTrigger(int option);
  17715. void updateStopTrigger(int option);
  17716. };
  17717. @ The constructor sets up controls for configuring these details.
  17718. @<RangeTimerConfWidget implementation@>=
  17719. RangeTimerConfWidget::RangeTimerConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  17720. : BasicDeviceConfigurationWidget(model, index)
  17721. {
  17722. QVBoxLayout *layout = new QVBoxLayout;
  17723. QGroupBox *startConfigurationGroup = new QGroupBox(tr("Start trigger"));
  17724. QRadioButton *startBatchOption = new QRadioButton(tr("Start of batch"));
  17725. QRadioButton *buttonOption = new QRadioButton(tr("Manual"));
  17726. QRadioButton *thresholdOption = new QRadioButton(tr("At temperature"));
  17727. QButtonGroup *startOptionGroup = new QButtonGroup;
  17728. startOptionGroup->addButton(startBatchOption, 1);
  17729. startOptionGroup->addButton(buttonOption, 2);
  17730. startOptionGroup->addButton(thresholdOption, 3);
  17731. startBatchOption->setChecked(true);
  17732. QGridLayout *startOptions = new QGridLayout;
  17733. startOptions->addWidget(startBatchOption, 0, 0);
  17734. startOptions->addWidget(buttonOption, 1, 0);
  17735. startOptions->addWidget(thresholdOption, 2, 0);
  17736. QLabel *buttonTextLabel = new QLabel(tr("Button Text: "));
  17737. QLineEdit *buttonTextEdit = new QLineEdit;
  17738. QHBoxLayout *buttonTextOptions = new QHBoxLayout;
  17739. buttonTextOptions->addWidget(buttonTextLabel);
  17740. buttonTextOptions->addWidget(buttonTextEdit);
  17741. startOptions->addLayout(buttonTextOptions, 1, 1);
  17742. QFormLayout *thresholdOptions = new QFormLayout;
  17743. QLineEdit *startColumnName = new QLineEdit;
  17744. QLineEdit *startValue = new QLineEdit;
  17745. thresholdOptions->addRow(tr("Column Name: "), startColumnName);
  17746. thresholdOptions->addRow(tr("Value: "), startValue);
  17747. startOptions->addLayout(thresholdOptions, 2, 1);
  17748. startConfigurationGroup->setLayout(startOptions);
  17749. layout->addWidget(startConfigurationGroup);
  17750. QGroupBox *stopConfigurationGroup = new QGroupBox(tr("Stop trigger"));
  17751. QRadioButton *stopBatchOption = new QRadioButton(tr("End of batch"));
  17752. QRadioButton *stopButtonOption = new QRadioButton(tr("Manual"));
  17753. QRadioButton *stopThresholdOption = new QRadioButton(tr("At temperature"));
  17754. QButtonGroup *stopOptionGroup = new QButtonGroup;
  17755. stopOptionGroup->addButton(stopBatchOption, 1);
  17756. stopOptionGroup->addButton(stopButtonOption, 2);
  17757. stopOptionGroup->addButton(stopThresholdOption, 3);
  17758. stopBatchOption->setChecked(true);
  17759. QGridLayout *stopOptions = new QGridLayout;
  17760. stopOptions->addWidget(stopBatchOption, 0, 0);
  17761. stopOptions->addWidget(stopButtonOption, 1, 0);
  17762. stopOptions->addWidget(stopThresholdOption, 2, 0);
  17763. QLabel *stopButtonLabel = new QLabel(tr("Button Text: "));
  17764. QLineEdit *stopButtonEdit = new QLineEdit;
  17765. QHBoxLayout *stopButtonTextOptions = new QHBoxLayout;
  17766. stopButtonTextOptions->addWidget(stopButtonLabel);
  17767. stopButtonTextOptions->addWidget(stopButtonEdit);
  17768. stopOptions->addLayout(stopButtonTextOptions, 1, 1);
  17769. QLineEdit *stopColumnName = new QLineEdit;
  17770. QLineEdit *stopValue = new QLineEdit;
  17771. QFormLayout *stopThresholdOptions = new QFormLayout;
  17772. stopThresholdOptions->addRow(tr("Column Name: "), stopColumnName);
  17773. stopThresholdOptions->addRow(tr("Value: "), stopValue);
  17774. stopOptions->addLayout(stopThresholdOptions, 2, 1);
  17775. stopConfigurationGroup->setLayout(stopOptions);
  17776. layout->addWidget(stopConfigurationGroup);
  17777. @<Get device configuration data for current node@>@;
  17778. for(int i = 0; i < configData.size(); i++)
  17779. {
  17780. node = configData.at(i).toElement();
  17781. if(node.attribute("name") == "startbuttontext")
  17782. {
  17783. buttonTextEdit->setText(node.attribute("value"));
  17784. }
  17785. else if(node.attribute("name") == "stopbuttontext")
  17786. {
  17787. stopButtonEdit->setText(node.attribute("value"));
  17788. }
  17789. else if(node.attribute("name") == "startcolumnname")
  17790. {
  17791. startColumnName->setText(node.attribute("value"));
  17792. }
  17793. else if(node.attribute("name") == "stopcolumnname")
  17794. {
  17795. stopColumnName->setText(node.attribute("value"));
  17796. }
  17797. else if(node.attribute("name") == "startvalue")
  17798. {
  17799. startValue->setText(node.attribute("value"));
  17800. }
  17801. else if(node.attribute("name") == "stopvalue")
  17802. {
  17803. stopValue->setText(node.attribute("value"));
  17804. }
  17805. else if(node.attribute("name") == "starttrigger")
  17806. {
  17807. if(node.attribute("value") == "batch")
  17808. {
  17809. startBatchOption->setChecked(true);
  17810. }
  17811. else if(node.attribute("value") == "manual")
  17812. {
  17813. buttonOption->setChecked(true);
  17814. }
  17815. else if(node.attribute("value") == "value")
  17816. {
  17817. thresholdOption->setChecked(true);
  17818. }
  17819. }
  17820. else if(node.attribute("name") == "stoptrigger")
  17821. {
  17822. if(node.attribute("value") == "batch")
  17823. {
  17824. stopBatchOption->setChecked(true);
  17825. }
  17826. else if(node.attribute("value") == "manual")
  17827. {
  17828. stopButtonOption->setChecked(true);
  17829. }
  17830. else if(node.attribute("value") == "value")
  17831. {
  17832. stopThresholdOption->setChecked(true);
  17833. }
  17834. }
  17835. }
  17836. updateStartButtonText(buttonTextEdit->text());
  17837. updateStopButtonText(stopButtonEdit->text());
  17838. updateStartColumnName(startColumnName->text());
  17839. updateStopColumnName(stopColumnName->text());
  17840. updateStartValue(startValue->text());
  17841. updateStopValue(stopValue->text());
  17842. updateStartTrigger(startOptionGroup->checkedId());
  17843. updateStopTrigger(stopOptionGroup->checkedId());
  17844. setLayout(layout);
  17845. connect(buttonTextEdit, SIGNAL(textChanged(QString)),
  17846. this, SLOT(updateStartButtonText(QString)));
  17847. connect(stopButtonEdit, SIGNAL(textChanged(QString)),
  17848. this, SLOT(updateStopButtonText(QString)));
  17849. connect(startColumnName, SIGNAL(textChanged(QString)),
  17850. this, SLOT(updateStartColumnName(QString)));
  17851. connect(stopColumnName, SIGNAL(textChanged(QString)),
  17852. this, SLOT(updateStopColumnName(QString)));
  17853. connect(startValue, SIGNAL(textChanged(QString)),
  17854. this, SLOT(updateStartValue(QString)));
  17855. connect(stopValue, SIGNAL(textChanged(QString)),
  17856. this, SLOT(updateStopValue(QString)));
  17857. connect(startOptionGroup, SIGNAL(buttonClicked(int)),
  17858. this, SLOT(updateStartTrigger(int)));
  17859. connect(stopOptionGroup, SIGNAL(buttonClicked(int)),
  17860. this, SLOT(updateStopTrigger(int)));
  17861. }
  17862. @ Small methods update the configuration as usual.
  17863. @<RangeTimerConfWidget implementation@>=
  17864. void RangeTimerConfWidget::updateStartButtonText(const QString &text)
  17865. {
  17866. updateAttribute("startbuttontext", text);
  17867. }
  17868. void RangeTimerConfWidget::updateStopButtonText(const QString &text)
  17869. {
  17870. updateAttribute("stopbuttontext", text);
  17871. }
  17872. void RangeTimerConfWidget::updateStartColumnName(const QString &text)
  17873. {
  17874. updateAttribute("startcolumnname", text);
  17875. }
  17876. void RangeTimerConfWidget::updateStopColumnName(const QString &text)
  17877. {
  17878. updateAttribute("stopcolumnname", text);
  17879. }
  17880. void RangeTimerConfWidget::updateStartValue(const QString &text)
  17881. {
  17882. updateAttribute("startvalue", text);
  17883. }
  17884. void RangeTimerConfWidget::updateStopValue(const QString &text)
  17885. {
  17886. updateAttribute("stopvalue", text);
  17887. }
  17888. void RangeTimerConfWidget::updateStartTrigger(int option)
  17889. {
  17890. switch(option)
  17891. {
  17892. case 1:
  17893. updateAttribute("starttrigger", "batch");
  17894. break;
  17895. case 2:
  17896. updateAttribute("starttrigger", "manual");
  17897. break;
  17898. case 3:
  17899. updateAttribute("starttrigger", "value");
  17900. break;
  17901. default:
  17902. break;
  17903. }
  17904. }
  17905. void RangeTimerConfWidget::updateStopTrigger(int option)
  17906. {
  17907. switch(option)
  17908. {
  17909. case 1:
  17910. updateAttribute("stoptrigger", "batch");
  17911. break;
  17912. case 2:
  17913. updateAttribute("stoptrigger", "manual");
  17914. break;
  17915. case 3:
  17916. updateAttribute("stoptrigger", "value");
  17917. break;
  17918. default:
  17919. break;
  17920. }
  17921. }
  17922. @ The widget is registered with the configuration system.
  17923. @<Register device configuration widgets@>=
  17924. app.registerDeviceConfigurationWidget("rangetimer",
  17925. RangeTimerConfWidget::staticMetaObject);
  17926. @ The implementation chunk for now is in the main source file.
  17927. @<Class implementations@>=
  17928. @<RangeTimerConfWidget implementation@>
  17929. @ The multirange timer is a little different. To keep configuration tractible,
  17930. this is slightly less general purpose than the range timer and only supports
  17931. automatic triggering on a single data series.
  17932. @<Class declarations@>=
  17933. class MultiRangeTimerConfWidget : public BasicDeviceConfigurationWidget
  17934. {
  17935. @[Q_OBJECT@]@/
  17936. public:@/
  17937. @[Q_INVOKABLE@]@, MultiRangeTimerConfWidget(DeviceTreeModel *model,
  17938. const QModelIndex &index);
  17939. @[private slots@]:@/
  17940. void updateColumnName(const QString &text);
  17941. void updateRangeData();
  17942. private:@/
  17943. SaltModel *tablemodel;
  17944. };
  17945. @ These limitations allow a rather small set of controls for configuration. A
  17946. line edit to specify the data series used for automatic triggering and a table
  17947. which specifies the name of the timed range and an ending temperature.
  17948. @<MultiRangeTimerConfWidget implementation@>=
  17949. MultiRangeTimerConfWidget::MultiRangeTimerConfWidget(DeviceTreeModel *model,
  17950. const QModelIndex &index)
  17951. : BasicDeviceConfigurationWidget(model, index), tablemodel(new SaltModel(2))
  17952. {
  17953. QFormLayout *layout = new QFormLayout;
  17954. QLineEdit *trigger = new QLineEdit;
  17955. layout->addRow(tr("Trigger column name:"), trigger);
  17956. tablemodel->setHeaderData(0, Qt::Horizontal, "Range Name");
  17957. tablemodel->setHeaderData(1, Qt::Horizontal, "End Temperature");
  17958. QTableView *rangeTable = new QTableView;
  17959. rangeTable->setModel(tablemodel);
  17960. layout->addRow(tr("Range data:"), rangeTable);
  17961. @<Get device configuration data for current node@>@;
  17962. for(int i = 0; i < configData.size(); i++)
  17963. {
  17964. node = configData.at(i).toElement();
  17965. if(node.attribute("name") == "trigger")
  17966. {
  17967. trigger->setText(node.attribute("value"));
  17968. }
  17969. else if(node.attribute("name") == "rangenames")
  17970. {
  17971. QString data = node.attribute("value");
  17972. if(data.length() > 3)
  17973. {
  17974. data.chop(2);
  17975. data = data.remove(0, 2);
  17976. }
  17977. QStringList itemList = data.split(", ");
  17978. for(int j = 0; j < itemList.size(); j++)
  17979. {
  17980. QString item = itemList.at(j);
  17981. item.chop(1);
  17982. item = item.remove(0, 1);
  17983. tablemodel->setData(tablemodel->index(j, 0),
  17984. QVariant(item), Qt::DisplayRole);
  17985. }
  17986. }
  17987. else if(node.attribute("name") == "endtemps")
  17988. {
  17989. @<Convert numeric array literal to list@>@;
  17990. int column = 1;
  17991. @<Populate model column from list@>@;
  17992. }
  17993. }
  17994. updateColumnName(trigger->text());
  17995. updateRangeData();
  17996. connect(trigger, SIGNAL(textEdited(QString)), this, SLOT(updateColumnName(QString)));
  17997. connect(tablemodel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(updateRangeData()));
  17998. setLayout(layout);
  17999. }
  18000. @ The update mechanisms are reasonably straightforward. Table updates just
  18001. refresh the entire table instead of attempting to be clever about updating only
  18002. the element that changed.
  18003. @<MultiRangeTimerConfWidget implementation@>=
  18004. void MultiRangeTimerConfWidget::updateRangeData()
  18005. {
  18006. updateAttribute("rangenames", tablemodel->quotedArrayLiteral(0, Qt::DisplayRole));
  18007. updateAttribute("endtemps", tablemodel->arrayLiteral(1, Qt::DisplayRole));
  18008. }
  18009. void MultiRangeTimerConfWidget::updateColumnName(const QString &text)
  18010. {
  18011. updateAttribute("trigger", text);
  18012. }
  18013. @ The widget is registered with the configuration system.
  18014. @<Register device configuration widgets@>=
  18015. app.registerDeviceConfigurationWidget("multirangetimer",
  18016. MultiRangeTimerConfWidget::staticMetaObject);
  18017. @ The implementation is in the main source file.
  18018. @<Class implementations@>=
  18019. @<MultiRangeTimerConfWidget implementation@>
  18020. @* Profile Translation Configuration Widget.
  18021. \noindent Configuring profile translation requires knowing which column to use
  18022. for matching purposes and the value to match.
  18023. @<Class declarations@>=
  18024. class TranslationConfWidget : public BasicDeviceConfigurationWidget
  18025. {
  18026. @[Q_OBJECT@]@;
  18027. public:@/
  18028. @[Q_INVOKABLE@]@, TranslationConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  18029. @[private slots@]:@/
  18030. void updateMatchingColumn(const QString &column);
  18031. void updateTemperature();
  18032. void updateDelay();
  18033. private:@/
  18034. QDoubleSpinBox *temperatureValue;
  18035. QComboBox *unitSelector;
  18036. QSpinBox *delaySelector;
  18037. };
  18038. @ The constructor sets up our user interface.
  18039. @<TranslationConfWidget implementation@>=
  18040. TranslationConfWidget::TranslationConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  18041. : BasicDeviceConfigurationWidget(model, index),
  18042. temperatureValue(new QDoubleSpinBox), unitSelector(new QComboBox),
  18043. delaySelector(new QSpinBox)
  18044. {
  18045. unitSelector->addItem("Fahrenheit");
  18046. unitSelector->addItem("Celsius");
  18047. temperatureValue->setMinimum(0);
  18048. temperatureValue->setMaximum(1000);
  18049. QFormLayout *layout = new QFormLayout;
  18050. QLineEdit *column = new QLineEdit;
  18051. layout->addRow(tr("Column to match:"), column);
  18052. layout->addRow(tr("Unit:"), unitSelector);
  18053. layout->addRow(tr("Value:"), temperatureValue);
  18054. layout->addRow(tr("Start of batch safety delay:"), delaySelector);
  18055. @<Get device configuration data for current node@>@;
  18056. for(int i = 0; i < configData.size(); i++)
  18057. {
  18058. node = configData.at(i).toElement();
  18059. if(node.attribute("name") == "column")
  18060. {
  18061. column->setText(node.attribute("value"));
  18062. }
  18063. else if(node.attribute("name") == "unit")
  18064. {
  18065. unitSelector->setCurrentIndex(unitSelector->findText(node.attribute("value")));
  18066. }
  18067. else if(node.attribute("name") == "value")
  18068. {
  18069. temperatureValue->setValue(node.attribute("value").toDouble());
  18070. }
  18071. else if(node.attribute("name") == "delay")
  18072. {
  18073. delaySelector->setValue(node.attribute("value").toInt());
  18074. }
  18075. }
  18076. updateMatchingColumn(column->text());
  18077. updateTemperature();
  18078. updateDelay();
  18079. connect(column, SIGNAL(textEdited(QString)), this, SLOT(updateMatchingColumn(QString)));
  18080. connect(unitSelector, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateTemperature()));
  18081. connect(temperatureValue, SIGNAL(valueChanged(double)), this, SLOT(updateTemperature()));
  18082. connect(delaySelector, SIGNAL(valueChanged(int)), this, SLOT(updateDelay()));
  18083. setLayout(layout);
  18084. }
  18085. @ To update the temperature at which to match we save both the values of the
  18086. two widgets which control this and the value in Fahrenheit so we don'@q'@>t need to
  18087. run unit conversions during view initialization.
  18088. @<TranslationConfWidget implementation@>=
  18089. void TranslationConfWidget::updateTemperature()
  18090. {
  18091. updateAttribute("unit", unitSelector->currentText());
  18092. updateAttribute("value", QString("%1").arg(temperatureValue->value()));
  18093. if(unitSelector->currentText() == "Fahrenheit")
  18094. {
  18095. updateAttribute("FValue", QString("%1").arg(temperatureValue->value()));
  18096. }
  18097. else
  18098. {
  18099. updateAttribute("FValue", QString("%1").arg(temperatureValue->value() * 9 / 5 + 32));
  18100. }
  18101. }
  18102. void TranslationConfWidget::updateMatchingColumn(const QString &column)
  18103. {
  18104. updateAttribute("column", column);
  18105. }
  18106. void TranslationConfWidget::updateDelay()
  18107. {
  18108. updateAttribute("delay", QString("%1").arg(delaySelector->value()));
  18109. }
  18110. @ This is registered with the configuration system.
  18111. @<Register device configuration widgets@>=
  18112. app.registerDeviceConfigurationWidget("translation", TranslationConfWidget::staticMetaObject);
  18113. @i rate.w
  18114. @i mergeseries.w
  18115. @i dataqsdk.w
  18116. @i scales.w
  18117. @i valueannotation.w
  18118. @i thresholdannotation.w
  18119. @i user.w
  18120. @i roastcoloredit.w
  18121. @** Local changes.
  18122. \noindent This is the end of \pn{} as distributed by its author. It is expected
  18123. that some might have need of a program like \pn, but require some modification.
  18124. The patching capabilities of \cweb{} can be used to produce these local
  18125. modifications. This section is provided for those whose change requirements are
  18126. sufficiently extensive to require the introduction of new sections to the
  18127. program.
  18128. @** Index.
  18129. \noindent Following is a list of identifiers used in \pn, with underlined
  18130. entries pointing to where \cweb{} has guessed that the identifier was defined.
  18131. All references are to section numbers instead of page numbers.
  18132. \def\nullsec{--}